fix: ChatGPT 方案第二輪審查的 P2

- 沒有正常結束的回答(response.incomplete)算失敗,那一步的工具不執行。
- 額度用完後,沒人在看的要求(例行任務、訊息管道、檢查)先不送,直到有一次成功。
- 提早更新 token 遇到網路問題時,手上還有幾分鐘的 token 照用(以前那幾分鐘每個要求都失敗)。
- 大腦的帳號狀態隨同步送到螢幕電腦(不含 token),模型選單、Bot 設定不再一律寫「未登入」。
- 螢幕電腦和手機只打開 https://auth.openai.com/ 的登入頁;手機擋彈出視窗時說明再按一次。
- 登出時憑證打不開、沒辦法撤銷,會告訴使用者去 ChatGPT 設定中斷;兩次撤銷之間隔一秒。
- 登入成功後自動抓一次模型清單。

已驗證: cargo test 全綠(chatgpt::、providers:: 新增用量上限暫停、incomplete、提早更新失敗、只開 OpenAI 登入頁)。
未驗證: 真的 ChatGPT 帳號登入與串流;螢幕電腦、手機實機(同上一個 commit)。審批路徑仍需人類簽名。

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Uirha3KhvSzysuKUobKUTR
This commit is contained in:
王性驊 2026-11-17 17:46:09 +08:00
parent a03f7c7458
commit c3e615c83c
8 changed files with 135 additions and 25 deletions

View File

@ -2676,6 +2676,7 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開)
- 錯誤:`subscription_sharing_usage_limit_exceeded` 顯示「已達用量上限(ChatGPT 方案)」和管理用量連結(chatgpt.com/settings/usage),不重試、不改用 API 金鑰;`usage_unavailable`、503 稍後重試;不支援的功能說出是哪個參數(思考模式不支援就自動拿掉再試)。
- 第一次用方案登入成功時說一次「你正在使用你的 ChatGPT 方案」。語音不能用方案。
- 螢幕電腦和手機:帳號在大腦。螢幕電腦的設定頁經 `/api/sync/chatgpt`(只有擁有者的螢幕),手機經 `/api/act/chatgpt`(只有擁有者)請大腦開始登入、登出、換帳號、看狀態;登入頁開在使用者那台,回來的那頁打不開時貼回網址,由大腦完成。大腦的狀態顯示在螢幕電腦的模型選單和 Bot 設定(不再一律寫「未登入」)。
- 額度用完之後,沒人在看的要求(例行任務、訊息管道、檢查)先不送,直到有一次要求成功;`response.incomplete` 算失敗、不執行那一步的工具。提早更新 token 失敗(網路)時,手上還有幾分鐘的 token 照用。大腦的帳號狀態隨同步送到螢幕電腦(不含 token);螢幕電腦和手機只打開 `https://auth.openai.com/` 的登入頁。登入成功後自動抓一次模型清單。
- Bot 請求登出、換帳號要先經使用者確認。目標檢查、發布前檢查找「別家模型」時,ChatGPT 方案排最後。
- 已知限制:「換帳號」會忘掉原帳號的註冊,換回來時會重新註冊一次。
- **看不到圖片的模型**:模型回「不能收圖片」(例如「At most 0 image(s)」)時,AnyBot 記住這個模型,立刻改成不附圖片重試,截圖的位置換成文字說明,Bot 不會再卡住。

View File

