From 6e87c2b231161813467d8376bb65c1d9d3dc9148 Mon Sep 17 00:00:00 2001 From: netcon Date: Tue, 17 Nov 2026 16:53:02 +0800 Subject: [PATCH 1/2] feat(ai): allow import/export conversations --- docs/ai.md | 5 +- extensions/github1s-ai/assets/chat.css | 101 +++++++++ .../github1s-ai/src/common/conversation.ts | 112 ++++++++++ extensions/github1s-ai/src/common/protocol.ts | 20 +- .../github1s-ai/src/controllers/history.ts | 2 +- .../github1s-ai/src/controllers/runner.ts | 6 + .../github1s-ai/src/controllers/settings.ts | 210 ++++++++++++------ .../github1s-ai/src/stores/conversations.ts | 172 +++++++------- extensions/github1s-ai/src/stores/index.ts | 12 +- .../webview/components/HistoryImportDialog.ts | 115 ++++++++++ .../src/webview/components/Icon.ts | 4 +- .../src/webview/components/SettingsPage.ts | 108 ++++++--- .../src/webview/components/Tooltip.ts | 2 +- extensions/github1s-ai/test/protocol.test.ts | 21 ++ 14 files changed, 709 insertions(+), 181 deletions(-) create mode 100644 extensions/github1s-ai/src/webview/components/HistoryImportDialog.ts diff --git a/docs/ai.md b/docs/ai.md index 6220819df..3ece7feec 100644 --- a/docs/ai.md +++ b/docs/ai.md @@ -100,8 +100,9 @@ The model and MCP services receive the data sent to them under their own service ### Manage saved data - **Delete one conversation:** open **Show History**, use its delete action, and confirm **Delete**. -- **Export conversations:** in AI Settings, open **General โ†’ Export history โ†’ Export**. The JSON contains conversation data for the current workspace, including stored message and tool content. -- **Reset AI data:** in **General**, select **Clear all data** and confirm. This removes local AI conversations across all workspaces, model settings and API keys, MCP settings, and prompt settings. +- **Export history:** in **AI Settings โ†’ General**, select **Export history** to download all workspaces as JSON, including messages, tool results, and attachments. +- **Import history:** in **General**, select **Import history** and choose a JSON export. The default **Merge + Keep** preserves local conversations with matching IDs in the same workspace. **Overwrite** uses imported conversations; **Replace** replaces all workspace history with the file. +- **Clear all data:** in **General**, select **Clear all data** to delete all workspace history, model settings and API keys, MCP settings, and prompts. ## Troubleshooting diff --git a/extensions/github1s-ai/assets/chat.css b/extensions/github1s-ai/assets/chat.css index 6d1f7c750..789432fd0 100644 --- a/extensions/github1s-ai/assets/chat.css +++ b/extensions/github1s-ai/assets/chat.css @@ -547,6 +547,107 @@ summary:focus-visible, border: 1px solid currentColor; } +.history-import-dialog { + box-sizing: border-box; + width: calc(100% - 24px); + max-width: 300px; + max-height: calc(88vh - 12px); + margin: 12vh auto 12px; + padding: 16px; + color: var(--vscode-foreground); + background: var(--vscode-editorWidget-background, var(--vscode-sideBar-background)); + border: 1px solid var(--vscode-widget-border, var(--vscode-input-border)); + border-radius: 6px; + box-shadow: 0 2px 12px var(--vscode-widget-shadow, rgba(0, 0, 0, 0.3)); +} + +.history-import-dialog::backdrop { + background: rgba(0, 0, 0, 0.35); +} + +.history-import-content { + display: grid; + min-width: 0; + gap: 16px; +} + +.history-import-content h3 { + margin: 0; + font-size: 14px; +} + +.history-import-summary { + min-width: 0; + color: var(--vscode-descriptionForeground); + font-size: 12px; + line-height: 1.5; +} + +.history-import-summary p { + margin: 0; +} + +.history-import-filename { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.history-import-field { + min-width: 0; + margin: 0; + padding: 0; + border: 0; +} + +.history-import-field legend { + margin-bottom: 6px; + padding: 0; + font-size: 12px; + font-weight: 600; +} + +.history-import-label, +.history-import-options, +.history-import-options label { + display: flex; + align-items: center; + gap: 6px; +} + +.history-import-label .icon-button { + width: 20px; + height: 20px; + color: var(--vscode-descriptionForeground); +} + +.history-import-options { + flex-wrap: wrap; + gap: 8px 20px; +} + +.history-import-options input { + margin: 0; + accent-color: var(--vscode-focusBorder); + color-scheme: light; +} + +.vscode-dark .history-import-options input, +.vscode-high-contrast .history-import-options input { + color-scheme: dark; +} + +.history-import-warning { + margin: 0; + color: var(--vscode-errorForeground); + font-size: 12px; + line-height: 1.5; +} + +.history-import-actions { + justify-content: flex-end; +} + /* History */ .history-list { diff --git a/extensions/github1s-ai/src/common/conversation.ts b/extensions/github1s-ai/src/common/conversation.ts index 954223f45..bd5137c5a 100644 --- a/extensions/github1s-ai/src/common/conversation.ts +++ b/extensions/github1s-ai/src/common/conversation.ts @@ -36,6 +36,58 @@ export interface Conversation extends ConversationSummary { messages: ConversationMessage[]; } +export interface WorkspaceConversationHistory { + workspaceKey: string; + conversations: Conversation[]; +} + +export interface ConversationHistory { + exportedAt: string; + workspaces: WorkspaceConversationHistory[]; +} + +export type HistoryImportOptions = { mode: 'merge'; conflicts: 'keep' | 'overwrite' } | { mode: 'replace' }; + +export const isConversationSummary = (value: unknown): value is ConversationSummary => { + if (!isPlainObject(value)) return false; + const summary = value as Record; + return ( + typeof summary.id === 'string' && + summary.id.length > 0 && + typeof summary.title === 'string' && + typeof summary.createdAt === 'number' && + Number.isFinite(summary.createdAt) && + summary.createdAt >= 0 && + typeof summary.updatedAt === 'number' && + Number.isFinite(summary.updatedAt) && + summary.updatedAt >= summary.createdAt && + (summary.usage === undefined || isLanguageModelUsage(summary.usage)) + ); +}; + +const isLanguageModelUsage = (value: unknown): value is LanguageModelUsage => { + if (!isPlainObject(value)) return false; + const usage = value as Record; + const inputTokenDetails = usage.inputTokenDetails; + const outputTokenDetails = usage.outputTokenDetails; + if (!isPlainObject(inputTokenDetails) || !isPlainObject(outputTokenDetails)) return false; + const input = inputTokenDetails as Record; + const output = outputTokenDetails as Record; + return ( + isTokenCount(usage.inputTokens) && + isTokenCount(input.noCacheTokens) && + isTokenCount(input.cacheReadTokens) && + isTokenCount(input.cacheWriteTokens) && + isTokenCount(usage.outputTokens) && + isTokenCount(output.textTokens) && + isTokenCount(output.reasoningTokens) && + isTokenCount(usage.totalTokens) + ); +}; + +const isTokenCount = (value: unknown): value is number | undefined => + value === undefined || (typeof value === 'number' && Number.isFinite(value) && value >= 0); + export const isInterruptedMessage = (message: ConversationMessage): boolean => message.metadata.status === 'failed' || message.metadata.status === 'aborted' || @@ -175,3 +227,63 @@ const isConversationMessageMetadata = (value: unknown): value is ConversationMes (metadata.error === undefined || typeof metadata.error === 'string') ); }; + +export const isConversationWorkspaceKey = (value: unknown): value is string => + typeof value === 'string' && (value === 'empty-workspace' || /^[a-f0-9]{40}$/.test(value)); + +export const parseConversationHistory = async (json: string): Promise => { + let value: unknown; + try { + value = JSON.parse(json); + } catch { + throw new Error('Invalid JSON file.'); + } + if (!isPlainObject(value)) throw new Error('Invalid history file.'); + const history = value as Record; + if ( + typeof history.exportedAt !== 'string' || + !Number.isFinite(Date.parse(history.exportedAt)) || + !Array.isArray(history.workspaces) + ) { + throw new Error('Invalid history file.'); + } + + const workspaceKeys = new Set(); + const workspaces: WorkspaceConversationHistory[] = []; + for (const value of history.workspaces) { + if (!isPlainObject(value)) throw new Error('Invalid workspace history.'); + const workspace = value as Record; + if (!isConversationWorkspaceKey(workspace.workspaceKey) || !Array.isArray(workspace.conversations)) { + throw new Error('Invalid workspace history.'); + } + if (workspaceKeys.has(workspace.workspaceKey)) throw new Error('Duplicate workspace.'); + workspaceKeys.add(workspace.workspaceKey); + + const ids = new Set(); + const conversations: Conversation[] = []; + for (const value of workspace.conversations) { + if (!isConversationSummary(value) || !/^[a-zA-Z0-9_-]+$/.test(value.id)) { + throw new Error('Invalid conversation.'); + } + if (ids.has(value.id)) throw new Error(`Duplicate conversation ID: ${value.id}.`); + ids.add(value.id); + const conversation = value as Conversation; + let messages: Conversation['messages']; + try { + messages = await validateConversationMessages(conversation.messages); + } catch { + throw new Error(`Invalid messages in conversation: ${conversation.id}.`); + } + conversations.push({ + id: conversation.id, + title: conversation.title, + createdAt: conversation.createdAt, + updatedAt: conversation.updatedAt, + ...(conversation.usage === undefined ? {} : { usage: conversation.usage }), + messages, + }); + } + workspaces.push({ workspaceKey: workspace.workspaceKey, conversations }); + } + return { exportedAt: history.exportedAt, workspaces }; +}; diff --git a/extensions/github1s-ai/src/common/protocol.ts b/extensions/github1s-ai/src/common/protocol.ts index 029a4d3df..172a71349 100644 --- a/extensions/github1s-ai/src/common/protocol.ts +++ b/extensions/github1s-ai/src/common/protocol.ts @@ -8,7 +8,7 @@ import { type ContextAttachmentAction, type ContextAttachmentDescriptor, } from './context'; -import type { ConversationSummary } from './conversation'; +import type { ConversationSummary, HistoryImportOptions } from './conversation'; import type { SyntaxHighlightingData } from './highlighting'; import type { McpConfig } from './mcp-config'; import { isModelConfigInput, type ModelConfigInput, type ModelConfigSummary } from './model-config'; @@ -60,6 +60,7 @@ type AllViewEvents = | { type: 'settings.selectModelConfig'; id: string } | { type: 'settings.clearFeedback' } | { type: 'settings.exportHistory' } + | { type: 'settings.importHistory'; content: string; options: HistoryImportOptions } | { type: 'settings.clearAllData' } | { type: 'settings.saveModelConfig'; config: ModelConfigInput } | { type: 'settings.savePromptsConfig'; config: PromptsConfig } @@ -161,6 +162,23 @@ export const parseViewEvent = (value: unknown): ViewEvent | undefined => { : undefined; case 'settings.saveMcpConfig': return exactString(event, 'json') ? { type: event.type, json: event.json } : undefined; + case 'settings.importHistory': { + if ( + !hasExactKeys(event, ['type', 'content', 'options']) || + typeof event.content !== 'string' || + !isPlainObject(event.options) + ) + return undefined; + const options = event.options as Record; + if (hasExactKeys(options, ['mode']) && options.mode === 'replace') { + return { type: event.type, content: event.content, options: { mode: 'replace' } }; + } + return hasExactKeys(options, ['mode', 'conflicts']) && + options.mode === 'merge' && + (options.conflicts === 'keep' || options.conflicts === 'overwrite') + ? { type: event.type, content: event.content, options: { mode: 'merge', conflicts: options.conflicts } } + : undefined; + } default: return undefined; } diff --git a/extensions/github1s-ai/src/controllers/history.ts b/extensions/github1s-ai/src/controllers/history.ts index 4afc8379d..730bd8c19 100644 --- a/extensions/github1s-ai/src/controllers/history.ts +++ b/extensions/github1s-ai/src/controllers/history.ts @@ -71,7 +71,7 @@ export class HistoryController extends Controller { if (selected) await this.runner.cancelPreparation(); await this.runner.cancelConversation(event.id); try { - await this.stores.conversations.delete(event.id); + await this.stores.conversations.delete([event.id]); } catch (error) { const detail = error instanceof Error ? error.message : 'Unknown error.'; await this.stores.runtime.setIn('history.notice', { diff --git a/extensions/github1s-ai/src/controllers/runner.ts b/extensions/github1s-ai/src/controllers/runner.ts index 36e765c1d..c874e1a5b 100644 --- a/extensions/github1s-ai/src/controllers/runner.ts +++ b/extensions/github1s-ai/src/controllers/runner.ts @@ -261,6 +261,12 @@ export class ConversationRunner { return conversationId !== undefined && this.requests.has(conversationId); } + // True while preparing a request or generating a response in any conversation. + isBusy(): boolean { + return this.preparation !== undefined || this.requests.size > 0; + } + + // Returns the given conversation's phase; preparation is shared across conversations. getPhase(conversationId: string | undefined): ChatPhase { if (this.preparation) return 'preparing'; return this.isRequestActive(conversationId) ? 'generating' : 'idle'; diff --git a/extensions/github1s-ai/src/controllers/settings.ts b/extensions/github1s-ai/src/controllers/settings.ts index d24ca3e4d..49ecf6b5e 100644 --- a/extensions/github1s-ai/src/controllers/settings.ts +++ b/extensions/github1s-ai/src/controllers/settings.ts @@ -1,9 +1,16 @@ import * as vscode from 'vscode'; +import { + isConversationWorkspaceKey, + markStreamingMessagesUnknown, + parseConversationHistory, + type Conversation, + type ConversationHistory, +} from '@/common/conversation'; import { parseMcpConfig } from '@/common/mcp-config'; import type { ViewEvent, ViewMessage } from '@/common/protocol'; +import { createAsyncQueue } from '@/helpers/async-queue'; import type { Stores } from '@/stores'; -import { DEFAULT_STORE_VERSION } from '@/stores/common'; import { Controller } from './common'; import type { ConversationRunner } from './runner'; @@ -11,9 +18,11 @@ import type { ConversationRunner } from './runner'; type HistoryExportMessage = Extract; export class SettingsController extends Controller { + private readonly enqueue = createAsyncQueue(); + constructor( stores: Stores, - private readonly runner: Pick, + private readonly runner: Pick, ) { super(stores); } @@ -25,77 +34,144 @@ export class SettingsController extends Controller { @Controller.handler('settings.exportHistory') async handleExportHistory(_event: ViewEvent<'settings.exportHistory'>): Promise { - try { - const confirmed = await vscode.window.showWarningMessage( - 'Export all conversation history?', - { - modal: true, - detail: 'The JSON export may include code and file contents attached to conversations.', - }, - 'Export', - ); - if (confirmed !== 'Export') return; - - const summaries = await this.stores.conversations.list(); - const storedConversations = await Promise.all(summaries.map(({ id }) => this.stores.conversations.get(id))); - const conversations = storedConversations.filter((conversation) => conversation !== undefined); - if (conversations.length !== summaries.length) { - throw new Error('Some conversations could not be loaded.'); + return this.enqueue(async () => { + try { + const confirmed = await vscode.window.showWarningMessage( + 'Export history?', + { + modal: true, + detail: 'Includes all workspaces and may contain attached code and file contents.', + }, + 'Export', + ); + if (confirmed !== 'Export') return; + + const workspaces: ConversationHistory['workspaces'] = []; + for (const workspaceKey of await this.stores.conversations.listWorkspaces()) { + if (!isConversationWorkspaceKey(workspaceKey)) throw new Error('Invalid workspace history directory.'); + const store = this.stores.conversations.forWorkspace(workspaceKey); + const conversations = await Promise.all((await store.list()).map(({ id }) => store.get(id))); + if (!conversations.every((conversation) => conversation !== undefined)) { + throw new Error('Some conversations could not be loaded.'); + } + if (conversations.length > 0) workspaces.push({ workspaceKey, conversations }); + } + const history = { exportedAt: new Date().toISOString(), workspaces }; + const date = history.exportedAt.slice(0, 10); + const content = JSON.stringify(history, null, 2); + await this.setFeedback('success', 'History download started.'); + return { + type: 'settings.historyExport', + filename: `conversation-history-${date}.json`, + content: `${content}\n`, + }; + } catch (error) { + const detail = error instanceof Error ? error.message : 'Unknown error.'; + await this.setFeedback('error', `Unable to export history. ${detail}`); } + }); + } - const date = new Date().toISOString().slice(0, 10); - const content = JSON.stringify( - { - version: DEFAULT_STORE_VERSION, - exportedAt: new Date().toISOString(), - conversations, - }, - null, - 2, - ); - await this.setFeedback('success', 'Conversation history download started.'); - return { - type: 'settings.historyExport', - filename: `github1s-ai-conversation-history-${date}.json`, - content: `${content}\n`, - }; - } catch (error) { - const detail = error instanceof Error ? error.message : 'Unknown error.'; - await this.setFeedback('error', `Unable to export conversation history. ${detail}`); - } + @Controller.handler('settings.importHistory') + async handleImportHistory(event: ViewEvent<'settings.importHistory'>): Promise { + return this.enqueue(async () => { + try { + const history = await parseConversationHistory(event.content); + if (this.runner.isBusy()) throw new Error('Stop all responses before importing history.'); + const currentId = (await this.stores.runtime.get()).chat.conversation?.id; + let importedCurrent: Conversation | undefined; + const deletions = new Map(); + if (event.options.mode === 'replace') { + for (const workspaceKey of await this.stores.conversations.listWorkspaces()) { + const importedIds = new Set( + history.workspaces + .find((workspace) => workspace.workspaceKey === workspaceKey) + ?.conversations.map(({ id }) => id), + ); + const local = await this.stores.conversations.forWorkspace(workspaceKey).list(); + deletions.set( + workspaceKey, + local.filter(({ id }) => !importedIds.has(id)).map(({ id }) => id), + ); + } + } + for (const { workspaceKey, conversations } of history.workspaces) { + const store = this.stores.conversations.forWorkspace(workspaceKey); + const existingIds = new Set((await store.list()).map(({ id }) => id)); + for (const conversation of conversations) { + if (existingIds.has(conversation.id)) { + if (event.options.mode === 'merge' && event.options.conflicts === 'keep') continue; + await store.replace(conversation); + if (store === this.stores.conversations && conversation.id === currentId) importedCurrent = conversation; + } else { + await store.append(conversation); + } + } + } + for (const [workspaceKey, ids] of deletions) { + const store = this.stores.conversations.forWorkspace(workspaceKey); + await store.delete(ids); + await store.select(undefined); + } + const runtime = await this.stores.runtime.get(); + let chat = runtime.chat; + if (event.options.mode === 'replace') { + chat = { ...chat, conversation: undefined, editing: undefined, pendingAttachments: [], notice: undefined }; + } else if (importedCurrent && chat.conversation?.id === importedCurrent.id) { + chat = { + ...chat, + conversation: markStreamingMessagesUnknown(importedCurrent), + editing: undefined, + pendingAttachments: [], + notice: undefined, + }; + } + await this.stores.runtime.set({ + ...runtime, + chat, + history: {}, + settings: { feedback: { severity: 'success', message: 'History imported.' } }, + }); + } catch (error) { + const detail = error instanceof Error ? error.message : 'Unknown error.'; + await this.setFeedback('error', `Unable to import history. ${detail}`); + } + }); } @Controller.handler('settings.clearAllData') async handleClearAllData(_event: ViewEvent<'settings.clearAllData'>): Promise { - try { - const confirmed = await vscode.window.showWarningMessage( - 'Clear all GitHub1s AI data?', - { - modal: true, - detail: - 'This deletes conversation history across all workspaces, model settings, MCP settings, and prompt settings.', - }, - 'Clear all data', - ); - if (confirmed !== 'Clear all data') return; - - await this.runner.cancelAll(); - await Promise.all([ - this.stores.conversations.clearGlobal(), - this.stores.modelConfigs.clear(), - this.stores.mcpConfig.clear(), - this.stores.promptsConfig.clear(), - ]); - await this.stores.runtime.set({ - page: 'settings', - chat: {}, - history: {}, - settings: { feedback: { severity: 'success', message: 'All data cleared.' } }, - }); - } catch (error) { - const detail = error instanceof Error ? error.message : 'Unknown error.'; - await this.setFeedback('error', `Unable to clear all data. ${detail}`); - } + return this.enqueue(async () => { + try { + const confirmed = await vscode.window.showWarningMessage( + 'Clear all GitHub1s AI data?', + { + modal: true, + detail: + 'This deletes conversation history across all workspaces, model settings, MCP settings, and prompt settings.', + }, + 'Clear all data', + ); + if (confirmed !== 'Clear all data') return; + + await this.runner.cancelAll(); + await Promise.all([ + this.stores.conversations.clearGlobal(), + this.stores.modelConfigs.clear(), + this.stores.mcpConfig.clear(), + this.stores.promptsConfig.clear(), + ]); + await this.stores.runtime.set({ + page: 'settings', + chat: {}, + history: {}, + settings: { feedback: { severity: 'success', message: 'All data cleared.' } }, + }); + } catch (error) { + const detail = error instanceof Error ? error.message : 'Unknown error.'; + await this.setFeedback('error', `Unable to clear all data. ${detail}`); + } + }); } @Controller.handler('settings.selectModelConfig') diff --git a/extensions/github1s-ai/src/stores/conversations.ts b/extensions/github1s-ai/src/stores/conversations.ts index 876560797..c26e4a2ab 100644 --- a/extensions/github1s-ai/src/stores/conversations.ts +++ b/extensions/github1s-ai/src/stores/conversations.ts @@ -1,8 +1,8 @@ -import type { LanguageModelUsage } from 'ai'; import { isPlainObject } from 'lodash-es'; import * as vscode from 'vscode'; import { + isConversationSummary, validateConversationMessages, type Conversation, type ConversationMessage, @@ -38,14 +38,34 @@ export class ConversationsStore { private detailsTimerMap = new Map; deadline: number }>(); private readonly detailsWrites = new Set>(); - constructor(context: vscode.ExtensionContext, workspaceKey: string) { + constructor( + private readonly context: vscode.ExtensionContext, + private readonly workspaceKey: string, + ) { this.rootDirectoryUri = vscode.Uri.joinPath(context.globalStorageUri, 'conversations'); this.dataDirectoryUri = vscode.Uri.joinPath(this.rootDirectoryUri, workspaceKey); this.indexPersist = new FilePersist({ fileUri: vscode.Uri.joinPath(this.dataDirectoryUri, 'index.json'), + check: isConversationIndex, }); } + forWorkspace(workspaceKey: string): ConversationsStore { + return workspaceKey === this.workspaceKey ? this : new ConversationsStore(this.context, workspaceKey); + } + + async listWorkspaces(): Promise { + const keys = new Set([this.workspaceKey]); + try { + for (const [key, type] of await vscode.workspace.fs.readDirectory(this.rootDirectoryUri)) { + if (type === vscode.FileType.Directory) keys.add(key); + } + } catch (error) { + if ((error as { code?: string })?.code !== 'FileNotFound') throw error; + } + return [...keys].sort(); + } + async list(): Promise { return (await this.readIndex()).summaries; } @@ -109,13 +129,46 @@ export class ConversationsStore { ...(conversation.usage === undefined ? {} : { usage: conversation.usage }), }; const summaries = [...conversations, summary]; - await this.writeIndex({ ...state, summaries }); const detail = { id: conversation.id, messages }; - await this.getDetailsPersist(conversation.id).write(detail); + const persist = this.getDetailsPersist(conversation.id); + await persist.write(detail); + try { + await this.writeIndex({ ...state, summaries }); + } catch (error) { + await persist.delete().catch(() => undefined); + throw error; + } this.detailsCacheMap.set(conversation.id, detail); }); } + async replace(conversation: Conversation): Promise { + return this.enqueue(async () => { + if (!isConversationSummary(conversation)) throw new Error('Invalid conversation object'); + const { messages, ...summary } = conversation; + const detail = { id: summary.id, messages: await validateMessages(messages, 'Invalid conversation object') }; + const state = await this.readIndex(); + if (!state.summaries.some(({ id }) => id === summary.id)) { + throw new Error(`Conversation with id ${summary.id} not found.`); + } + const pending = this.detailsTimerMap.get(summary.id); + if (pending) { + clearTimeout(pending.timer); + this.detailsTimerMap.delete(summary.id); + } + await Promise.allSettled([...this.detailsWrites]); + const persist = this.getDetailsPersist(summary.id); + // Preserve pending local messages if writing the replacement fails. + if (pending) await persist.write(this.detailsCacheMap.get(summary.id)!); + await persist.write(detail); + this.detailsCacheMap.set(summary.id, detail); + await this.writeIndex({ + ...state, + summaries: state.summaries.map((item) => (item.id === summary.id ? summary : item)), + }); + }); + } + async update(id: string, data: Partial): Promise { return this.enqueue(async () => { const state = await this.readIndex(); @@ -159,26 +212,38 @@ export class ConversationsStore { }); } - async delete(id: string): Promise { + async delete(ids: string[]): Promise { + const requested = new Set(ids); + if (requested.size === 0) return; return this.enqueue(async () => { const state = await this.readIndex(); - const conversations = state.summaries; - const index = conversations.findIndex((c) => c.id === id); - if (index === -1) { - throw new Error(`Conversation with id ${id} not found.`); + const existingIds = new Set(state.summaries.map(({ id }) => id)); + for (const id of requested) { + if (!existingIds.has(id)) throw new Error(`Conversation with id ${id} not found.`); } - if (this.detailsTimerMap.has(id)) { - clearTimeout(this.detailsTimerMap.get(id)!.timer); - this.detailsTimerMap.delete(id); + for (const id of requested) { + if (this.detailsTimerMap.has(id)) { + clearTimeout(this.detailsTimerMap.get(id)!.timer); + this.detailsTimerMap.delete(id); + } } await Promise.allSettled([...this.detailsWrites]); - await this.getDetailsPersist(id).delete(); - this.detailsCacheMap.delete(id); - const summaries = conversations.filter((_, itemIndex) => itemIndex !== index); - await this.writeIndex({ - selectedId: state.selectedId === id ? undefined : state.selectedId, - summaries, - }); + const deleted = new Set(); + try { + for (const id of requested) { + await this.getDetailsPersist(id).delete(); + this.detailsCacheMap.delete(id); + deleted.add(id); + } + } finally { + // Save completed deletions even if a later file cannot be removed. + if (deleted.size > 0) { + await this.writeIndex({ + selectedId: state.selectedId !== undefined && deleted.has(state.selectedId) ? undefined : state.selectedId, + summaries: state.summaries.filter(({ id }) => !deleted.has(id)), + }); + } + } }); } @@ -202,10 +267,7 @@ export class ConversationsStore { private async readIndex(): Promise { if (this.indexCache === undefined) { - const stored = await this.indexPersist.read(); - const summaries = sanitizeConversationSummaries(stored?.summaries); - const selectedId = summaries.some(({ id }) => id === stored?.selectedId) ? stored?.selectedId : undefined; - this.indexCache = { selectedId, summaries }; + this.indexCache = (await this.indexPersist.read()) ?? { summaries: [] }; } return this.indexCache; } @@ -229,70 +291,16 @@ export class ConversationsStore { } } -const isConversationSummary = (value: unknown): value is ConversationSummary => { - if (!hasConversationSummaryFields(value)) return false; - return value.usage === undefined || isLanguageModelUsage(value.usage); -}; - -const sanitizeConversationSummaries = (value: unknown): ConversationSummary[] => { - if (!Array.isArray(value)) return []; - const summaries: ConversationSummary[] = []; - const ids = new Set(); - for (const item of value) { - if (!hasConversationSummaryFields(item) || ids.has(item.id)) continue; - ids.add(item.id); - summaries.push({ - id: item.id, - title: item.title, - createdAt: item.createdAt, - updatedAt: item.updatedAt, - ...(isLanguageModelUsage(item.usage) ? { usage: item.usage } : {}), - }); - } - return summaries; -}; - -const hasConversationSummaryFields = ( - value: unknown, -): value is Record & Pick => { - if (!isPlainObject(value)) return false; - const summary = value as Record; - return ( - typeof summary.id === 'string' && - summary.id.length > 0 && - typeof summary.title === 'string' && - typeof summary.createdAt === 'number' && - Number.isFinite(summary.createdAt) && - summary.createdAt >= 0 && - typeof summary.updatedAt === 'number' && - Number.isFinite(summary.updatedAt) && - summary.updatedAt >= summary.createdAt - ); -}; - -const isLanguageModelUsage = (value: unknown): value is LanguageModelUsage => { +const isConversationIndex = (value: unknown): value is ConversationIndex => { if (!isPlainObject(value)) return false; - const usage = value as Record; - const inputTokenDetails = usage.inputTokenDetails; - const outputTokenDetails = usage.outputTokenDetails; - if (!isPlainObject(inputTokenDetails) || !isPlainObject(outputTokenDetails)) return false; - const input = inputTokenDetails as Record; - const output = outputTokenDetails as Record; + const index = value as Record; return ( - isTokenCount(usage.inputTokens) && - isTokenCount(input.noCacheTokens) && - isTokenCount(input.cacheReadTokens) && - isTokenCount(input.cacheWriteTokens) && - isTokenCount(usage.outputTokens) && - isTokenCount(output.textTokens) && - isTokenCount(output.reasoningTokens) && - isTokenCount(usage.totalTokens) + Array.isArray(index.summaries) && + index.summaries.every(isConversationSummary) && + (index.selectedId === undefined || typeof index.selectedId === 'string') ); }; -const isTokenCount = (value: unknown): value is number | undefined => - value === undefined || (typeof value === 'number' && Number.isFinite(value) && value >= 0); - const validateMessages = async (value: unknown, message: string): Promise => { try { return await validateConversationMessages(value); diff --git a/extensions/github1s-ai/src/stores/index.ts b/extensions/github1s-ai/src/stores/index.ts index 0ace1205a..b8fde1a24 100644 --- a/extensions/github1s-ai/src/stores/index.ts +++ b/extensions/github1s-ai/src/stores/index.ts @@ -18,7 +18,17 @@ export interface Stores { readonly promptsConfig: Pick; readonly conversations: Pick< ConversationsStore, - 'list' | 'get' | 'getSelected' | 'select' | 'append' | 'update' | 'delete' | 'clearGlobal' + | 'list' + | 'get' + | 'getSelected' + | 'select' + | 'append' + | 'replace' + | 'update' + | 'delete' + | 'clearGlobal' + | 'forWorkspace' + | 'listWorkspaces' >; } diff --git a/extensions/github1s-ai/src/webview/components/HistoryImportDialog.ts b/extensions/github1s-ai/src/webview/components/HistoryImportDialog.ts new file mode 100644 index 000000000..d73e8d74b --- /dev/null +++ b/extensions/github1s-ai/src/webview/components/HistoryImportDialog.ts @@ -0,0 +1,115 @@ +import { html } from 'htm/preact'; +import { useEffect, useRef, useState } from 'preact/hooks'; + +import type { ConversationHistory, HistoryImportOptions } from '@/common/conversation'; + +import { Icon } from './Icon'; +import { TooltipButton } from './Tooltip'; + +interface HistoryImportDialogProps { + filename: string; + history: ConversationHistory; + onImport: (options: HistoryImportOptions) => void; + onCancel: () => void; +} + +export const HistoryImportDialog = ({ filename, history, onImport, onCancel }: HistoryImportDialogProps) => { + const dialog = useRef(null); + const [mode, setMode] = useState<'merge' | 'replace'>('merge'); + const [conflicts, setConflicts] = useState<'keep' | 'overwrite'>('keep'); + const workspaceCount = history.workspaces.length; + const conversationCount = history.workspaces.reduce((count, workspace) => count + workspace.conversations.length, 0); + const summary = `${workspaceCount} ${workspaceCount === 1 ? 'workspace' : 'workspaces'} ยท ${conversationCount} ${conversationCount === 1 ? 'conversation' : 'conversations'}`; + + useEffect(() => { + const element = dialog.current!; + element.showModal(); + return () => element.close(); + }, []); + + const submit = (event: SubmitEvent) => { + event.preventDefault(); + onImport(mode === 'merge' ? { mode, conflicts } : { mode }); + }; + + return html` +
+

