Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:sparkles: Support removing saved ChatGPT accounts and settings navigation options https://github.com/siyuan-note/siyuan/issues/20109

Daniel41aa87abfa24
diff --git a/app/src/config/index.ts b/app/src/config/index.ts
index a22833aa0d..4f93e1845d 100644
--- a/app/src/config/index.ts
+++ b/app/src/config/index.ts
@@ -130,7 +130,8 @@ export const openPluginSetting = (app: App) => {
/// #endif
};
-export const openSetting = (app: App, tab?: TSettingTab, aiProvider?: "chatgpt") => {
+export const openSetting = (app: App, tab?: TSettingTab, options?: {aiProvider?: "chatgpt"}) => {
+ const aiProvider = options?.aiProvider;
if (tab === "bazaar" && !isBazaarAvailable()) {
return;
}
diff --git a/app/src/config/setting/windowMode.test.ts b/app/src/config/setting/windowMode.test.ts
index 3044c1ee54..1d4ff1a1ca 100644
--- a/app/src/config/setting/windowMode.test.ts
+++ b/app/src/config/setting/windowMode.test.ts
@@ -22,7 +22,7 @@ const fixture = (browser = false, mobile = false) => {
{BROWSER: browser, MOBILE: mobile}, false, true), ScriptTarget.ES2021, true);
const declarations = index.statements.filter(statement => isVariableStatement(statement) &&
statement.declarationList.declarations.some(item => ["openSetting", "openBazaarReadme"].includes(item.name.getText(index))));
- const entry = {} as {openSetting: (app: unknown, tab?: string, aiProvider?: "chatgpt") => void;
+ const entry = {} as {openSetting: (app: unknown, tab?: string, options?: {aiProvider?: "chatgpt"}) => void;
openBazaarReadme: (app: unknown, type: string, name: string, from: string) => Promise<void>};
let native = false;
runInNewContext(transpileModule(declarations.map(item => item.getText(index)).join("\n"), {compilerOptions}).outputText, {
@@ -79,13 +79,13 @@ test("browser and mobile keep their own settings UI regardless of the native pre
test("ChatGPT navigation reaches the native settings command and dialog entry", () => {
const f = fixture();
- f.entry.openSetting({}, "ai", "chatgpt");
+ f.entry.openSetting({}, "ai", {aiProvider: "chatgpt"});
assert.equal(JSON.stringify(f.calls[0][2]), JSON.stringify({tab: "ai", aiProvider: "chatgpt"}));
f.calls.length = 0;
f.storage.mode = 0;
- f.entry.openSetting({}, "ai", "chatgpt");
+ f.entry.openSetting({}, "ai", {aiProvider: "chatgpt"});
assert.deepEqual(f.calls.map(item => item[0]), ["dialog", "chatgpt"]);
const mobile = fixture(true, true);
- mobile.entry.openSetting({}, "ai", "chatgpt");
+ mobile.entry.openSetting({}, "ai", {aiProvider: "chatgpt"});
assert.deepEqual(mobile.calls.map(item => item[0]), ["mobile", "chatgpt"]);
});
diff --git a/app/src/config/tabs/ai/chatGPTAccount.test.ts b/app/src/config/tabs/ai/chatGPTAccount.test.ts
index 16864fdcde..faa7228ab3 100644
--- a/app/src/config/tabs/ai/chatGPTAccount.test.ts
+++ b/app/src/config/tabs/ai/chatGPTAccount.test.ts
@@ -25,12 +25,12 @@ const account = (id = "account-one", email = "[email protected]") => ({id, email,
const fixture = (remote = false, initialProfiles = [account()], accountID = "") => {
const controls: Record<string, Control> = {};
- for (const name of ["accountRow", "accountInfo", "account", "password", "file", "statusRow", "status", "login", "add", "logout", "usage", "cancel", "export", "import"]) {
+ for (const name of ["accountRow", "accountInfo", "account", "password", "file", "statusRow", "status", "login", "add", "logout", "remove", "usage", "cancel", "export", "import"]) {
controls[name] = new Control();
controls[name].dataset.chatgpt = name;
}
const root = new Control();
- const buttons = ["login", "add", "logout", "usage", "cancel", "export", "import"].map(name => controls[name]);
+ const buttons = ["login", "add", "logout", "remove", "usage", "cancel", "export", "import"].map(name => controls[name]);
Object.assign(root, {
querySelector: (selector: string) => controls[selector.match(/data-chatgpt='([^']+)'/)![1]],
querySelectorAll: () => buttons,
@@ -44,6 +44,9 @@ const fixture = (remote = false, initialProfiles = [account()], accountID = "")
const namespace: Record<string, unknown> = {};
let pendingStatus: (response: unknown) => void;
let loginCount = 0;
+ const confirmations: Array<{text: string; confirm: () => void; cancel: () => void}> = [];
+ const messages: string[] = [];
+ const outcomes = {removeCode: 0, revoked: true};
const source = readFileSync("src/config/tabs/ai/chatGPTAccount.ts", "utf8");
runInNewContext(transpileModule(source, {compilerOptions: {module: ModuleKind.CommonJS}}).outputText, {
exports: namespace,
@@ -59,6 +62,11 @@ const fixture = (remote = false, initialProfiles = [account()], accountID = "")
if (selected) { selected.connected = false; selected.sharing = false; }
callback?.({code: 0, data: {revoked: true}});
}
+ if (path.endsWith("remove")) {
+ const index = profiles.findIndex(profile => profile.id === (body as {accountID: string}).accountID);
+ if (outcomes.removeCode === 0 && index !== -1) { profiles.splice(index, 1); }
+ callback?.({code: outcomes.removeCode, data: {revoked: outcomes.revoked}});
+ }
if (path.endsWith("import")) {
const imported = account("account-two", "[email protected]");
profiles.push(imported);
@@ -70,7 +78,10 @@ const fixture = (remote = false, initialProfiles = [account()], accountID = "")
if (name.endsWith("util/hostCapabilities")) { return {getHostCapabilities: () => ({remoteKernel: remote})}; }
if (name.endsWith("util/compatibility")) { return {isInMobileApp: () => false, saveExportFile: async () => ({status: "success"})}; }
if (name.endsWith("editor/openLink")) { return {openByMobile: () => {}}; }
- if (name.endsWith("dialog/message")) { return {showMessage: () => {}}; }
+ if (name.endsWith("dialog/message")) { return {showMessage: (message: string) => messages.push(message)}; }
+ if (name.endsWith("dialog/confirmDialog")) {
+ return {confirmDialog: (_title: string, text: string, confirm: () => void, cancel: () => void) => confirmations.push({text, confirm, cancel})};
+ }
if (name.endsWith("render/fragments")) { return {genConfigItemMainHtml: () => ""}; }
if (name === "electron") { return {shell: {openExternal: async () => {}}}; }
throw new Error(name);
@@ -78,7 +89,7 @@ const fixture = (remote = false, initialProfiles = [account()], accountID = "")
location: {hostname: remote ? "notes.example.com" : "127.0.0.1"},
MutationObserver: class { constructor(callback: () => void) { observerCallback = callback; } observe() {} disconnect() {} },
window: {
- siyuan: {languages: {chatGPTAccount: "ChatGPT account", chatGPTSignedOut: "Not signed in; account info is kept for signing in again", mcpStatusConnected: "Connected", mcpStatusAuthorizationRequired: "Authorization required", chatGPTConnect: "Continue", chatGPTSignInPendingTip: "Signing in", chatGPTRemoteTip: "Import on remote"}},
+ siyuan: {languages: {confirmDeleteTip: "Delete ${x}?", chatGPTRevokeFailed: "Remote revocation was not confirmed", chatGPTAccount: "ChatGPT account", chatGPTSignedOut: "Not signed in; account info is kept for signing in again", mcpStatusConnected: "Connected", mcpStatusAuthorizationRequired: "Authorization required", chatGPTConnect: "Continue", chatGPTSignInPendingTip: "Signing in", chatGPTRemoteTip: "Import on remote"}},
setTimeout: (callback: () => void) => { const id = timers.size + 1; timers.set(id, callback); return id; },
clearTimeout: (id: number) => { timers.delete(id); },
open: () => browserWindow,
@@ -90,7 +101,7 @@ const fixture = (remote = false, initialProfiles = [account()], accountID = "")
const mount = namespace.mountChatGPTAccount as (root: unknown, draft: unknown, onChange: (ready: boolean) => void) => void;
mount(view, draft, value => ready.push(value));
return {
- controls, root, view, draft, calls, timers, ready, browserWindow, profiles,
+ controls, root, view, draft, calls, timers, ready, browserWindow, profiles, confirmations, outcomes, messages,
remove: () => { view.isConnected = false; observerCallback(); },
finish: (response: unknown) => pendingStatus(response),
};
@@ -100,13 +111,70 @@ test("no saved accounts show login without an account picker or repeated login t
const f = fixture(false, []);
assert.equal(f.controls.accountRow.classes.has("fn__none"), true);
assert.equal(f.controls.account.classes.has("fn__none"), true);
- for (const name of ["add", "logout", "usage", "statusRow"]) {
+ for (const name of ["add", "logout", "remove", "usage", "statusRow"]) {
assert.equal(f.controls[name].classes.has("fn__none"), true);
}
assert.equal(f.controls.login.disabled, false);
assert.equal(f.ready.at(-1), false);
});
+test("removing the selected registration preserves another registration with the same email", async () => {
+ const f = fixture(false, [account(), account("account-two")], "account-one");
+ const removing = f.root.listeners.get("click")!({target: f.controls.remove});
+ assert.equal(f.confirmations[0].text, "Delete [email protected] (ount-one)?");
+ assert.equal(f.calls.some(call => call.path.endsWith("remove")), false);
+ f.confirmations[0].confirm();
+ await removing;
+ assert.equal(f.profiles.length, 1);
+ assert.equal(f.profiles[0].id, "account-two");
+ assert.equal(f.controls.account.classes.has("fn__none"), true);
+ assert.equal(f.draft.accountID, "account-two");
+ assert.equal(f.draft.models.length, 0);
+});
+
+test("cancelling account removal does not send a request", async () => {
+ const f = fixture();
+ const removing = f.root.listeners.get("click")!({target: f.controls.remove});
+ f.confirmations[0].cancel();
+ await removing;
+ assert.equal(f.calls.some(call => call.path.endsWith("remove")), false);
+ assert.equal(f.draft.accountID, "account-one");
+ assert.equal(f.controls.remove.disabled, false);
+});
+
+test("removing the last signed-out account on a remote kernel restores the empty state", async () => {
+ const f = fixture(true, [{...account(), connected: false, sharing: false}]);
+ assert.equal(f.controls.remove.disabled, false);
+ const removing = f.root.listeners.get("click")!({target: f.controls.remove});
+ f.confirmations[0].confirm();
+ await removing;
+ assert.equal(f.controls.accountRow.classes.has("fn__none"), true);
+ assert.equal(f.controls.remove.classes.has("fn__none"), true);
+ assert.equal(f.draft.accountID, "");
+ assert.equal(f.ready.at(-1), false);
+});
+
+test("failed removal retains the selected registration and model configuration", async () => {
+ const f = fixture(false, [account()], "account-one");
+ f.outcomes.removeCode = -1;
+ const removing = f.root.listeners.get("click")!({target: f.controls.remove});
+ f.confirmations[0].confirm();
+ await removing;
+ assert.equal(f.draft.accountID, "account-one");
+ assert.equal(f.draft.models.length, 1);
+ assert.equal(f.controls.remove.disabled, false);
+});
+
+test("unconfirmed remote revocation is reported after local removal", async () => {
+ const f = fixture();
+ f.outcomes.revoked = false;
+ const removing = f.root.listeners.get("click")!({target: f.controls.remove});
+ f.confirmations[0].confirm();
+ await removing;
+ assert.equal(f.draft.accountID, "");
+ assert.equal(f.messages.at(-1), "Remote revocation was not confirmed");
+});
+
test("a single saved account is selected and displayed as text", () => {
const f = fixture();
assert.equal(f.controls.accountRow.classes.has("fn__none"), false);
diff --git a/app/src/config/tabs/ai/chatGPTAccount.ts b/app/src/config/tabs/ai/chatGPTAccount.ts
index 99ddfb39a2..1e7e9bc5da 100644
--- a/app/src/config/tabs/ai/chatGPTAccount.ts
+++ b/app/src/config/tabs/ai/chatGPTAccount.ts
@@ -2,6 +2,7 @@ import {fetchPost} from "../../../util/fetch";
import type {ChatGPTAccount} from "../../../types/api";
import {escapeHtmlTextAndAttr} from "../../../util/escape";
import {showMessage} from "../../../dialog/message";
+import {confirmDialog} from "../../../dialog/confirmDialog";
import {genConfigItemMainHtml} from "../../render/fragments";
import {openByMobile} from "../../../editor/openLink";
import {isInMobileApp, saveExportFile} from "../../../protyle/util/compatibility";
@@ -35,6 +36,8 @@ export const genChatGPTAccountHTML = () => {
<span class="fn__space"></span>
<button class="b3-button b3-button--outline fn__none" data-chatgpt="logout">${L.logout}</button>
<span class="fn__space"></span>
+ <button class="b3-button b3-button--outline fn__none" data-chatgpt="remove">${L.remove}</button>
+ <span class="fn__space"></span>
<button class="b3-button b3-button--outline fn__none" data-chatgpt="usage">${L.chatGPTUsage}</button>
<span class="fn__space"></span>
<button class="b3-button b3-button--cancel fn__none" data-chatgpt="cancel">${L.cancel}</button>
@@ -94,6 +97,8 @@ export const mountChatGPTAccount = (view: HTMLElement, draft: Config.IProvider,
cancel.disabled = busy;
root.querySelector<HTMLButtonElement>("[data-chatgpt='add']").classList.toggle("fn__none", profiles.length === 0);
root.querySelector<HTMLButtonElement>("[data-chatgpt='logout']").classList.toggle("fn__none", !selected?.connected);
+ root.querySelector<HTMLButtonElement>("[data-chatgpt='remove']").classList.toggle("fn__none", !selected);
+ root.querySelector<HTMLButtonElement>("[data-chatgpt='remove']").disabled ||= !selected;
root.querySelector<HTMLButtonElement>("[data-chatgpt='usage']").classList.toggle("fn__none", !selected);
root.querySelector<HTMLButtonElement>("[data-chatgpt='logout']").disabled ||= !selected?.connected;
root.querySelector<HTMLButtonElement>("[data-chatgpt='export']").disabled ||= !selected?.connected && !exportedFile;
@@ -191,6 +196,23 @@ export const mountChatGPTAccount = (view: HTMLElement, draft: Config.IProvider,
if (response.code === 0 && !response.data.revoked) { showMessage(L.chatGPTRevokeFailed); }
});
await load();
+ } else if (action === "remove") {
+ const accountID = draft.accountID;
+ const selected = profiles.find(item => item.id === accountID);
+ if (!selected) { return; }
+ const confirmed = await new Promise<boolean>(resolve => {
+ confirmDialog(L.deleteOpConfirm, L.confirmDeleteTip.replace("${x}", escapeHtmlTextAndAttr(accountLabel(selected))),
+ () => resolve(true), () => resolve(false), true);
+ });
+ if (!confirmed || disposed) { return; }
+ await fetchPost("/api/ai/chatgpt/remove", {accountID}, response => {
+ if (disposed || response.code !== 0) { return; }
+ draft.accountID = "";
+ draft.models = [];
+ exportedFile = "";
+ if (!response.data.revoked) { showMessage(L.chatGPTRevokeFailed); }
+ });
+ await load();
} else if (action === "export") {
if (!exportedFile) {
const secret = transferPassword();
diff --git a/app/src/layout/dock/agent/AgentChat.ts b/app/src/layout/dock/agent/AgentChat.ts
index 2f5dc065af..6499d3a285 100644
--- a/app/src/layout/dock/agent/AgentChat.ts
+++ b/app/src/layout/dock/agent/AgentChat.ts
@@ -819,7 +819,7 @@ export class AgentChat extends Model {
openChatGPTProvider();
} else {
const {openSetting} = await import("../../../config");
- openSetting(this.app, "ai", "chatgpt");
+ openSetting(this.app, "ai", {aiProvider: "chatgpt"});
}
});
return;
diff --git a/app/src/types/api/index.d.ts b/app/src/types/api/index.d.ts
index a62667302e..83bea8b33b 100644
--- a/app/src/types/api/index.d.ts
+++ b/app/src/types/api/index.d.ts
@@ -2778,6 +2778,11 @@ export interface APIPOSTRoutes {
response: { "code": 0; "data": ChatGPTLogoutResult; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
body: "json";
};
+ "/api/ai/chatgpt/remove": {
+ request: ChatGPTAccountRequestInput;
+ response: { "code": 0; "data": ChatGPTLogoutResult; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
+ body: "json";
+ };
"/api/ai/chatgpt/start": {
request: ChatGPTAccountRequestInput;
response: { "code": 0; "data": ChatGPTLogin; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
diff --git a/kernel/api/ai_disabled_test.go b/kernel/api/ai_disabled_test.go
index 9a72b321b8..91a6ad4786 100644
--- a/kernel/api/ai_disabled_test.go
+++ b/kernel/api/ai_disabled_test.go
@@ -41,6 +41,7 @@ func TestAPIContractAIDisabled(t *testing.T) {
"/api/ai/chatgpt/status": chatGPTStatus,
"/api/ai/chatgpt/cancel": chatGPTCancel,
"/api/ai/chatgpt/logout": chatGPTLogout,
+ "/api/ai/chatgpt/remove": chatGPTRemove,
"/api/ai/chatgpt/import": chatGPTImport,
"/api/ai/chatgpt/export": chatGPTExport,
"/api/ai/mcpOAuthAuthorize": mcpOAuthAuthorize,
diff --git a/kernel/api/chatgpt.go b/kernel/api/chatgpt.go
index b829d96d74..1bbe627ed9 100644
--- a/kernel/api/chatgpt.go
+++ b/kernel/api/chatgpt.go
@@ -87,6 +87,17 @@ func chatGPTLogoutContract(c *gin.Context, req apicontract.ChatGPTAccountRequest
return apicontract.Success(apicontract.ChatGPTLogoutResult{Revoked: revoked})
}
+var chatGPTRemove = contractHandler(apicontract.ChatGPTRemove, chatGPTRemoveContract)
+
+func chatGPTRemoveContract(c *gin.Context, req apicontract.ChatGPTAccountRequest) apicontract.Response[apicontract.ChatGPTLogoutResult] {
+ chatGPTNoCache(c)
+ revoked, err := util.ChatGPTService().Remove(c.Request.Context(), req.AccountID)
+ if err != nil {
+ return apicontract.Failure[apicontract.ChatGPTLogoutResult](-1, err.Error())
+ }
+ return apicontract.Success(apicontract.ChatGPTLogoutResult{Revoked: revoked})
+}
+
var chatGPTExport = contractHandler(apicontract.ChatGPTExport, chatGPTExportContract)
func chatGPTExportContract(c *gin.Context, req apicontract.ChatGPTTransferRequest) apicontract.Response[apicontract.ExportFileData] {
diff --git a/kernel/api/chatgpt_test.go b/kernel/api/chatgpt_test.go
index 5f3bf3afb2..697fdcc93c 100644
--- a/kernel/api/chatgpt_test.go
+++ b/kernel/api/chatgpt_test.go
@@ -34,6 +34,7 @@ func TestAPIContractChatGPTAccountLifecycle(t *testing.T) {
engine.POST("/api/ai/chatgpt/import", chatGPTImport)
engine.POST("/api/ai/chatgpt/export", chatGPTExport)
engine.POST("/api/ai/chatgpt/logout", chatGPTLogout)
+ engine.POST("/api/ai/chatgpt/remove", chatGPTRemove)
request := func(path, body string) map[string]json.RawMessage {
w := httptest.NewRecorder()
engine.ServeHTTP(w, httptest.NewRequest(http.MethodPost, path, strings.NewReader(body)))
@@ -60,7 +61,7 @@ func TestAPIContractChatGPTAccountLifecycle(t *testing.T) {
t.Cleanup(func() { util.ChatGPTService().Cancel(login.ID) })
request("/api/ai/chatgpt/status", string(body))
request("/api/ai/chatgpt/cancel", string(body))
- for _, path := range []string{"import", "export", "logout"} {
+ for _, path := range []string{"import", "export", "logout", "remove"} {
result = request("/api/ai/chatgpt/"+path, `{"accountID":"missing","password":"short","data":"{}"}`)
if string(result["code"]) != "-1" {
t.Fatalf("invalid %s accepted", path)
@@ -116,7 +117,7 @@ func TestAPIContractChatGPTAuthorizationBeforeBody(t *testing.T) {
engine := gin.New()
engine.Use(func(c *gin.Context) { c.Set(model.RoleContextKey, role); c.Next() })
ServeAPI(engine)
- paths := []string{"start", "cancel", "logout", "export", "import"}
+ paths := []string{"start", "cancel", "logout", "remove", "export", "import"}
if role != model.RoleAdministrator {
paths = append(paths, "accounts", "status")
}
diff --git a/kernel/api/router.go b/kernel/api/router.go
index 4fdcd02b45..03d4fb13b2 100644
--- a/kernel/api/router.go
+++ b/kernel/api/router.go
@@ -684,6 +684,7 @@ func ServeAPI(ginServer *gin.Engine) {
ginServer.Handle("POST", "/api/ai/chatgpt/status", model.CheckAuth, model.CheckAdminRole, chatGPTStatus)
ginServer.Handle("POST", "/api/ai/chatgpt/cancel", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, chatGPTCancel)
ginServer.Handle("POST", "/api/ai/chatgpt/logout", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, chatGPTLogout)
+ ginServer.Handle("POST", "/api/ai/chatgpt/remove", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, chatGPTRemove)
ginServer.Handle("POST", "/api/ai/chatgpt/export", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, chatGPTExport)
ginServer.Handle("POST", "/api/ai/chatgpt/import", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, chatGPTImport)
ginServer.Handle("POST", "/api/ai/embeddingStat", model.CheckAuth, model.CheckAdminRole, embeddingStat)
diff --git a/kernel/apicontract/contracts.go b/kernel/apicontract/contracts.go
index bca085ecbb..103dae0e31 100644
--- a/kernel/apicontract/contracts.go
+++ b/kernel/apicontract/contracts.go
@@ -1020,6 +1020,10 @@ var ChatGPTCancel = define[ChatGPTLoginRequest, Null]("chatGPTCancel", "/api/ai/
// 退出清除本地令牌并保留账户映射;revoked 表示远程撤销是否确认成功。
var ChatGPTLogout = define[ChatGPTAccountRequest, ChatGPTLogoutResult]("chatGPTLogout", "/api/ai/chatgpt/logout", JSONBody, ResponseOptions{}, "POST")
+// 删除指定的本机账户注册并终止其请求及登录尝试,不合并同邮箱注册;不修改提供商配置或主机 ID。
+// 先尝试撤销会话,远程撤销未确认时仍清除本地记录并返回 revoked=false;缺失账户报错。
+var ChatGPTRemove = define[ChatGPTAccountRequest, ChatGPTLogoutResult]("chatGPTRemove", "/api/ai/chatgpt/remove", JSONBody, ResponseOptions{}, "POST")
+
// 导出使用至少 12 个字符的密码,先写入带版本的认证加密文件,再停止源主机刷新。
var ChatGPTExport = define[ChatGPTTransferRequest, ExportFileData]("chatGPTExport", "/api/ai/chatgpt/export", JSONBody, ResponseOptions{}, "POST")
diff --git a/kernel/apicontract/schema.json b/kernel/apicontract/schema.json
index ee27ec8784..8041647d0c 100644
--- a/kernel/apicontract/schema.json
+++ b/kernel/apicontract/schema.json
@@ -119608,6 +119608,81 @@
]
}
},
+ {
+ "method": "POST",
+ "path": "/api/ai/chatgpt/remove",
+ "handler": "chatGPTRemove",
+ "body": "json",
+ "request": {
+ "$ref": "#/$defs/ChatGPTAccountRequestInput"
+ },
+ "response": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ 0
+ ]
+ },
+ "data": {
+ "$ref": "#/$defs/ChatGPTLogoutResult"
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ -1
+ ]
+ },
+ "data": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "closeTimeout": {
+ "type": "number"
+ }
+ },
+ "required": [
+ "closeTimeout"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data"
+ ],
+ "additionalProperties": true
+ }
+ ]
+ }
+ },
{
"method": "POST",
"path": "/api/ai/chatgpt/start",
diff --git a/kernel/chatgpt/oauth.go b/kernel/chatgpt/oauth.go
index f1657cae14..9573272827 100644
--- a/kernel/chatgpt/oauth.go
+++ b/kernel/chatgpt/oauth.go
@@ -341,7 +341,13 @@ func (s *Service) complete(ctx context.Context, a *attempt, values url.Values) (
}
// 签发的注册 ID 在换码失败后仍可复用,未校验的账户不会成为已连接账户。
if err := s.withStore(ctx, func(store *diskStore) error {
+ if err := ctx.Err(); err != nil {
+ return err
+ }
if _, err := findAccount(store, clientID); err != nil {
+ if a.account != nil {
+ return err
+ }
store.Accounts = append(store.Accounts, &Account{ClientID: clientID})
}
return nil
@@ -366,6 +372,9 @@ func (s *Service) complete(ctx context.Context, a *attempt, values url.Values) (
return nil, err
}
err = s.withStore(ctx, func(store *diskStore) error {
+ if err := ctx.Err(); err != nil {
+ return err
+ }
old, err := findAccount(store, clientID)
if err != nil {
return err
@@ -459,6 +468,23 @@ func (s *Service) Token(ctx context.Context, id string, force bool) (token strin
}
func (s *Service) Logout(ctx context.Context, id string) (revoked bool, err error) {
+ return s.endSession(ctx, id, false)
+}
+
+// Remove 撤销会话并删除指定注册,不按邮箱合并其他注册。
+func (s *Service) Remove(ctx context.Context, id string) (revoked bool, err error) {
+ s.mu.Lock()
+ for _, a := range s.attempts {
+ if a.account != nil && a.account.ClientID == id && a.status.State == "pending" {
+ a.cancel()
+ a.status = LoginStatus{State: "failed", Error: "ChatGPT account was removed"}
+ }
+ }
+ s.mu.Unlock()
+ return s.endSession(ctx, id, true)
+}
+
+func (s *Service) endSession(ctx context.Context, id string, remove bool) (revoked bool, err error) {
s.stopRequests(id)
err = s.withStore(ctx, func(store *diskStore) error {
a, err := findAccount(store, id)
@@ -491,6 +517,14 @@ func (s *Service) Logout(ctx context.Context, id string) (revoked bool, err erro
}
}
clearTokens(a)
+ if remove {
+ for index, account := range store.Accounts {
+ if account.ClientID == id {
+ store.Accounts = append(store.Accounts[:index], store.Accounts[index+1:]...)
+ break
+ }
+ }
+ }
return nil
})
return
diff --git a/kernel/chatgpt/oauth_test.go b/kernel/chatgpt/oauth_test.go
index 49c7e1ac7c..aac24f7952 100644
--- a/kernel/chatgpt/oauth_test.go
+++ b/kernel/chatgpt/oauth_test.go
@@ -29,6 +29,7 @@ type fixture struct {
server *httptest.Server
nonce, challenge, subject, refreshError string
refreshes atomic.Int32
+ revokeFailed bool
}
func newFixture(t *testing.T) *fixture {
@@ -81,6 +82,11 @@ func newFixture(t *testing.T) *fixture {
}
io.WriteString(w, `{"models":[{"slug":"model-a","display_name":"Model A","visibility":"list"},{"slug":"hidden","visibility":"hide"},{"slug":"model-b","display_name":"Model B","visibility":"list"}]}`)
case "/revoke":
+ if f.revokeFailed {
+ w.WriteHeader(http.StatusServiceUnavailable)
+ io.WriteString(w, `{"error":"server_error"}`)
+ return
+ }
w.WriteHeader(200)
default:
w.WriteHeader(404)
@@ -326,12 +332,69 @@ func TestChatGPTCorruptionPreservesOriginal(t *testing.T) {
if _, err := s.Profiles(context.Background()); err == nil {
t.Fatal("corrupted credentials accepted")
}
+ if _, err := s.Remove(context.Background(), "missing"); err == nil {
+ t.Fatal("removal accepted corrupted credentials")
+ }
current, _ := os.ReadFile(path)
if string(current) != string(data) {
t.Fatal("corrupted credentials overwritten")
}
}
+func TestChatGPTRemoveRegistration(t *testing.T) {
+ for _, scenario := range []string{"connected", "signed-out", "revocation-failed"} {
+ t.Run(scenario, func(t *testing.T) {
+ f := newFixture(t)
+ login := f.login(t, "")
+ u, _ := url.Parse(login.URL)
+ f.callback(t, login, u.Query().Get("state"))
+ var hostID string
+ if err := f.service.withStore(context.Background(), func(store *diskStore) error {
+ hostID = store.HostID
+ copy := *store.Accounts[0]
+ copy.ClientID = "other-registration"
+ store.Accounts = append(store.Accounts, &copy)
+ if scenario == "signed-out" {
+ clearTokens(store.Accounts[0])
+ }
+ return nil
+ }); err != nil {
+ t.Fatal(err)
+ }
+ returning := f.login(t, "oaiapp_test")
+ f.service.mu.Lock()
+ pending := f.service.attempts[returning.ID]
+ f.service.mu.Unlock()
+ f.revokeFailed = scenario == "revocation-failed"
+ revoked, err := f.service.Remove(context.Background(), "oaiapp_test")
+ if err != nil || revoked == f.revokeFailed {
+ t.Fatalf("remove: %v %v", revoked, err)
+ }
+ profiles, err := f.service.Profiles(context.Background())
+ if err != nil || len(profiles) != 1 || profiles[0].ID != "other-registration" || !profiles[0].Connected {
+ t.Fatalf("other registration changed: %+v %v", profiles, err)
+ }
+ if status, _ := f.service.Status(returning.ID); status.State != "failed" {
+ t.Fatalf("pending sign-in was not cancelled: %+v", status)
+ }
+ if _, err = f.service.complete(context.Background(), pending, url.Values{"code": {"late"}}); err == nil {
+ t.Fatal("late sign-in recreated removed registration")
+ }
+ if _, err = f.service.Token(context.Background(), "oaiapp_test", false); err == nil {
+ t.Fatal("removed credentials remained usable")
+ }
+ if err = f.service.withStore(context.Background(), func(store *diskStore) error {
+ if store.HostID != hostID || len(store.Accounts) != 1 {
+ t.Fatal("host or account mappings changed")
+ }
+ return nil
+ }); err != nil {
+ t.Fatal(err)
+ }
+ })
+ }
+}
+
func TestChatGPTRejectedNoncePreservesRegistration(t *testing.T) {
f := newFixture(t)
login := f.login(t, "")