@ -39,4 +39,4 @@
- 能力或技能全部勾回來就是「全部」:之後新增的能力類別、新裝的技能也自動算它的。它自己的電腦一定能用,拿不掉。
- 名字或模型空白時,「建立 Bot」「儲存」按不下去。`create_bot` 建出來的 Bot 電腦工具是關的。
- 「匯出 Bot」不帶聊天記錄、金鑰和 Token。
- ChatGPT 方案:額度用完會停下來說「已達用量上限(ChatGPT 方案)」並給「管理用量」連結,不會自動改用 API 金鑰付費,也不會一直重試;沒勾同意使用方案,算登入了但不能用;在 ChatGPT 設定裡中斷連線,下一次要求才會發現,要重新登入。語音轉文字、朗讀不能用方案,還是要 OpenAI 的 API 金鑰。登入的 token 存在大腦,不會傳到螢幕電腦和手機。連到大腦的螢幕電腦:設定 › 模型 › ChatGPT 方案 按鈕一樣,登入頁開在這台;登入後那頁打不開,把網址貼進下面的欄位按「完成登入」。手機:設定 › AI 服務 › ChatGPT 方案 →「使用 ChatGPT 繼續…」,同樣貼回網址。`chatgpt_login` 的 logout、switch_account 會先跳確認卡片。
- ChatGPT 方案:額度用完會停下來說「已達用量上限(ChatGPT 方案)」並給「管理用量」連結,不會自動改用 API 金鑰付費,也不會一直重試;之後沒人在看的(例行任務、訊息管道、檢查)先不送,等你自己問的那一次成功才恢復。回答沒有正常結束(例如太長)算失敗,那一步的工具不執行;沒勾同意使用方案,算登入了但不能用;在 ChatGPT 設定裡中斷連線,下一次要求才會發現,要重新登入。語音轉文字、朗讀不能用方案,還是要 OpenAI 的 API 金鑰。登入的 token 存在大腦,不會傳到螢幕電腦和手機。連到大腦的螢幕電腦:設定 › 模型 › ChatGPT 方案 按鈕一樣,登入頁開在這台;登入後那頁打不開,把網址貼進下面的欄位按「完成登入」。手機:設定 › AI 服務 › ChatGPT 方案 →「使用 ChatGPT 繼續…」,同樣貼回網址。`chatgpt_login` 的 logout、switch_account 會先跳確認卡片。

View File