Import history

+
+

${filename}

+

${summary}

+
+
+ + Import mode + <${TooltipButton} + class="icon-button" + label=${'Merge combines history by workspace.\nReplace uses only imported history.'} + > + <${Icon} name="info" /> + + + +
+ ${(['merge', 'replace'] as const).map( + (value) => + html``, + )} +
+
+ ${mode === 'merge' + ? html`
+ + On conflict + <${TooltipButton} + class="icon-button" + label=${'For matching IDs in the same workspace:\nKeep preserves the local conversation.\nOverwrite uses the imported conversation.'} + > + <${Icon} name="info" /> + + + +
+ ${(['keep', 'overwrite'] as const).map( + (value) => + html``, + )} +
+
` + : html`

+ This replaces all workspace history. Conversations not in the file will be deleted. +

`} +
+ + +
+
+
`; +}; diff --git a/extensions/github1s-ai/src/webview/components/Icon.ts b/extensions/github1s-ai/src/webview/components/Icon.ts index 43e549768..8ff65eec5 100644 --- a/extensions/github1s-ai/src/webview/components/Icon.ts +++ b/extensions/github1s-ai/src/webview/components/Icon.ts @@ -12,6 +12,7 @@ const ICON_PATHS = { file: 'M3 1h6l4 4v10H3zm6 1.4V5h2.6zM4 2v12h8V6H8V2z', fork: 'M4 4.5v7m0-3.5h5a3 3 0 0 0 3-3v-.5M4 1.5a1.5 1.5 0 1 0 0 3 1.5 1.5 0 0 0 0-3m8 0a1.5 1.5 0 1 0 0 3 1.5 1.5 0 0 0 0-3M4 11.5a1.5 1.5 0 1 0 0 3 1.5 1.5 0 0 0 0-3', history: 'M8 1a7 7 0 1 1-6.7 9h1.06a6 6 0 1 0 .44-5H5v1H1V2h1v2.4A7 7 0 0 1 8 1m-.5 3h1v4.2l2.85 1.65-.5.86L7.5 8.8z', + info: 'M8 1.5a6.5 6.5 0 1 0 0 13a6.5 6.5 0 0 0 0-13M8 7v4M8 4.5v.5', refresh: 'M8 1a7 7 0 1 1-6.7 9h1.06a6 6 0 1 0 .44-5H5v1H1V2h1v2.4A7 7 0 0 1 8 1', repo: 'M2 2h5l1 2h6v10H2zm1 1v10h10V5H7.4l-1-2z', selection: 'M2 2h4v1H3v3H2zm8 0h4v4h-1V3h-3zm-8 8h1v3h3v1H2zm11 0h1v4h-4v-1h3z', @@ -20,6 +21,7 @@ const ICON_PATHS = { stop: 'M4 4h8v8H4z', terminal: 'M2 3h12v10H2zm1 1v8h10V4zm1.5 2 .7-.7L7.9 8l-2.7 2.7-.7-.7 2-2zm4 4H12v1H8.5z', trash: 'M5 2h6l.5 1.5H14v1H2v-1h2.5zM4 6h1l.5 7h5l.5-7h1l-.6 8H4.6z', + upload: 'M7.5 11h1V2.9l2.8 2.8.7-.7-4-4-4 4 .7.7 2.8-2.8zM2 12h1v2h10v-2h1v3H2z', warning: 'M8 1.5 15 14H1zm0 2.3L2.9 13h10.2zm-.6 2.7h1.2v3.8H7.4zm0 5h1.2v1.2H7.4z', } as const; @@ -31,7 +33,7 @@ interface IconProps { } export const Icon = ({ name, className }: IconProps) => { - const stroked = name === 'close' || name === 'edit' || name === 'fork'; + const stroked = name === 'close' || name === 'edit' || name === 'fork' || name === 'info'; return html` { : html`<${GeneralSettings} notice=${feedback} onExport=${() => post({ type: 'settings.exportHistory' })} + onImport=${(content: string, options: HistoryImportOptions) => + post({ type: 'settings.importHistory', content, options })} onClear=${() => post({ type: 'settings.clearAllData' })} />`}`; @@ -134,37 +138,91 @@ const SettingsTabs = ({ active, onChange }: SettingsTabsProps) => { interface GeneralSettingsProps { notice?: Notice; onExport: () => void; + onImport: (content: string, options: HistoryImportOptions) => void; onClear: () => void; } -const GeneralSettings = ({ notice, onExport, onClear }: GeneralSettingsProps) => html` -
-