@ -2502,10 +2502,12 @@ function wireSettings(kind, st) {
// ChatGPT 方案: an account on the brain, not a key. The sign-in page opens here; the page it
// comes back to (127.0.0.1 on the brain) won't load on the phone, so its address is pasted back.
...(p.account ? [{icon: "key", label: p.ready ? "重新用 ChatGPT 登入…" : "使用 ChatGPT 繼續…", on: async () => {
// (Opened now, while the tap still counts: a window opened after waiting is blocked.)
const w = window.open("", "_blank");
if (!w) { toast("請允許這個網頁開新視窗,再按一次"); return; }
const v = await act("chatgpt", {action: "login"}, false);
if (!v || !v.url) { if (w) w.close(); if (v && v.text) toast(v.text); return; }
if (w) w.location = v.url; else location.assign(v.url);
if (!v || !v.url || !String(v.url).startsWith("https://auth.openai.com/")) { w.close(); if (v && v.text) toast(v.text); return; }
w.location = v.url;
const cb = await ask("登入並同意後,那一頁打不開的話,把它的網址整個貼在這裡", "", "http://127.0.0.1:1455/auth/callback?code=…");
if (!cb) return;
const r = await act("chatgpt", {action: "login", callback: cb}, false);

View File

@ -3320,7 +3320,7 @@ impl App {
if v["registered"] == true && ui.add(secondary_button("換帳號")).on_hover_text(t("登出並忘記這個帳號,下次用另一個 ChatGPT 帳號登入")).clicked() {
self.chatgpt_ask_brain(serde_json::json!({"action": "switch_account"}), false);
}
if let Some(u) = v["url"].as_str().filter(|_| !usable) {
if let Some(u) = v["url"].as_str().filter(|u| !usable && crate::chatgpt::is_sign_in_page(u)) {
ui.hyperlink_to(t("打開登入頁"), u);
}
ui.hyperlink_to(t("管理用量"), crate::chatgpt::USAGE_URL);
@ -3358,8 +3358,10 @@ impl App {
match crate::remote::sync_post(&s, "chatgpt", &body) {
Ok(v) => {
if let Some(u) = v["url"].as_str() {
// (Windows' `start` reads & in an address as the end of it: there, the link opens it.)
if cfg!(windows) {
// (Only OpenAI's own sign-in page is opened, whatever a brain sends.)
if !crate::chatgpt::is_sign_in_page(u) {
crate::chatgpt::set_note("大腦給的登入網址不是 OpenAI 的,沒有打開。");
} else if cfg!(windows) {
crate::chatgpt::set_note("按「打開登入頁」登入並同意。之後那一頁打不開的話,把它的網址整個貼在下面,按「完成登入」。");
} else {
crate::chatgpt::set_note("已在瀏覽器打開登入頁:登入並同意。之後那一頁打不開的話,把它的網址整個貼在下面,按「完成登入」。");

View File

@ -137,6 +137,10 @@ impl App {
self.mcp_poll(ctx);
// ChatGPT 方案: a sign-in that finished (the first one with the plan gets the welcome).
for r in crate::chatgpt::take_finished() {
// (Signed in: this account's models, as the plan lists them.)
if r.is_ok() && !self.mir.on {
self.fetch_models(crate::providers::ProviderKind::ChatGpt);
}
self.notice = Some(match r {
Ok(who) => crate::chatgpt::welcome_once().unwrap_or_else(|| format!("已用 ChatGPT({who})登入。")),
Err(e) => format!("ChatGPT 沒有登入成功:{e}"),

View File

@ -693,6 +693,8 @@ impl App {
.collect();
// The connectors run here too: whether each is connected, or why not.
out["mcp"] = self.mcp_state();
// ChatGPT 方案: whether the brain's account can be used (never its tokens).
out["chatgpt"] = crate::chatgpt::view();
// The bots' computer lives here; a screen shows its state, not its own computer's.
let run = crate::cloudbox::run_state();
out["box"] = json!({"label": run.label(), "running": run.is_running(), "available": crate::cloudbox::available(), "busy": crate::cloudbox::is_busy(), "screens": self.tiles_json()});
@ -1220,6 +1222,9 @@ impl App {
if v["mcp"].is_object() {
self.mir.mcp_state = v["mcp"].clone();
}
if v["chatgpt"].is_object() {
crate::chatgpt::set_brain_view(v["chatgpt"].clone());
}
if let Some(c) = v["computers"].as_object() {
self.mir.computers = c.iter().filter_map(|(k, x)| Some((k.parse().ok()?, x.clone()))).collect();
}

View File

@ -629,7 +629,15 @@ pub fn fresh_token() -> Result<String, NoToken> {
if !a.plan_ok() {
return Err(NoToken::needs_person(NO_PLAN));
}
if a.near_end() { renew_after(&a.access) } else { Ok(a.access) }
if !a.near_end() {
return Ok(a.access);
}
match renew_after(&a.access) {
Ok(t) => Ok(t),
// (Renewed early, and it didn't work this time: the token in hand still has minutes left.)
Err(e) if e.retry && a.expires_at > crate::model::now_ms() + 30_000 && account().access == a.access => Ok(a.access),
Err(e) => Err(e),
}
}
/// A new access token, because `stale` ended or was refused. One renewal at a time (the refresh
@ -705,10 +713,15 @@ pub fn logout(forget: bool) -> Result<String, String> {
let _g = renewing().lock().unwrap_or_else(|e| e.into_inner());
let a = account();
let mut said = String::new();
if !a.refresh.is_empty() && !a.refresh.starts_with(crate::vault_store::SEALED) {
// (Revoked twice at most over a network hiccup; signed out here either way.)
if a.refresh.starts_with(crate::vault_store::SEALED) {
said = "(這台電腦現在打不開存著的憑證,沒辦法到 OpenAI 撤銷:請到 ChatGPT 設定裡中斷 AnyBot 的連線)".into();
} else if !a.refresh.is_empty() {
// (Revoked twice at most over a network hiccup, a moment apart; signed out here either way.)
let mut revoked = false;
for _ in 0..2 {
for i in 0..2 {
if i > 0 {
std::thread::sleep(Duration::from_secs(1));
}
match post_form(&format!("{}/api/accounts/oauth/revoke", auth_base()), &[("token", a.refresh.clone()), ("token_type_hint", "refresh_token".into()), ("client_id", a.client_id.clone())]) {
Ok((s, _)) if (200..300).contains(&s) => {
revoked = true;
@ -768,8 +781,35 @@ pub fn for_screen(v: &Value) -> Value {
(t, ok, None)
}
};
let mut v = view();
v["ok"] = json!(ok);
v["text"] = json!(text);
v["url"] = json!(url);
v
}
/// How the account stands, for a screen or the phone (never a token).
pub fn view() -> Value {
let a = account();
json!({"ok": ok, "text": text, "url": url, "signed_in": a.signed_in(), "plan_ok": a.plan_ok(), "email": a.email, "registered": !a.client_id.is_empty(), "status": status_text()})
json!({"signed_in": a.signed_in(), "plan_ok": a.plan_ok(), "email": a.email, "registered": !a.client_id.is_empty(), "status": status_text(), "limited": limited()})
}
/// 已達用量上限: the plan said its usage is used up. Requests nobody is watching (a routine, a
/// channel's message, a check) aren't sent on the plan until one goes through again; a turn
/// the person is watching still tries (they chose to ask).
static LIMITED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
pub fn limited() -> bool {
LIMITED.load(std::sync::atomic::Ordering::Relaxed)
}
pub fn set_limited(on: bool) {
LIMITED.store(on, std::sync::atomic::Ordering::Relaxed);
}
/// Only OpenAI's own sign-in page is opened from what a brain sends (a screen opens it in a browser).
pub fn is_sign_in_page(url: &str) -> bool {
url.starts_with("https://auth.openai.com/")
}
/// On a screen: how the brain's account stands, as it last said (None: not asked yet).
@ -1153,6 +1193,14 @@ pub mod tests {
// Plenty of time left: not renewed.
sign_in_for_test("fine", 3_600_000);
assert_eq!(fresh_token().unwrap(), "fine");
// Renewed early but the sign-in server can't be reached: the token in hand (minutes left) is used.
sign_in_for_test("still-good", 120_000);
TEST_AUTH.with(|t| *t.borrow_mut() = Some("http://127.0.0.1:1".into()));
assert_eq!(fresh_token().unwrap(), "still-good");
// …but not once it is about to end.
sign_in_for_test("ending", 10_000);
assert!(fresh_token().unwrap_err().retry);
TEST_AUTH.with(|t| *t.borrow_mut() = Some(fake.url.clone()));
// A refresh token OpenAI won't take: signed out, the registration kept.
update(|a| a.refresh = "spent".into()).unwrap();
let e = renew_after("fine").unwrap_err();
@ -1187,6 +1235,20 @@ pub mod tests {
leave_test_place(dir);
}
#[test]
fn only_openais_sign_in_page_is_opened() {
assert!(is_sign_in_page("https://auth.openai.com/api/accounts/authorize?client_id=x"));
for bad in ["http://auth.openai.com/x", "https://auth.openai.com.evil.example/x", "file:///etc/passwd", "https://evil.example/?https://auth.openai.com/"] {
assert!(!is_sign_in_page(bad), "{bad}");
}
// What a screen or the phone gets: how it stands, never a token.
let dir = use_test_place("http://127.0.0.1:1");
sign_in_for_test("secret-token", 3_600_000);
let v = view().to_string();
assert!(v.contains("\"signed_in\":true") && !v.contains("secret-token") && !v.contains("refresh-x"), "{v}");
leave_test_place(dir);
}
#[test]
fn signed_in_without_the_plan_asks_for_consent_again() {
let declined = Account { client_id: "oaiapp_9".into(), access: "a".into(), scopes: vec!["openid".into()], ..Default::default() };

View File

@ -1470,10 +1470,13 @@ fn plan_failure(e: &Value, retry_after: Option<u64>) -> Option<Failure> {
let said = e["message"].as_str().unwrap_or("");
let param = e["param"].as_str().unwrap_or("");
Some(match code {
"subscription_sharing_usage_limit_exceeded" => Failure::fatal(format!(
"subscription_sharing_usage_limit_exceeded" => {
crate::chatgpt::set_limited(true);
Failure::fatal(format!(
"已達用量上限(ChatGPT 方案):你的 ChatGPT 方案,或你給 AnyBot 的上限,這段時間用完了。到 ChatGPT 設定的「用量」查看或調整(管理用量:{})。",
crate::chatgpt::USAGE_URL
)),
))
}
"subscription_sharing_usage_unavailable" | "subscription_sharing_user_unavailable" => {
Failure { msg: "ChatGPT 方案暫時沒辦法用,等一下再試。".into(), retryable: true, retry_after_ms: Some(retry_after.unwrap_or(BUSY_RETRY_MS)) }
}
@ -1533,6 +1536,10 @@ fn stream_responses_with(req: &ChatRequest, effort: Option<&str>, cancel: &Atomi
// (Not strict: AnyBot's schemas have optional fields, which strict mode refuses.)
body["tools"] = json!(req.tools.iter().map(|t| json!({"type": "function", "name": t["name"], "description": t["description"], "parameters": t["parameters"], "strict": false})).collect::<Vec<_>>());
}
// Used up: what nobody is watching waits until a request goes through again.
if crate::chatgpt::limited() && PATIENT.with(|p| p.get()) {
return Err(plan_failure(&json!({"code": "subscription_sharing_usage_limit_exceeded"}), None).unwrap_or_else(|| Failure::fatal(String::new())));
}
// Only ever OpenAI's own address, whatever the settings say: the token goes nowhere else.
let url = format!("{}/responses", crate::chatgpt::api_base());
let mut token = crate::chatgpt::fresh_token().map_err(no_token)?;
@ -1593,23 +1600,22 @@ fn stream_responses_with(req: &ChatRequest, effort: Option<&str>, cancel: &Atomi
out.tool_calls.push(call);
}
}
"response.completed" | "response.incomplete" => {
"response.completed" => {
if let Some(u) = v["response"].get("usage").filter(|u| u.is_object()) {
out.usage = Usage::of_responses(u);
}
let note = match v["response"]["incomplete_details"]["reason"].as_str() {
Some("max_output_tokens") => "\n\n(回答太長,已達長度上限。)".to_string(),
Some("content_filter") => "\n\n(模型拒絕回答這個要求。)".to_string(),
_ if kind == "response.incomplete" => format!("\n\n(回答沒有完成:{})", v["response"]["incomplete_details"]["reason"].as_str().unwrap_or("沒有說原因")),
_ => String::new(),
};
if !note.is_empty() {
out.text.push_str(&note);
send(StreamEvent::Text(note));
}
ended = true;
return false;
}
// Only a completed answer counts: an incomplete one is said, and its steps aren't run.
"response.incomplete" => {
error = Some(Failure::fatal(match v["response"]["incomplete_details"]["reason"].as_str() {
Some("max_output_tokens") => "回答太長,已達長度上限,沒有完成。".to_string(),
Some("content_filter") => "模型拒絕回答這個要求。".to_string(),
r => format!("ChatGPT 的回答沒有完成({})。", r.unwrap_or("沒有說原因")),
}));
return false;
}
"response.failed" | "error" => {
// (response.failed carries it in response.error; an error event carries it itself.)
let e = if kind == "error" { if v["error"].is_object() { v["error"].clone() } else { v.clone() } } else { v["response"]["error"].clone() };
@ -1627,6 +1633,7 @@ fn stream_responses_with(req: &ChatRequest, effort: Option<&str>, cancel: &Atomi
if !ended && !cancel.load(Ordering::Relaxed) {
return Err(Failure::retry("ChatGPT 的回答中途斷了(沒有收到結尾)。".into()));
}
crate::chatgpt::set_limited(false);
Ok(out)
}
@ -2553,6 +2560,12 @@ mod tests {
// ---------- ChatGPT 方案 (the Responses API) ----------
/// The plan's 「used up」 mark is one for the program: the tests that stream on the plan take turns.
fn plan_turn() -> std::sync::MutexGuard<'static, ()> {
static T: std::sync::Mutex<()> = std::sync::Mutex::new(());
T.lock().unwrap_or_else(|e| e.into_inner())
}
fn plan_req(history: Vec<Message>, tools: Vec<Value>) -> ChatRequest {
// (Whatever the settings say, requests go to chatgpt::api_base(): a test points it at its own server.)
ChatRequest { kind: ProviderKind::ChatGpt, base_url: "https://evil.example/v1".into(), api_key: "stale-from-settings".into(), model: "gpt-6.1-sol".into(), system: "你是助手".into(), history, tools, session: String::new(), effort: String::new() }
@ -2583,6 +2596,7 @@ mod tests {
#[test]
fn the_plan_streams_words_and_tool_calls_with_its_own_token_and_address() {
let _turn = plan_turn();
use crate::testkit::{Fake, Format, Reply};
let fake = Fake::start(Format::Responses, vec![Reply::text("你好"), Reply::call("call_9", "list_dir", json!({"path": "."}))], None);
let dir = crate::chatgpt::tests::use_test_place("http://127.0.0.1:1");
@ -2617,9 +2631,10 @@ mod tests {
#[test]
fn a_used_up_plan_stops_and_says_where_to_look() {
let _turn = plan_turn();
use crate::testkit::{Fake, Format, Reply};
let failed = format!("event: response.failed\ndata: {}\n\n", json!({"type": "response.failed", "response": {"error": {"code": "subscription_sharing_usage_limit_exceeded", "message": "limit"}}}));
let fake = Fake::start(Format::Responses, vec![Reply::Raw(200, failed)], Some(Reply::text("不該再問")));
let fake = Fake::start(Format::Responses, vec![Reply::Raw(200, failed)], Some(Reply::text("又能用了")));
let dir = crate::chatgpt::tests::use_test_place("http://127.0.0.1:1");
crate::chatgpt::tests::sign_in_for_test("plan-token", 3_600_000);
crate::chatgpt::tests::use_test_api(Some(fake.base()));
@ -2632,12 +2647,21 @@ mod tests {
assert!(!plan_http_error(429, r#"{"error":{"code":"subscription_sharing_usage_limit_exceeded"}}"#, None).retryable);
assert!(plan_http_error(503, r#"{"error":{"code":"subscription_sharing_usage_unavailable"}}"#, None).retryable);
assert!(plan_http_error(400, r#"{"error":{"code":"subscription_sharing_unsupported_capability","param":"reasoning.effort"}}"#, None).msg.contains("reasoning.effort"));
// Used up: what nobody watches isn't sent until one goes through again; a watched turn still asks.
assert!(crate::chatgpt::limited());
set_patient(true);
let e = run_step_as_written(&plan_req(vec![Message::user("例行")], vec![]), &AtomicBool::new(false), &|_| {}).unwrap_err();
set_patient(false);
assert!(e.contains("已達用量上限") && fake.requests() == 1, "{e}");
assert_eq!(run_step_as_written(&plan_req(vec![Message::user("hi")], vec![]), &AtomicBool::new(false), &|_| {}).unwrap().text, "又能用了");
assert!(!crate::chatgpt::limited());
crate::chatgpt::tests::use_test_api(None);
crate::chatgpt::tests::leave_test_place(dir);
}
#[test]
fn a_refused_token_is_renewed_once_and_a_cut_stream_is_not_an_answer() {
let _turn = plan_turn();
use crate::testkit::{Fake, Format, Reply};
let auth = crate::chatgpt::tests::FakeAuth::start("oaiapp_1", Default::default(), crate::chatgpt::PLAN_SCOPE);
let cut = format!("event: response.output_text.delta\ndata: {}\n\n", json!({"type": "response.output_text.delta", "delta": "說到一半"}));
@ -2650,6 +2674,16 @@ mod tests {
assert!(fake.raw.lock().unwrap()[1].to_lowercase().contains("authorization: bearer access-1"));
let e = run_step_as_written(&req, &AtomicBool::new(false), &|_| {}).unwrap_err();
assert!(e.contains("中途斷了"), "{e}");
// An incomplete answer isn't an answer: its steps aren't run.
let incomplete = [
format!("event: response.output_item.done\ndata: {}\n\n", json!({"type": "response.output_item.done", "item": {"type": "function_call", "call_id": "c1", "name": "shell", "arguments": "{}"}})),
format!("event: response.incomplete\ndata: {}\n\n", json!({"type": "response.incomplete", "response": {"incomplete_details": {"reason": "max_output_tokens"}}})),
]
.concat();
let fake2 = Fake::start(Format::Responses, vec![Reply::Raw(200, incomplete)], None);
crate::chatgpt::tests::use_test_api(Some(fake2.base()));
let e = run_step_as_written(&req, &AtomicBool::new(false), &|_| {}).unwrap_err();
assert!(e.contains("長度上限"), "{e}");
crate::chatgpt::tests::use_test_api(None);
crate::chatgpt::tests::leave_test_place(dir);
}