Manage conversation history and locally stored GitHub1s AI data.

- <${SettingsNotice} notice=${notice} /> -
-
-
- Conversation history -

Download all conversations as JSON. Attached code and file contents may be included.

+const GeneralSettings = ({ notice, onExport, onImport, onClear }: GeneralSettingsProps) => { + const fileInput = useRef(null); + const [importFile, setImportFile] = useState<{ filename: string; history: ConversationHistory }>(); + const [reading, setReading] = useState(false); + const [fileError, setFileError] = useState(); + useEffect(() => setFileError(undefined), [notice]); + + const readFile = async (event: Event) => { + const input = event.currentTarget as HTMLInputElement; + const file = input.files?.[0]; + input.value = ''; + if (!file) return; + setFileError(undefined); + setReading(true); + try { + const { parseConversationHistory } = await import('@/common/conversation'); + const history = await parseConversationHistory(await file.text()); + setImportFile({ filename: file.name, history }); + } catch (error) { + setFileError({ + severity: 'error', + message: error instanceof Error ? error.message : 'Unable to read this file.', + }); + } finally { + setReading(false); + } + }; + + return html` +
+

Manage saved history and settings.

+ <${SettingsNotice} notice=${fileError ?? notice} /> +
+
+
+ Conversation history +

Import or export history for all workspaces as JSON.

+
+
+ + + +
+

Close other GitHub1s tabs and reload this page before import or export.

- -
-
-
- All local data -

Permanently delete conversations across all workspaces, model settings, MCP settings, and prompts.

+
+
+ All local data +

Permanently delete conversations across all workspaces, model settings, MCP settings, and prompts.

+
+
-
+ ${importFile + ? html`<${HistoryImportDialog} + filename=${importFile.filename} + history=${importFile.history} + onImport=${(options: HistoryImportOptions) => { + onImport(JSON.stringify(importFile.history), options); + setImportFile(undefined); + }} + onCancel=${() => setImportFile(undefined)} + />` + : null}
-
-`; + `; +}; const SettingsNotice = ({ notice }: { notice?: Notice }) => notice diff --git a/extensions/github1s-ai/src/webview/components/Tooltip.ts b/extensions/github1s-ai/src/webview/components/Tooltip.ts index cac85b0f5..76b9e2b4d 100644 --- a/extensions/github1s-ai/src/webview/components/Tooltip.ts +++ b/extensions/github1s-ai/src/webview/components/Tooltip.ts @@ -100,7 +100,7 @@ export const Tooltip = ({ content, children }: TooltipProps) => { > ${content}
`, - document.body, + anchor.current?.closest('dialog') ?? document.body, ) : null} `; diff --git a/extensions/github1s-ai/test/protocol.test.ts b/extensions/github1s-ai/test/protocol.test.ts index 3e755bea0..66b3a4f4e 100644 --- a/extensions/github1s-ai/test/protocol.test.ts +++ b/extensions/github1s-ai/test/protocol.test.ts @@ -54,6 +54,27 @@ test('conversation title updates require an ID and a nonblank title', () => { } }); +test('history import events require file contents and an explicit valid import strategy', () => { + for (const event of [ + { type: 'settings.importHistory', content: '{}', options: { mode: 'merge', conflicts: 'keep' } }, + { type: 'settings.importHistory', content: '{}', options: { mode: 'merge', conflicts: 'overwrite' } }, + { type: 'settings.importHistory', content: '{}', options: { mode: 'replace' } }, + ]) { + assert.deepEqual(parseViewEvent(event), event); + } + for (const event of [ + { type: 'settings.importHistory', options: { mode: 'replace' } }, + { type: 'settings.importHistory', content: {}, options: { mode: 'replace' } }, + { type: 'settings.importHistory', content: '{}', options: { mode: 'merge' } }, + { type: 'settings.importHistory', content: '{}', options: { mode: 'merge', conflicts: 'unknown' } }, + { type: 'settings.importHistory', content: '{}', options: { mode: 'replace', conflicts: 'keep' } }, + { type: 'settings.importHistory', content: '{}', options: { mode: 'unknown' } }, + { type: 'settings.importHistory', content: '{}', options: { mode: 'replace' }, extra: true }, + ]) { + assert.equal(parseViewEvent(event), undefined); + } +}); + test('highlight requests enforce the source length limit and required fields', () => { const request = { type: 'markdown.highlight', From 248fd121d753d3ae8ec7063326d71ad12e807baf Mon Sep 17 00:00:00 2001 From: netcon Date: Tue, 17 Nov 2026 17:09:28 +0800 Subject: [PATCH 2/2] chore: fix ci --- .github/workflows/build.yml | 2 +- .github/workflows/test-wtih-vscode-build.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 4c487267d..0be8c20ff 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -15,7 +15,7 @@ jobs: strategy: matrix: - os: [macos-14] + os: [macos-26] node-version: [24.x] runs-on: ${{ matrix.os }} diff --git a/.github/workflows/test-wtih-vscode-build.yml b/.github/workflows/test-wtih-vscode-build.yml index 2d35e02a9..adcc9aeaf 100644 --- a/.github/workflows/test-wtih-vscode-build.yml +++ b/.github/workflows/test-wtih-vscode-build.yml @@ -15,7 +15,7 @@ jobs: strategy: matrix: - os: [macos-14] + os: [macos-26] node-version: [24.x] runs-on: ${{ matrix.os }}