From 1e212c0ccfc624aab15a58ea1d24e6acc186f929 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 21 Oct 2026 09:22:35 +0800 Subject: [PATCH 01/19] chore(deps): bump markdown-it in /extensions/github1s-ai (#785) Bumps [markdown-it](https://github.com/markdown-it/markdown-it) from 15.0.1 to 15.0.3. - [Changelog](https://github.com/markdown-it/markdown-it/blob/master/CHANGELOG.md) - [Commits](https://github.com/markdown-it/markdown-it/compare/15.0.1...15.0.3) --- updated-dependencies: - dependency-name: markdown-it dependency-version: 15.0.3 dependency-type: direct:production ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- extensions/github1s-ai/package-lock.json | 28 ++++++++++++------------ extensions/github1s-ai/package.json | 2 +- 2 files changed, 15 insertions(+), 15 deletions(-) diff --git a/extensions/github1s-ai/package-lock.json b/extensions/github1s-ai/package-lock.json index 8f40b1e70..80aec5519 100644 --- a/extensions/github1s-ai/package-lock.json +++ b/extensions/github1s-ai/package-lock.json @@ -18,7 +18,7 @@ "htm": "3.1.1", "katex": "0.18.2", "lodash-es": "4.18.1", - "markdown-it": "15.0.1", + "markdown-it": "15.0.3", "mermaid": "12.2.0", "preact": "10.29.8" }, @@ -1545,9 +1545,9 @@ } }, "node_modules/argparse": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/argparse/-/argparse-3.0.0.tgz", - "integrity": "sha512-BOp5NMrHqKxmq/OLr+clzzrRxgOKSLkcjmkWuChp7Irqwn4s74WjOBPIgWfA/HMcBnVkZ5XEuf9uUqzlpfCQ6A==", + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-3.0.3.tgz", + "integrity": "sha512-Sn98ftV3KfsO8xfLPHG6oT8y+b0yvbrLgZjgPDXsharNY15tTAjqIsIju4S32nl6/iEUNNE4v+yL2Zhm8ooP3w==", "funding": [ { "type": "github", @@ -1558,7 +1558,7 @@ "url": "https://github.com/sponsors/nodeca" } ], - "license": "Python-2.0" + "license": "PSF-2.0" }, "node_modules/baseline-browser-mapping": { "version": "2.11.13", @@ -2705,9 +2705,9 @@ } }, "node_modules/entities": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/entities/-/entities-8.0.0.tgz", - "integrity": "sha512-zwfzJecQ/Uej6tusMqwAqU/6KL2XaB2VZ2Jg54Je6ahNBGNH6Ek6g3jjNCF0fG9EWQKGZNddNjU5F1ZQn/sBnA==", + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/entities/-/entities-8.1.0.tgz", + "integrity": "sha512-kxL7msIffSuh9aaFAMD7rxAIuTRMAHMeBtgHW2yUdWw732ZNh4MehkF2gdjvtdmikkaIP9bFDDJOPlsvm7avrA==", "license": "BSD-2-Clause", "engines": { "node": ">=20.19.0" @@ -3345,9 +3345,9 @@ "license": "MIT" }, "node_modules/markdown-it": { - "version": "15.0.1", - "resolved": "https://registry.npmjs.org/markdown-it/-/markdown-it-15.0.1.tgz", - "integrity": "sha512-9/7gE95FNPkfUWrjJIoHZza2iLmuJlPD0UNMxPi7bxUrbCR525YZY0r+zyfes0dZI5ZZ/uNIXUJca0pJvtw41g==", + "version": "15.0.3", + "resolved": "https://registry.npmjs.org/markdown-it/-/markdown-it-15.0.3.tgz", + "integrity": "sha512-+Az7Ojz3iRGu8KYMvJ6xVhvrxP3eE+vEtJX75Ow88XBpcQNV/0lGX5ZynIIBftREo4DC2jsveAMDaeltmm8QvQ==", "funding": [ { "type": "github", @@ -3360,9 +3360,9 @@ ], "license": "MIT", "dependencies": { - "argparse": "^3.0.0", - "entities": "^8.0.0", - "linkify-it": "^6.0.0", + "argparse": "^3.0.3", + "entities": "^8.1.0", + "linkify-it": "^6.1.0", "mdurl": "^2.1.0", "punycode.js": "^2.3.1", "uc.micro": "^3.0.0" diff --git a/extensions/github1s-ai/package.json b/extensions/github1s-ai/package.json index dbab84ba7..0706e0ff3 100644 --- a/extensions/github1s-ai/package.json +++ b/extensions/github1s-ai/package.json @@ -123,7 +123,7 @@ "htm": "3.1.1", "katex": "0.18.2", "lodash-es": "4.18.1", - "markdown-it": "15.0.1", + "markdown-it": "15.0.3", "mermaid": "12.2.0", "preact": "10.29.8" }, From bf13d041f1e3ece9fa0bce7639bc093203871db5 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 21 Oct 2026 16:57:49 +0800 Subject: [PATCH 02/19] chore(deps-dev): bump launch-editor from 2.14.1 to 2.14.2 (#786) Bumps [launch-editor](https://github.com/vitejs/launch-editor) from 2.14.1 to 2.14.2. - [Commits](https://github.com/vitejs/launch-editor/compare/v2.14.1...v2.14.2) --- updated-dependencies: - dependency-name: launch-editor dependency-version: 2.14.2 dependency-type: indirect ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- package-lock.json | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/package-lock.json b/package-lock.json index 49edf0c32..c0b4c75e2 100644 --- a/package-lock.json +++ b/package-lock.json @@ -5597,14 +5597,14 @@ } }, "node_modules/launch-editor": { - "version": "2.14.1", - "resolved": "https://registry.npmjs.org/launch-editor/-/launch-editor-2.14.1.tgz", - "integrity": "sha512-QWBrQsMpH7gPr965dsKD/3cKWiNoTjpATQf++Xq63N6sKRGMwlVXz41O1IZTMfZQgBctD/K5Zt06+/I6pP6+HA==", + "version": "2.14.2", + "resolved": "https://registry.npmjs.org/launch-editor/-/launch-editor-2.14.2.tgz", + "integrity": "sha512-NHJEb30MGBCkmZXLZwz25t37QR4aY03ZzPYUJXOJaOa92uWwExI9SBQUuIznBYc1xkD7cJNGX7oc3Nl3sq2kQQ==", "dev": true, "license": "MIT", "dependencies": { "picocolors": "^1.1.1", - "shell-quote": "^1.8.4" + "shell-quote": "^1.10.0" } }, "node_modules/lazy-ass": { From 3b21f4872961884ffeb5216a4c8b4df366bbe1d6 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 2 Nov 2026 13:13:05 +0800 Subject: [PATCH 03/19] chore(deps-dev): bump fast-uri from 3.1.7 to 3.1.9 (#791) Bumps [fast-uri](https://github.com/fastify/fast-uri) from 3.1.7 to 3.1.9. - [Release notes](https://github.com/fastify/fast-uri/releases) - [Commits](https://github.com/fastify/fast-uri/compare/v3.1.7...v3.1.9) --- updated-dependencies: - dependency-name: fast-uri dependency-version: 3.1.9 dependency-type: indirect ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- package-lock.json | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/package-lock.json b/package-lock.json index c0b4c75e2..f637dcc5b 100644 --- a/package-lock.json +++ b/package-lock.json @@ -3928,9 +3928,9 @@ "license": "MIT" }, "node_modules/fast-uri": { - "version": "3.1.7", - "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.7.tgz", - "integrity": "sha512-dOvZVzjdZdz7phd9v6jCbwxrBW3fK6n8Rc0CtdmM4bumzMnxywBYhuph6J819RRw/ku+rLbelwfMunktuzVVHg==", + "version": "3.1.9", + "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.9.tgz", + "integrity": "sha512-hS/0Wt3Ya043oKXs0sIxrMpKQITXhMLIrVAKKXi4gozGC9v7YRWVnXIZzjNPTO02M9BdxLCWqK1yRXgNziVyJQ==", "dev": true, "funding": [ { From ab08118af1e103f3c462162f7354faaa47105961 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 2 Nov 2026 13:13:49 +0800 Subject: [PATCH 04/19] chore(deps-dev): bump fast-uri in /extensions/github1s (#790) Bumps [fast-uri](https://github.com/fastify/fast-uri) from 3.1.7 to 3.1.9. - [Release notes](https://github.com/fastify/fast-uri/releases) - [Commits](https://github.com/fastify/fast-uri/compare/v3.1.7...v3.1.9) --- updated-dependencies: - dependency-name: fast-uri dependency-version: 3.1.9 dependency-type: indirect ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- extensions/github1s/package-lock.json | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/extensions/github1s/package-lock.json b/extensions/github1s/package-lock.json index c12985c14..319f9b970 100644 --- a/extensions/github1s/package-lock.json +++ b/extensions/github1s/package-lock.json @@ -1618,9 +1618,9 @@ "license": "MIT" }, "node_modules/fast-uri": { - "version": "3.1.7", - "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.7.tgz", - "integrity": "sha512-dOvZVzjdZdz7phd9v6jCbwxrBW3fK6n8Rc0CtdmM4bumzMnxywBYhuph6J819RRw/ku+rLbelwfMunktuzVVHg==", + "version": "3.1.9", + "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.9.tgz", + "integrity": "sha512-hS/0Wt3Ya043oKXs0sIxrMpKQITXhMLIrVAKKXi4gozGC9v7YRWVnXIZzjNPTO02M9BdxLCWqK1yRXgNziVyJQ==", "dev": true, "funding": [ { From 814c47a2d50ba34939b14d14efa9fa34fc6e4dca Mon Sep 17 00:00:00 2001 From: netcon Date: Tue, 3 Nov 2026 12:06:49 +0800 Subject: [PATCH 05/19] feat(ai): allow edit user message (#796) --- extensions/github1s-ai/assets/chat.css | 18 ++++ extensions/github1s-ai/src/common/protocol.ts | 5 + extensions/github1s-ai/src/common/state.ts | 5 + extensions/github1s-ai/src/controllers/app.ts | 2 +- .../github1s-ai/src/controllers/chat.ts | 101 ++++++++++-------- .../github1s-ai/src/controllers/history.ts | 5 +- .../github1s-ai/src/controllers/runner.ts | 98 +++++++++++++---- .../src/webview/components/ChatPage.ts | 53 ++++++--- .../src/webview/components/Composer.ts | 60 +++++++++-- .../src/webview/components/MessageView.ts | 35 ++++-- extensions/github1s-ai/test/runner.test.ts | 2 +- 11 files changed, 293 insertions(+), 91 deletions(-) diff --git a/extensions/github1s-ai/assets/chat.css b/extensions/github1s-ai/assets/chat.css index 0ce9b903e..634822834 100644 --- a/extensions/github1s-ai/assets/chat.css +++ b/extensions/github1s-ai/assets/chat.css @@ -724,6 +724,24 @@ summary:focus-visible, line-height: 1.55; } +.user-request-editable { + cursor: text; +} + +.user-request-editable:hover { + border-color: var(--vscode-focusBorder); +} + +.message[inert], +.composer-wrap[inert] { + opacity: 0.5; +} + +.message-editing .composer-wrap { + padding: 0; + background: transparent; +} + .assistant-response > .markdown + .markdown { margin-top: 0.75em; } diff --git a/extensions/github1s-ai/src/common/protocol.ts b/extensions/github1s-ai/src/common/protocol.ts index 9b521d02f..ceaa4a8e2 100644 --- a/extensions/github1s-ai/src/common/protocol.ts +++ b/extensions/github1s-ai/src/common/protocol.ts @@ -41,6 +41,7 @@ type AllViewEvents = | { type: 'app.openSettings' } | { type: 'app.openFile'; source: string } | { type: 'chat.send'; text: string } + | { type: 'chat.setEditingMessageId'; id?: string } | { type: 'chat.retry'; id: string } | { type: 'chat.runQuickAction'; action: ChatQuickAction } | { type: 'chat.addContextAttachment'; action: ContextAttachmentAction } @@ -92,6 +93,10 @@ export const parseViewEvent = (value: unknown): ViewEvent | undefined => { ? { type: event.type, text: event.text } : undefined; + case 'chat.setEditingMessageId': + if (hasExactKeys(event, ['type'])) return { type: event.type }; + return exactString(event, 'id') ? { type: event.type, id: event.id as string } : undefined; + case 'chat.setIncludeRecentFiles': return hasExactKeys(event, ['type', 'enabled']) && typeof event.enabled === 'boolean' ? { type: event.type, enabled: event.enabled } diff --git a/extensions/github1s-ai/src/common/state.ts b/extensions/github1s-ai/src/common/state.ts index 54f228c53..df937ee20 100644 --- a/extensions/github1s-ai/src/common/state.ts +++ b/extensions/github1s-ai/src/common/state.ts @@ -15,6 +15,11 @@ export interface RuntimeState { pendingAttachments?: ContextAttachmentDescriptor[]; recentFiles?: ContextReference[]; includeRecentFiles?: boolean; + editing?: { + messageId: string; + pendingAttachments: ContextAttachmentDescriptor[]; + includeRecentFiles: boolean; + }; preparing?: boolean; notice?: Notice; }; diff --git a/extensions/github1s-ai/src/controllers/app.ts b/extensions/github1s-ai/src/controllers/app.ts index 5898428e0..2aa805303 100644 --- a/extensions/github1s-ai/src/controllers/app.ts +++ b/extensions/github1s-ai/src/controllers/app.ts @@ -71,7 +71,7 @@ export class AppController extends Controller { chat: { ...runtime.chat, ...(resetConversation ? { conversation: undefined, pendingAttachments: [] } : {}), - ...(resetConversation || page !== 'chat' ? { notice: undefined } : {}), + ...(resetConversation || page !== 'chat' ? { editing: undefined, notice: undefined } : {}), }, history: { ...runtime.history, notice: undefined }, settings: { ...runtime.settings, feedback: undefined }, diff --git a/extensions/github1s-ai/src/controllers/chat.ts b/extensions/github1s-ai/src/controllers/chat.ts index d1bbd0f82..ad60e2cfd 100644 --- a/extensions/github1s-ai/src/controllers/chat.ts +++ b/extensions/github1s-ai/src/controllers/chat.ts @@ -1,4 +1,5 @@ import type { ContextAttachmentDescriptor } from '@/common/context'; +import { resolvePrompts } from '@/common/prompts-config'; import type { ViewEvent } from '@/common/protocol'; import { getQuickAction } from '@/common/quick-actions'; import type { Stores } from '@/stores'; @@ -17,12 +18,38 @@ export class ChatController extends Controller { @Controller.handler('chat.send') async handleSend(event: ViewEvent<'chat.send'>): Promise { - await this.runner.send({ text: event.text }); + const { chat } = await this.stores.runtime.get(); + if (chat.editing) await this.runner.edit(event.text); + else await this.runner.send(event.text); + } + + @Controller.handler('chat.setEditingMessageId') + async handleSetEditingMessageId(event: ViewEvent<'chat.setEditingMessageId'>): Promise { + const { chat } = await this.stores.runtime.get(); + if (chat.preparing || this.runner.isRequestActive(chat.conversation?.id)) return; + if (event.id === undefined) { + await this.stores.runtime.setIn('chat', { ...chat, editing: undefined, notice: undefined }); + return; + } + if (chat.editing?.messageId === event.id) return; + const message = chat.conversation?.messages.find((candidate) => candidate.id === event.id); + if (message?.role !== 'user') return; + await this.stores.runtime.setIn('chat', { + ...chat, + editing: { + messageId: message.id, + pendingAttachments: message.parts.flatMap((part) => + part.type === 'data-attachments' ? part.data.map(({ content, ...descriptor }) => descriptor) : [], + ), + includeRecentFiles: true, + }, + notice: undefined, + }); } @Controller.handler('chat.retry') async handleRetry(event: ViewEvent<'chat.retry'>): Promise { - await this.runner.send({ retryMessageId: event.id }); + await this.runner.retry(event.id); } @Controller.handler('chat.cancel') @@ -32,14 +59,18 @@ export class ChatController extends Controller { @Controller.handler('chat.setIncludeRecentFiles') async handleSetIncludeRecentFiles(event: ViewEvent<'chat.setIncludeRecentFiles'>): Promise { - await this.stores.runtime.setIn('chat.includeRecentFiles', event.enabled); + const { chat } = await this.stores.runtime.get(); + await this.stores.runtime.setIn( + chat.editing ? 'chat.editing.includeRecentFiles' : 'chat.includeRecentFiles', + event.enabled, + ); } @Controller.handler('chat.runQuickAction') async handleRunQuickAction(event: ViewEvent<'chat.runQuickAction'>): Promise { - const runtime = await this.stores.runtime.get(); + const { chat } = await this.stores.runtime.get(); const action = getQuickAction(event.action); - const attachment = action.attachment ? runtime.chat[action.attachment] : undefined; + const attachment = action.attachment ? chat[action.attachment] : undefined; if (action.attachment && !attachment) { const message = action.attachment === 'currentFile' @@ -48,29 +79,19 @@ export class ChatController extends Controller { await this.stores.runtime.setIn('chat.notice', { severity: 'error', message }); return; } - if (attachment) await this.add([attachment]); - await this.runner.send({ action: event.action }); + if (attachment) await this.add(attachment); + const prompts = resolvePrompts(await this.stores.promptsConfig.get()); + await this.runner.send(prompts.quickActions[event.action]); } @Controller.handler('chat.addContextAttachment') async handleAddContextAttachment(event: ViewEvent<'chat.addContextAttachment'>): Promise { - const runtime = await this.stores.runtime.get(); + const { chat } = await this.stores.runtime.get(); let descriptor: ContextAttachmentDescriptor | undefined; try { - switch (event.action) { - case 'selectFile': - descriptor = await selectFile(); - break; - case 'currentFile': - descriptor = runtime.chat.currentFile; - break; - case 'currentSelection': - descriptor = runtime.chat.currentSelection; - break; - case 'descriptor': - descriptor = event.descriptor; - break; - } + if (event.action === 'selectFile') descriptor = await selectFile(); + else if (event.action === 'descriptor') descriptor = event.descriptor; + else descriptor = chat[event.action]; } catch (error) { const detail = error instanceof Error ? error.message : 'Unknown error.'; await this.stores.runtime.setIn('chat.notice', { @@ -79,39 +100,35 @@ export class ChatController extends Controller { }); return; } - if (descriptor) await this.add([descriptor]); + if ((await this.stores.runtime.get()).chat.editing?.messageId !== chat.editing?.messageId) return; + if (descriptor) await this.add(descriptor); } @Controller.handler('chat.removeContextAttachment') async handleRemoveContextAttachment(event: ViewEvent<'chat.removeContextAttachment'>): Promise { const runtime = await this.stores.runtime.get(); + const context = runtime.chat.editing ?? runtime.chat; + const pendingAttachments = (context.pendingAttachments ?? []).filter(({ id }) => id !== event.id); await this.stores.runtime.setIn('chat', { ...runtime.chat, - pendingAttachments: (runtime.chat.pendingAttachments ?? []).filter(({ id }) => id !== event.id), + ...(runtime.chat.editing ? { editing: { ...runtime.chat.editing, pendingAttachments } } : { pendingAttachments }), notice: undefined, }); } - private async add(descriptors: readonly ContextAttachmentDescriptor[]): Promise { - const runtime = await this.stores.runtime.get(); + private async add(descriptor: ContextAttachmentDescriptor): Promise { + const { chat } = await this.stores.runtime.get(); + const pendingAttachments = [...(chat.editing?.pendingAttachments ?? chat.pendingAttachments ?? [])]; + const index = pendingAttachments.findIndex((existing) => isSameContextAttachment(existing, descriptor)); + const next = chat.editing + ? { ...descriptor, id: globalThis.crypto.randomUUID() } + : preserveContextAttachmentId(descriptor, pendingAttachments[index]); + if (index >= 0) pendingAttachments.splice(index, 1); + pendingAttachments.push(next); await this.stores.runtime.setIn('chat', { - ...runtime.chat, - pendingAttachments: mergeAttachmentDescriptors(runtime.chat.pendingAttachments ?? [], descriptors), + ...chat, + ...(chat.editing ? { editing: { ...chat.editing, pendingAttachments } } : { pendingAttachments }), notice: undefined, }); } } - -const mergeAttachmentDescriptors = ( - current: readonly ContextAttachmentDescriptor[], - incoming: readonly ContextAttachmentDescriptor[], -): ContextAttachmentDescriptor[] => { - const merged = current.map((descriptor) => ({ ...descriptor })); - for (const descriptor of incoming) { - const index = merged.findIndex((existing) => isSameContextAttachment(existing, descriptor)); - const next = preserveContextAttachmentId(descriptor, index >= 0 ? merged[index] : undefined); - if (index >= 0) merged.splice(index, 1); - merged.push(next); - } - return merged; -}; diff --git a/extensions/github1s-ai/src/controllers/history.ts b/extensions/github1s-ai/src/controllers/history.ts index c3fb5327c..cc40eb417 100644 --- a/extensions/github1s-ai/src/controllers/history.ts +++ b/extensions/github1s-ai/src/controllers/history.ts @@ -36,6 +36,7 @@ export class HistoryController extends Controller { chat: { ...runtime.chat, conversation, + editing: undefined, ...(runtime.chat.conversation?.id !== event.id ? { pendingAttachments: [] } : {}), notice: loadError ? { severity: 'error' as const, message: loadError } : undefined, }, @@ -64,7 +65,9 @@ export class HistoryController extends Controller { page: 'history' as const, chat: { ...runtime.chat, - ...(runtime.chat.conversation?.id === event.id ? { conversation: undefined, pendingAttachments: [] } : {}), + ...(runtime.chat.conversation?.id === event.id + ? { conversation: undefined, pendingAttachments: [], editing: undefined } + : {}), }, history: { ...runtime.history, notice: undefined }, }); diff --git a/extensions/github1s-ai/src/controllers/runner.ts b/extensions/github1s-ai/src/controllers/runner.ts index a51403722..8fe6e344a 100644 --- a/extensions/github1s-ai/src/controllers/runner.ts +++ b/extensions/github1s-ai/src/controllers/runner.ts @@ -10,7 +10,7 @@ import { type ConversationMessage, } from '@/common/conversation'; import { resolvePrompts } from '@/common/prompts-config'; -import type { ChatQuickAction } from '@/common/quick-actions'; +import type { RuntimeState } from '@/common/state'; import { buildModelMessages } from '@/llm/helpers'; import { connectMcpTools } from '@/llm/mcp'; import { streamLLMAgent } from '@/llm/transport'; @@ -23,6 +23,12 @@ type ActiveRequest = { messageId: string; }; +type MessagePreparation = { + history: ConversationMessage[]; + createMessage: () => Promise; + clearPendingAttachments: boolean; +}; + export class ConversationRunner { private readonly requests = new Map(); private preparation: symbol | undefined; @@ -32,16 +38,75 @@ export class ConversationRunner { private readonly publishState: () => Promise, ) {} - async send(input: { text: string } | { action: ChatQuickAction } | { retryMessageId: string }): Promise { - if (('text' in input && !input.text.trim()) || this.preparation) return; + async send(text: string): Promise { + if (!text.trim()) return; + return this.run((chat) => ({ + history: chat.conversation?.messages ?? [], + clearPendingAttachments: true, + createMessage: async () => + createUserMessage( + globalThis.crypto.randomUUID(), + text, + await resolveContextAttachments(chat.pendingAttachments ?? []), + chat.includeRecentFiles === false ? [] : chat.recentFiles, + ), + })); + } + + async retry(messageId: string): Promise { + return this.run((chat) => { + const messages = chat.conversation?.messages ?? []; + if (getRetryableMessage(messages)?.id !== messageId) return; + return { + history: messages.slice(0, -2), + createMessage: async () => messages[messages.length - 2], + clearPendingAttachments: false, + }; + }); + } + + async edit(text: string): Promise { + if (!text.trim()) return; + return this.run((chat) => { + const editing = chat.editing; + if (!editing) return; + const messages = chat.conversation?.messages ?? []; + const messageIndex = messages.findIndex((message) => message.id === editing.messageId && message.role === 'user'); + if (messageIndex < 0) return; + const originalMessage = messages[messageIndex]; + const descriptors = editing.pendingAttachments.map((descriptor) => ({ ...descriptor })); + return { + history: messages.slice(0, messageIndex), + clearPendingAttachments: false, + createMessage: async () => { + const originalAttachments = originalMessage.parts.flatMap((part) => + part.type === 'data-attachments' ? part.data : [], + ); + const attachments = await Promise.all( + descriptors.map( + async (descriptor) => + originalAttachments.find((attachment) => attachment.id === descriptor.id) ?? + (await resolveContextAttachments([descriptor]))[0], + ), + ); + const recentFiles = + editing.includeRecentFiles === false + ? [] + : originalMessage.parts.flatMap((part) => (part.type === 'data-recentFiles' ? part.data : [])); + return createUserMessage(originalMessage.metadata.turnId, text, attachments, recentFiles); + }, + }; + }); + } + + private async run(prepare: (chat: RuntimeState['chat']) => MessagePreparation | undefined): Promise { + if (this.preparation) return; const [promptsConfig, config] = await Promise.all([ this.stores.promptsConfig.get(), this.stores.modelConfigs.getSelected(), ]); const prompts = resolvePrompts(promptsConfig); - const text = 'text' in input ? input.text : 'action' in input ? prompts.quickActions[input.action] : ''; - const retry = 'retryMessageId' in input; if (!config) { await this.stores.runtime.setIn('chat.notice', { @@ -53,10 +118,10 @@ export class ConversationRunner { const runtime = await this.stores.runtime.get(); if (this.preparation) return; const previous = runtime.chat.conversation; - if (retry && (!previous || getRetryableMessage(previous.messages)?.id !== input.retryMessageId)) return; + const prepared = prepare(runtime.chat); + if (!prepared) return; const conversationId = previous?.id ?? globalThis.crypto.randomUUID(); if (this.requests.has(conversationId)) return; - const descriptors = (runtime.chat.pendingAttachments ?? []).map((descriptor) => ({ ...descriptor })); const preparation = Symbol('conversation-preparation'); this.preparation = preparation; await this.stores.runtime.setIn('chat', { ...runtime.chat, preparing: true, notice: undefined }); @@ -64,13 +129,7 @@ export class ConversationRunner { let userMessage: ConversationMessage; try { await this.publishState(); - if (retry) { - userMessage = previous!.messages.at(-2)!; - } else { - const attachments = await resolveContextAttachments(descriptors); - const recentFiles = runtime.chat.includeRecentFiles === false ? [] : runtime.chat.recentFiles; - userMessage = createUserMessage(globalThis.crypto.randomUUID(), text, attachments, recentFiles); - } + userMessage = await prepared.createMessage(); } catch (error) { const detail = error instanceof Error ? error.message : 'Unknown error.'; await this.finishPreparation(preparation, `Unable to read the selected context attachment. ${detail}`); @@ -80,7 +139,7 @@ export class ConversationRunner { const startedAt = Date.now(); const turnId = userMessage.metadata.turnId; - const history = retry ? previous!.messages.slice(0, -2) : (previous?.messages ?? []); + const history = prepared.history; let providerMessages; try { providerMessages = await buildModelMessages(history, [userMessage]); @@ -100,7 +159,7 @@ export class ConversationRunner { } : { id: conversationId, - title: createConversationTitle(text, descriptors), + title: createConversationTitle(userMessage), messages: [userMessage, assistantMessage], createdAt: startedAt, updatedAt: startedAt, @@ -138,7 +197,8 @@ export class ConversationRunner { await this.stores.runtime.setIn('chat', { ...currentRuntime.chat, conversation, - pendingAttachments: retry ? currentRuntime.chat.pendingAttachments : [], + pendingAttachments: prepared.clearPendingAttachments ? [] : currentRuntime.chat.pendingAttachments, + editing: undefined, preparing: false, }); await this.stores.conversations.select(conversationId); @@ -272,7 +332,9 @@ const addUsage = ( return addLanguageModelUsage(current ?? createNullLanguageModelUsage(), next); }; -const createConversationTitle = (prompt: string, attachments: readonly { label: string }[]): string => { +const createConversationTitle = (message: ConversationMessage): string => { + const prompt = message.parts.flatMap((part) => (part.type === 'text' ? [part.text] : [])).join(''); + const attachments = message.parts.flatMap((part) => (part.type === 'data-attachments' ? part.data : [])); const text = prompt.replace(/\s+/g, ' ').trim(); const primary = attachments[0]?.label; const additional = attachments.length > 1 ? ` +${attachments.length - 1}` : ''; diff --git a/extensions/github1s-ai/src/webview/components/ChatPage.ts b/extensions/github1s-ai/src/webview/components/ChatPage.ts index 7e97881fc..31f5c385f 100644 --- a/extensions/github1s-ai/src/webview/components/ChatPage.ts +++ b/extensions/github1s-ai/src/webview/components/ChatPage.ts @@ -28,12 +28,19 @@ export const ChatPage = ({ state, active, post }: ChatPageProps) => { const busy = state.runtime.chat.preparing === true || messages.some(({ metadata }) => metadata.status === 'streaming'); const notice = state.runtime.chat.notice?.message; + const editingId = state.runtime.chat.editing?.messageId; return html` - ${notice ? html`

${notice}

` : null} - <${Transcript} state=${state} messages=${messages} busy=${busy} post=${post} /> + ${notice && !editingId ? html`

${notice}

` : null} + <${Transcript} state=${state} messages=${messages} busy=${busy} active=${active} post=${post} /> ${state.modelConfigs.configs.length > 0 - ? html`<${Composer} key=${conversationId ?? 'new'} state=${state} busy=${busy} active=${active} post=${post} />` + ? html`<${Composer} + key=${conversationId ?? 'new'} + state=${state} + busy=${busy} + active=${active && !editingId} + post=${post} + />` : null} `; }; @@ -44,20 +51,33 @@ interface ChatContentProps extends ChatContextProps { interface TranscriptProps extends ChatContentProps { messages: readonly ConversationMessage[]; + active: boolean; } -const Transcript = ({ state, messages, busy, post }: TranscriptProps) => { +const Transcript = ({ state, messages, busy, active, post }: TranscriptProps) => { const retryableMessage = busy ? undefined : getRetryableMessage(messages); + const editingId = state.runtime.chat.editing?.messageId; + const lastMessageBeforeEditing = useRef(); const transcript = useRef(null); const content = useRef(null); const followOutput = useRef(true); useLayoutEffect(() => { + const lastMessageId = messages.at(-1)?.id; + if (editingId) { + lastMessageBeforeEditing.current = lastMessageId; + return; + } + if (lastMessageBeforeEditing.current && lastMessageBeforeEditing.current !== lastMessageId) { + followOutput.current = true; + } + lastMessageBeforeEditing.current = undefined; const element = transcript.current; if (element && followOutput.current) scrollToBottom(element); - }, [messages]); + }, [messages, editingId]); useLayoutEffect(() => { + if (editingId) return; const element = transcript.current; const contentElement = content.current; if (!element || !contentElement || typeof ResizeObserver === 'undefined') return; @@ -66,7 +86,7 @@ const Transcript = ({ state, messages, busy, post }: TranscriptProps) => { }); observer.observe(contentElement); return () => observer.disconnect(); - }, []); + }, [editingId]); const onScroll = () => { const element = transcript.current; @@ -79,14 +99,19 @@ const Transcript = ({ state, messages, busy, post }: TranscriptProps) => {
${messages.length === 0 ? html`<${EmptyChat} state=${state} busy=${busy} post=${post} />` - : messages.map( - (message) => - html`<${MessageView} - key=${message.id} - message=${message} - canRetry=${message === retryableMessage} - post=${post} - />`, + : messages.map((message) => + message.id === editingId + ? html`
+ <${Composer} state=${state} busy=${busy} active=${active} post=${post} message=${message} /> +
` + : html`<${MessageView} + key=${message.id} + message=${message} + canRetry=${message === retryableMessage} + canEdit=${!busy && !editingId && state.modelConfigs.configs.length > 0} + inactive=${Boolean(editingId)} + post=${post} + />`, )}
`; diff --git a/extensions/github1s-ai/src/webview/components/Composer.ts b/extensions/github1s-ai/src/webview/components/Composer.ts index c9d55b015..f7816830e 100644 --- a/extensions/github1s-ai/src/webview/components/Composer.ts +++ b/extensions/github1s-ai/src/webview/components/Composer.ts @@ -1,6 +1,7 @@ import { html } from 'htm/preact'; import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'preact/hooks'; +import type { ConversationMessage } from '@/common/conversation'; import type { ViewEvent, ViewState } from '@/common/protocol'; import { resizeComposer, shouldSubmitComposer } from '../helpers/composer'; @@ -35,15 +36,21 @@ interface ComposerProps { busy: boolean; active: boolean; post: (event: ViewEvent) => void; + message?: ConversationMessage; } -export const Composer = ({ state, busy, active, post }: ComposerProps) => { - const [draft, setDraft] = useState(''); +export const Composer = ({ state, busy, active, post, message: editedMessage }: ComposerProps) => { + const [draft, setDraft] = useState(() => + editedMessage ? editedMessage.parts.flatMap((part) => (part.type === 'text' ? [part.text] : [])).join('') : '', + ); const textarea = useRef(null); const chat = state.runtime.chat; + const context = editedMessage ? (chat.editing ?? chat) : chat; const preparing = chat.preparing === true; - const recentFiles = chat.recentFiles ?? []; - const includeRecentFiles = chat.includeRecentFiles !== false; + const recentFiles = editedMessage + ? editedMessage.parts.flatMap((part) => (part.type === 'data-recentFiles' ? part.data : [])) + : (chat.recentFiles ?? []); + const includeRecentFiles = context.includeRecentFiles !== false; const selectedModelConfig = state.modelConfigs.configs.find(({ id }) => id === state.modelConfigs.selectedId); const selectedModelConfigId = selectedModelConfig?.id; const conversationUsage = chat.conversation?.usage; @@ -55,6 +62,28 @@ export const Composer = ({ state, busy, active, post }: ComposerProps) => { if (textarea.current) resizeComposer(textarea.current); }, [draft]); + useLayoutEffect(() => { + if (!active || !editedMessage || busy) return; + textarea.current?.focus({ preventScroll: true }); + textarea.current?.closest('.composer-wrap')?.scrollIntoView({ block: 'nearest' }); + const cancel = (event: KeyboardEvent) => { + if (event.key !== 'Escape' || event.isComposing || event.defaultPrevented) return; + event.preventDefault(); + post({ type: 'chat.setEditingMessageId' }); + }; + const cancelOnClick = ({ target }: MouseEvent) => { + if (target instanceof Element && !target.closest('.message-editing, .tooltip')) { + post({ type: 'chat.setEditingMessageId' }); + } + }; + window.addEventListener('keydown', cancel); + window.addEventListener('click', cancelOnClick, true); + return () => { + window.removeEventListener('keydown', cancel); + window.removeEventListener('click', cancelOnClick, true); + }; + }, [active, editedMessage?.id, busy, post]); + useEffect(() => { if (active && wasBusy.current && !busy) textarea.current?.focus(); wasBusy.current = busy; @@ -63,7 +92,7 @@ export const Composer = ({ state, busy, active, post }: ComposerProps) => { const submit = () => { if (!message || busy || !selectedModelConfigId) return; post({ type: 'chat.send', text: message }); - setDraft(''); + if (!editedMessage) setDraft(''); }; const onInput = (event: InputEvent) => { @@ -76,10 +105,15 @@ export const Composer = ({ state, busy, active, post }: ComposerProps) => { submit(); }; - return html`
+ return html`
+ ${editedMessage && chat.notice ? html`` : null}
<${AttachmentChips} - attachments=${chat.pendingAttachments ?? []} + attachments=${context.pendingAttachments ?? []} disabled=${preparing} onOpen=${(source: string) => post({ type: 'app.openFile', source })} onRemove=${(id: string) => post({ type: 'chat.removeContextAttachment', id })} @@ -131,7 +165,7 @@ export const Composer = ({ state, busy, active, post }: ComposerProps) => {
- ${usage + ${!editedMessage && usage ? html`<${Tooltip} content=${html`
Tokens usage: @@ -165,6 +199,16 @@ export const Composer = ({ state, busy, active, post }: ComposerProps) => { <${Icon} name="chevron-right" />
+ ${editedMessage + ? html`<${TooltipButton} + class="ghost-button" + label="Cancel editing" + disabled=${preparing} + onClick=${() => post({ type: 'chat.setEditingMessageId' })} + > + <${Icon} name="close" /> + ` + : null} <${TooltipButton} class="submit-button" label=${busy ? 'Stop generating' : 'Send message'} diff --git a/extensions/github1s-ai/src/webview/components/MessageView.ts b/extensions/github1s-ai/src/webview/components/MessageView.ts index a837be1dc..32db019c3 100644 --- a/extensions/github1s-ai/src/webview/components/MessageView.ts +++ b/extensions/github1s-ai/src/webview/components/MessageView.ts @@ -17,10 +17,12 @@ type AssistantSegment = interface MessageViewProps { message: ConversationMessage; canRetry?: boolean; + canEdit?: boolean; + inactive?: boolean; post: (event: ViewEvent) => void; } -export const MessageView = ({ message, canRetry, post }: MessageViewProps) => { +export const MessageView = ({ message, canRetry, canEdit, inactive, post }: MessageViewProps) => { if (message.role !== 'user' && message.role !== 'assistant') return null; const segments = message.role === 'assistant' ? assistantSegments(message) : []; const activityRunning = segments.some( @@ -28,9 +30,9 @@ export const MessageView = ({ message, canRetry, post }: MessageViewProps) => { ); const status = activityRunning ? undefined : messageStatusLabel(message.metadata); - return html`
+ return html`
${message.role === 'user' - ? html`<${UserRequest} message=${message} post=${post} />` + ? html`<${UserRequest} message=${message} canEdit=${canEdit} post=${post} />` : html`
${segments.map((segment) => segment.type === 'text' @@ -98,12 +100,33 @@ const assistantSegments = (message: ConversationMessage): AssistantSegment[] => return segments; }; -const UserRequest = ({ message, post }: MessageViewProps) => { +const UserRequest = ({ message, canEdit, post }: MessageViewProps) => { const text = message.parts.flatMap((part) => (part.type === 'text' ? [part.text] : [])).join(''); const attachments = message.parts.flatMap((part) => (part.type === 'data-attachments' ? part.data : [])); const recentFiles = message.parts.flatMap((part) => (part.type === 'data-recentFiles' ? part.data : [])); - const request = html`
0 ? 0 : undefined}> -
${text}
+ const edit = (event: MouseEvent | KeyboardEvent) => { + if (!canEdit || (event.target instanceof Element && event.target.closest('button, a'))) return; + if (event instanceof MouseEvent && window.getSelection()?.toString()) return; + if (event instanceof KeyboardEvent) { + if (event.target !== event.currentTarget || (event.key !== 'Enter' && event.key !== ' ')) return; + event.preventDefault(); + } + post({ type: 'chat.setEditingMessageId', id: message.id }); + }; + const request = html`
0 ? 0 : undefined} + onClick=${edit} + > +
+ ${text} +
<${AttachmentChips} attachments=${attachments} onOpen=${(source: string) => post({ type: 'app.openFile', source })} diff --git a/extensions/github1s-ai/test/runner.test.ts b/extensions/github1s-ai/test/runner.test.ts index 9c9ecd735..944b69468 100644 --- a/extensions/github1s-ai/test/runner.test.ts +++ b/extensions/github1s-ai/test/runner.test.ts @@ -104,7 +104,7 @@ const response = () => test('retry replaces the failed reply using the original context and current settings', async (t) => { const { stores, user, runner, getConversation } = await setup(); const fetch = t.mock.method(globalThis, 'fetch', async () => response()); - await runner.send({ retryMessageId: 'old-assistant' }); + await runner.retry('old-assistant'); assert.equal(fetch.mock.callCount(), 1); const request = JSON.parse(fetch.mock.calls[0].arguments[1]?.body as string); assert.equal(request.model, 'current-model'); From fbeb80191b858071ca147e8d04d5bcdd76b46dd1 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 3 Nov 2026 12:07:09 +0800 Subject: [PATCH 06/19] chore(deps-dev): bump serialize-javascript from 7.0.5 to 7.1.4 (#795) Bumps [serialize-javascript](https://github.com/yahoo/serialize-javascript) from 7.0.5 to 7.1.4. - [Release notes](https://github.com/yahoo/serialize-javascript/releases) - [Commits](https://github.com/yahoo/serialize-javascript/compare/v7.0.5...v7.1.4) --- updated-dependencies: - dependency-name: serialize-javascript dependency-version: 7.1.4 dependency-type: indirect ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- package-lock.json | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/package-lock.json b/package-lock.json index f637dcc5b..119532faf 100644 --- a/package-lock.json +++ b/package-lock.json @@ -7869,9 +7869,9 @@ } }, "node_modules/serialize-javascript": { - "version": "7.0.5", - "resolved": "https://registry.npmjs.org/serialize-javascript/-/serialize-javascript-7.0.5.tgz", - "integrity": "sha512-F4LcB0UqUl1zErq+1nYEEzSHJnIwb3AF2XWB94b+afhrekOUijwooAYqFyRbjYkm2PAKBabx6oYv/xDxNi8IBw==", + "version": "7.1.4", + "resolved": "https://registry.npmjs.org/serialize-javascript/-/serialize-javascript-7.1.4.tgz", + "integrity": "sha512-FqlEuoTq/zRmA4Lg6aOqyH3lCHbUtCB0bmHCeFniX2GBdDqMJM3FwdvEhlE5Pim1dlt2FfBdVPmUNNiGhhKqpw==", "dev": true, "license": "BSD-3-Clause", "engines": { From f747911f7e1388cda0db8f4d70cb5a134b11a0a6 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 3 Nov 2026 12:07:36 +0800 Subject: [PATCH 07/19] chore(deps): bump decode-uri-component in /extensions/github1s (#794) Bumps [decode-uri-component](https://github.com/SamVerschueren/decode-uri-component) from 0.5.0 to 0.5.1. - [Release notes](https://github.com/SamVerschueren/decode-uri-component/releases) - [Commits](https://github.com/SamVerschueren/decode-uri-component/compare/v0.5.0...v0.5.1) --- updated-dependencies: - dependency-name: decode-uri-component dependency-version: 0.5.1 dependency-type: indirect ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- extensions/github1s/package-lock.json | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/extensions/github1s/package-lock.json b/extensions/github1s/package-lock.json index 319f9b970..9806fe069 100644 --- a/extensions/github1s/package-lock.json +++ b/extensions/github1s/package-lock.json @@ -1287,9 +1287,9 @@ "license": "MIT" }, "node_modules/decode-uri-component": { - "version": "0.5.0", - "resolved": "https://registry.npmjs.org/decode-uri-component/-/decode-uri-component-0.5.0.tgz", - "integrity": "sha512-1BiQVoK8C9gUbQU6NzAtO/tkz2qOFpEObMWpcFvhx4fYnj4Oc5yzaJN/LD36ihkVUdXyh5ZekzX+yM+ty/SrPg==", + "version": "0.5.1", + "resolved": "https://registry.npmjs.org/decode-uri-component/-/decode-uri-component-0.5.1.tgz", + "integrity": "sha512-vWHQkXgg2cE3BB4rR0c+PYw9BCQzLoNIRMI7AunIkZst74tw/vpPp7VLoYtsR/cy1f55g3XDWUslfeCZjiZJyA==", "license": "MIT", "engines": { "node": ">=14.16" From 3ddd6f7cbd2f89d9fb8b599e1945337b9919a1b0 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 3 Nov 2026 12:07:55 +0800 Subject: [PATCH 08/19] chore(deps): bump follow-redirects from 1.16.0 to 1.16.2 in /tests (#792) Bumps [follow-redirects](https://github.com/follow-redirects/follow-redirects) from 1.16.0 to 1.16.2. - [Release notes](https://github.com/follow-redirects/follow-redirects/releases) - [Commits](https://github.com/follow-redirects/follow-redirects/compare/v1.16.0...v1.16.2) --- updated-dependencies: - dependency-name: follow-redirects dependency-version: 1.16.2 dependency-type: indirect ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- tests/package-lock.json | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/package-lock.json b/tests/package-lock.json index fec9b4f35..b53c6b4ad 100644 --- a/tests/package-lock.json +++ b/tests/package-lock.json @@ -2312,9 +2312,9 @@ } }, "node_modules/follow-redirects": { - "version": "1.16.0", - "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.16.0.tgz", - "integrity": "sha512-y5rN/uOsadFT/JfYwhxRS5R7Qce+g3zG97+JrtFZlC9klX/W5hD7iiLzScI4nZqUS7DNUdhPgw4xI8W2LuXlUw==", + "version": "1.16.2", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.16.2.tgz", + "integrity": "sha512-/kVP2U8z596Ia0gwFrwyIeo74ta5aVmSeU1FfAUMAmcEP5EP7zydmag3SLiN64NaRKef3lxsq7i/g7ltJQDGow==", "dev": true, "funding": [ { From 0218bf8ca4c65c4d6de71abb9d476160c6ce11fa Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 3 Nov 2026 12:08:10 +0800 Subject: [PATCH 09/19] chore(deps-dev): bump qs from 6.16.0 to 6.17.1 (#793) Bumps [qs](https://github.com/ljharb/qs) from 6.16.0 to 6.17.1. - [Changelog](https://github.com/ljharb/qs/blob/main/CHANGELOG.md) - [Commits](https://github.com/ljharb/qs/compare/v6.16.0...v6.17.1) --- updated-dependencies: - dependency-name: qs dependency-version: 6.17.1 dependency-type: indirect ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- package-lock.json | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/package-lock.json b/package-lock.json index 119532faf..a23c16a8c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -7230,9 +7230,9 @@ } }, "node_modules/qs": { - "version": "6.16.0", - "resolved": "https://registry.npmjs.org/qs/-/qs-6.16.0.tgz", - "integrity": "sha512-h6fhOIaRrID2CbEY2fqs+7t+UXZo+MLAnU5gRIq85uFtdiUPCdsApMlHhXogKVM4HM2DVbIjGNTTYH2OcmP1vA==", + "version": "6.17.1", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.17.1.tgz", + "integrity": "sha512-jd3COkaKVgGUW+ZHyEHCG9bH7RoaaiWuMgzsIBjUMVjLAaWGWpoUAVwljVvBHxRu/2qEHnadLGZrkutYUBPQJA==", "dev": true, "license": "BSD-3-Clause", "dependencies": { From 32efc273fd8dbee17c5bebf646cc12e303c99c2c Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 3 Nov 2026 12:08:42 +0800 Subject: [PATCH 10/19] chore(deps-dev): bump fast-uri in /extensions/github1s-ai (#788) Bumps [fast-uri](https://github.com/fastify/fast-uri) from 3.1.7 to 3.1.9. - [Release notes](https://github.com/fastify/fast-uri/releases) - [Commits](https://github.com/fastify/fast-uri/compare/v3.1.7...v3.1.9) --- updated-dependencies: - dependency-name: fast-uri dependency-version: 3.1.9 dependency-type: indirect ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- extensions/github1s-ai/package-lock.json | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/extensions/github1s-ai/package-lock.json b/extensions/github1s-ai/package-lock.json index 80aec5519..428557de1 100644 --- a/extensions/github1s-ai/package-lock.json +++ b/extensions/github1s-ai/package-lock.json @@ -2884,9 +2884,9 @@ "license": "MIT" }, "node_modules/fast-uri": { - "version": "3.1.7", - "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.7.tgz", - "integrity": "sha512-dOvZVzjdZdz7phd9v6jCbwxrBW3fK6n8Rc0CtdmM4bumzMnxywBYhuph6J819RRw/ku+rLbelwfMunktuzVVHg==", + "version": "3.1.9", + "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.9.tgz", + "integrity": "sha512-hS/0Wt3Ya043oKXs0sIxrMpKQITXhMLIrVAKKXi4gozGC9v7YRWVnXIZzjNPTO02M9BdxLCWqK1yRXgNziVyJQ==", "dev": true, "funding": [ { From 58795eadac209a45ded57988c61cac1ea6967c25 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 3 Nov 2026 12:09:24 +0800 Subject: [PATCH 11/19] chore(deps): bump undici in /extensions/github1s-ai (#789) Bumps [undici](https://github.com/nodejs/undici) from 7.30.0 to 7.30.1. - [Release notes](https://github.com/nodejs/undici/releases) - [Commits](https://github.com/nodejs/undici/compare/v7.30.0...v7.30.1) --- updated-dependencies: - dependency-name: undici dependency-version: 7.30.1 dependency-type: indirect ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- extensions/github1s-ai/package-lock.json | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/extensions/github1s-ai/package-lock.json b/extensions/github1s-ai/package-lock.json index 428557de1..218a0bb03 100644 --- a/extensions/github1s-ai/package-lock.json +++ b/extensions/github1s-ai/package-lock.json @@ -4675,9 +4675,9 @@ "license": "MIT" }, "node_modules/undici": { - "version": "7.30.0", - "resolved": "https://registry.npmjs.org/undici/-/undici-7.30.0.tgz", - "integrity": "sha512-dkrQXeHSaoamnItlYbmzG0wFYrM0ZwDxCIg0A7aKjTyyhh9svRzCNFEzV+Vm05/yehjCzjDZ31KXfGEjYSztDQ==", + "version": "7.30.1", + "resolved": "https://registry.npmjs.org/undici/-/undici-7.30.1.tgz", + "integrity": "sha512-03KrMbjIFDWQR5RNPrSw3bd1r12JpyFQl9/yxjUbJtqkjmllqC5lFjZh6ujeuJCKr8EOQvRW872Oy/az+nLYxg==", "license": "MIT", "engines": { "node": ">=20.18.1" From 36d9db7f6731c22ae841d3e1584c69a82090fa07 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 3 Nov 2026 12:09:39 +0800 Subject: [PATCH 12/19] chore(deps): bump dompurify in /extensions/github1s-ai (#787) Bumps [dompurify](https://github.com/cure53/DOMPurify) from 3.4.16 to 3.4.17. - [Release notes](https://github.com/cure53/DOMPurify/releases) - [Commits](https://github.com/cure53/DOMPurify/compare/3.4.16...3.4.17) --- updated-dependencies: - dependency-name: dompurify dependency-version: 3.4.17 dependency-type: direct:production ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- extensions/github1s-ai/package-lock.json | 8 ++++---- extensions/github1s-ai/package.json | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/extensions/github1s-ai/package-lock.json b/extensions/github1s-ai/package-lock.json index 218a0bb03..a457412d6 100644 --- a/extensions/github1s-ai/package-lock.json +++ b/extensions/github1s-ai/package-lock.json @@ -14,7 +14,7 @@ "@ai-sdk/openai-compatible": "3.0.41", "@vscode/markdown-it-katex": "1.1.2", "ai": "7.0.87", - "dompurify": "3.4.16", + "dompurify": "3.4.17", "htm": "3.1.1", "katex": "0.18.2", "lodash-es": "4.18.1", @@ -2654,9 +2654,9 @@ } }, "node_modules/dompurify": { - "version": "3.4.16", - "resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.4.16.tgz", - "integrity": "sha512-sqo+pNp3qRhCIpbgRi1y8Tgk27Bo2Ry7w0dC1NBeNTdZChWjz9Xb/KOoZbRP/R6pQZ80Qw8YhXw13hWWBbMRnQ==", + "version": "3.4.17", + "resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.4.17.tgz", + "integrity": "sha512-B/pSlYVHQ58kqISD/yDjuJ1yfzI34m1gF4lAod2bwSRhiN4K5Cl3H8Af7hqB2PmTL911tdEudnnXn5FnhRoz0w==", "license": "(MPL-2.0 OR Apache-2.0)", "optionalDependencies": { "@types/trusted-types": "^2.0.7" diff --git a/extensions/github1s-ai/package.json b/extensions/github1s-ai/package.json index 0706e0ff3..08b1dd32a 100644 --- a/extensions/github1s-ai/package.json +++ b/extensions/github1s-ai/package.json @@ -119,7 +119,7 @@ "@ai-sdk/openai-compatible": "3.0.41", "@vscode/markdown-it-katex": "1.1.2", "ai": "7.0.87", - "dompurify": "3.4.16", + "dompurify": "3.4.17", "htm": "3.1.1", "katex": "0.18.2", "lodash-es": "4.18.1", From b1abb14e444a211c27e321524f720b9535be81a8 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 3 Nov 2026 12:10:10 +0800 Subject: [PATCH 13/19] chore(deps-dev): bump follow-redirects from 1.16.0 to 1.16.1 (#783) Bumps [follow-redirects](https://github.com/follow-redirects/follow-redirects) from 1.16.0 to 1.16.1. - [Release notes](https://github.com/follow-redirects/follow-redirects/releases) - [Commits](https://github.com/follow-redirects/follow-redirects/compare/v1.16.0...v1.16.1) --- updated-dependencies: - dependency-name: follow-redirects dependency-version: 1.16.1 dependency-type: indirect ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- package-lock.json | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/package-lock.json b/package-lock.json index a23c16a8c..4b7673d99 100644 --- a/package-lock.json +++ b/package-lock.json @@ -4101,9 +4101,9 @@ "license": "ISC" }, "node_modules/follow-redirects": { - "version": "1.16.0", - "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.16.0.tgz", - "integrity": "sha512-y5rN/uOsadFT/JfYwhxRS5R7Qce+g3zG97+JrtFZlC9klX/W5hD7iiLzScI4nZqUS7DNUdhPgw4xI8W2LuXlUw==", + "version": "1.16.1", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.16.1.tgz", + "integrity": "sha512-FNvFGzoMLWmE6Yj9spb/zjd7yiNCHiAW9/Tg9CXrQ8wuu32HtlJOwWO11OJafl5FfY3DxTdQ0vj42zU1kvv5jg==", "dev": true, "funding": [ { From 611f051651ba7624cf02d7dfca3dda339b244862 Mon Sep 17 00:00:00 2001 From: netcon Date: Wed, 4 Nov 2026 15:29:51 +0800 Subject: [PATCH 14/19] feat(ai): add assistant message actions and metadata (#799) * feat(ai): add assistant message actions and metadata * tests: fix ui test --- extensions/github1s-ai/assets/chat.css | 89 ++++- .../github1s-ai/src/common/conversation.ts | 39 +-- extensions/github1s-ai/src/common/protocol.ts | 5 + extensions/github1s-ai/src/common/state.ts | 1 - extensions/github1s-ai/src/controllers/app.ts | 1 + .../github1s-ai/src/controllers/chat.ts | 7 +- .../github1s-ai/src/controllers/index.ts | 1 + .../github1s-ai/src/controllers/runner.ts | 308 ++++++++++-------- .../github1s-ai/src/stores/conversations.ts | 3 +- .../src/webview/components/ChatPage.ts | 47 ++- .../src/webview/components/Composer.ts | 12 +- .../src/webview/components/Icon.ts | 4 +- .../src/webview/components/Markdown.ts | 23 +- .../src/webview/components/MessageView.ts | 94 +++++- .../src/webview/helpers/clipboard.ts | 10 + .../src/webview/helpers/presentation.ts | 5 +- .../github1s-ai/test/conversation.test.ts | 17 +- .../github1s-ai/test/model-messages.test.ts | 4 +- extensions/github1s-ai/test/protocol.test.ts | 1 + extensions/github1s-ai/test/runner.test.ts | 135 +++++++- tests/__tests__/index.test.ts | 13 +- 21 files changed, 544 insertions(+), 275 deletions(-) create mode 100644 extensions/github1s-ai/src/webview/helpers/clipboard.ts diff --git a/extensions/github1s-ai/assets/chat.css b/extensions/github1s-ai/assets/chat.css index 634822834..dc95f14cf 100644 --- a/extensions/github1s-ai/assets/chat.css +++ b/extensions/github1s-ai/assets/chat.css @@ -693,7 +693,7 @@ summary:focus-visible, } .message { - padding: 10px 0; + padding: 8px 0; } .message-user { @@ -746,6 +746,67 @@ summary:focus-visible, margin-top: 0.75em; } +.message-footer { + display: flex; + min-height: 20px; + align-items: center; + gap: 12px; + margin-top: 8px; + opacity: 0; + pointer-events: none; +} + +.message-meta { + display: flex; + min-width: 0; + flex: 1; + justify-content: flex-end; + flex-wrap: wrap; + gap: 2px 8px; + color: var(--vscode-descriptionForeground); + font-size: 0.8em; + line-height: 1.4; + text-align: right; +} + +.message-model, +.message-meta time { + max-width: 100%; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.message-actions { + display: flex; + flex: none; + gap: 2px; +} + +.message-actions .icon-button { + width: 20px; + height: 20px; + border-radius: 3px; +} + +.message-actions .icon { + width: 13px; + height: 13px; +} + +.message-assistant:hover .message-footer, +.message-assistant:focus-within .message-footer { + opacity: 1; + pointer-events: auto; +} + +@media (hover: none) { + .message-footer { + opacity: 1; + pointer-events: auto; + } +} + /* Markdown */ .markdown { @@ -1186,16 +1247,6 @@ summary:focus-visible, font: inherit; } -.message-retry { - gap: 4px; - margin-top: 6px; -} - -.message-retry .icon { - width: 12px; - height: 12px; -} - .message-status { margin: 5px 0 0; color: var(--vscode-descriptionForeground); @@ -1249,6 +1300,22 @@ summary:focus-visible, line-height: 1.4; } +.notice-success { + display: flex; + flex: none; + align-items: flex-start; + gap: 6px; + padding: 8px 0; + color: var(--vscode-testing-iconPassed, var(--vscode-foreground)); +} + +.notice-success .icon { + width: 14px; + height: 14px; + flex: none; + margin-top: 1px; +} + .composer-surface { padding: 7px 7px 6px; background: var(--vscode-input-background); diff --git a/extensions/github1s-ai/src/common/conversation.ts b/extensions/github1s-ai/src/common/conversation.ts index c9f5455a2..954223f45 100644 --- a/extensions/github1s-ai/src/common/conversation.ts +++ b/extensions/github1s-ai/src/common/conversation.ts @@ -16,6 +16,8 @@ export type ConversationMessageStatus = 'streaming' | 'completed' | 'failed' | ' export interface ConversationMessageMetadata { turnId: string; status: ConversationMessageStatus; + modelId?: string; + createdAt?: number; error?: string; } @@ -39,17 +41,6 @@ export const isInterruptedMessage = (message: ConversationMessage): boolean => message.metadata.status === 'aborted' || message.metadata.status === 'unknown'; -export const getRetryableMessage = (messages: readonly ConversationMessage[]): ConversationMessage | undefined => { - const assistant = messages.at(-1); - const user = messages.at(-2); - return assistant?.role === 'assistant' && - isInterruptedMessage(assistant) && - user?.role === 'user' && - user.metadata.turnId === assistant.metadata.turnId - ? assistant - : undefined; -}; - export const createUserMessage = ( turnId: string, text: string, @@ -67,10 +58,13 @@ export const createUserMessage = ( return { id: turnId, role: 'user', metadata: { turnId, status: 'completed' }, parts }; }; -export const createAssistantMessage = (id: string, turnId: string): ConversationMessage => ({ +export const createAssistantMessage = ( + id: string, + metadata: Omit, +): ConversationMessage => ({ id, role: 'assistant', - metadata: { turnId, status: 'streaming' }, + metadata: { ...metadata, status: 'streaming' }, parts: [], }); @@ -78,14 +72,10 @@ export const withMessageStatus = ( message: ConversationMessage, status: ConversationMessageStatus, error?: string, -): ConversationMessage => ({ - ...message, - metadata: { - turnId: message.metadata.turnId, - status, - ...(error ? { error } : {}), - }, -}); +): ConversationMessage => { + const { error: _previousError, ...metadata } = message.metadata; + return { ...message, metadata: { ...metadata, status, ...(error ? { error } : {}) } }; +}; export const markStreamingMessagesUnknown = (conversation: Conversation): Conversation => { const messages = conversation.messages.map((message) => @@ -104,6 +94,8 @@ const metadataSchema = jsonSchema( properties: { turnId: { type: 'string', minLength: 1 }, status: { enum: ['streaming', 'completed', 'failed', 'aborted', 'unknown'] }, + modelId: { type: 'string' }, + createdAt: { type: 'number' }, error: { type: 'string' }, }, }, @@ -169,7 +161,7 @@ const isConversationMessageMetadata = (value: unknown): value is ConversationMes if (!isPlainObject(value)) return false; const metadata = value as Record; return ( - Object.keys(metadata).every((key) => key === 'turnId' || key === 'status' || key === 'error') && + Object.keys(metadata).every((key) => ['turnId', 'status', 'modelId', 'createdAt', 'error'].includes(key)) && typeof metadata.turnId === 'string' && metadata.turnId.length > 0 && (metadata.status === 'streaming' || @@ -177,6 +169,9 @@ const isConversationMessageMetadata = (value: unknown): value is ConversationMes metadata.status === 'failed' || metadata.status === 'aborted' || metadata.status === 'unknown') && + (metadata.modelId === undefined || typeof metadata.modelId === 'string') && + (metadata.createdAt === undefined || + (typeof metadata.createdAt === 'number' && Number.isFinite(metadata.createdAt))) && (metadata.error === undefined || typeof metadata.error === 'string') ); }; diff --git a/extensions/github1s-ai/src/common/protocol.ts b/extensions/github1s-ai/src/common/protocol.ts index ceaa4a8e2..e176d494d 100644 --- a/extensions/github1s-ai/src/common/protocol.ts +++ b/extensions/github1s-ai/src/common/protocol.ts @@ -22,8 +22,11 @@ export type { Notice } from './state'; export const MAX_SYNTAX_HIGHLIGHT_SOURCE_LENGTH = 100_000; +export type ChatPhase = 'idle' | 'preparing' | 'generating'; + export interface ViewState { runtime: RuntimeState; + chatPhase: ChatPhase; promptsConfig: PromptsConfig; modelConfigs: { selectedId?: string; @@ -43,6 +46,7 @@ type AllViewEvents = | { type: 'chat.send'; text: string } | { type: 'chat.setEditingMessageId'; id?: string } | { type: 'chat.retry'; id: string } + | { type: 'chat.fork'; id: string } | { type: 'chat.runQuickAction'; action: ChatQuickAction } | { type: 'chat.addContextAttachment'; action: ContextAttachmentAction } | { type: 'chat.addContextAttachment'; action: 'descriptor'; descriptor: ContextAttachmentDescriptor } @@ -103,6 +107,7 @@ export const parseViewEvent = (value: unknown): ViewEvent | undefined => { : undefined; case 'chat.retry': + case 'chat.fork': case 'chat.removeContextAttachment': case 'history.selectConversation': case 'history.deleteConversation': diff --git a/extensions/github1s-ai/src/common/state.ts b/extensions/github1s-ai/src/common/state.ts index df937ee20..91a621edf 100644 --- a/extensions/github1s-ai/src/common/state.ts +++ b/extensions/github1s-ai/src/common/state.ts @@ -20,7 +20,6 @@ export interface RuntimeState { pendingAttachments: ContextAttachmentDescriptor[]; includeRecentFiles: boolean; }; - preparing?: boolean; notice?: Notice; }; history: { diff --git a/extensions/github1s-ai/src/controllers/app.ts b/extensions/github1s-ai/src/controllers/app.ts index 2aa805303..d557f836c 100644 --- a/extensions/github1s-ai/src/controllers/app.ts +++ b/extensions/github1s-ai/src/controllers/app.ts @@ -30,6 +30,7 @@ export class AppController extends Controller { @Controller.handler('app.newChat') async handleNewChat(_event: ViewEvent<'app.newChat'>): Promise { + await this.runner.cancelPreparation(); await this.stores.conversations.select(undefined); await this.openPage('chat', true); } diff --git a/extensions/github1s-ai/src/controllers/chat.ts b/extensions/github1s-ai/src/controllers/chat.ts index ad60e2cfd..4cf43b272 100644 --- a/extensions/github1s-ai/src/controllers/chat.ts +++ b/extensions/github1s-ai/src/controllers/chat.ts @@ -26,7 +26,7 @@ export class ChatController extends Controller { @Controller.handler('chat.setEditingMessageId') async handleSetEditingMessageId(event: ViewEvent<'chat.setEditingMessageId'>): Promise { const { chat } = await this.stores.runtime.get(); - if (chat.preparing || this.runner.isRequestActive(chat.conversation?.id)) return; + if (this.runner.getPhase(chat.conversation?.id) !== 'idle') return; if (event.id === undefined) { await this.stores.runtime.setIn('chat', { ...chat, editing: undefined, notice: undefined }); return; @@ -52,6 +52,11 @@ export class ChatController extends Controller { await this.runner.retry(event.id); } + @Controller.handler('chat.fork') + async handleFork(event: ViewEvent<'chat.fork'>): Promise { + await this.runner.fork(event.id); + } + @Controller.handler('chat.cancel') async handleCancel(_event: ViewEvent<'chat.cancel'>): Promise { await this.runner.cancelCurrent(); diff --git a/extensions/github1s-ai/src/controllers/index.ts b/extensions/github1s-ai/src/controllers/index.ts index 169e40213..27168ccf9 100644 --- a/extensions/github1s-ai/src/controllers/index.ts +++ b/extensions/github1s-ai/src/controllers/index.ts @@ -78,6 +78,7 @@ export class Controllers { const mcpConfig = runtime.page === 'settings' ? await this.stores.mcpConfig.get() : undefined; return { runtime, + chatPhase: this.runner.getPhase(runtime.chat.conversation?.id), promptsConfig, modelConfigs: { configs, selectedId: selectedModel?.id }, conversations, diff --git a/extensions/github1s-ai/src/controllers/runner.ts b/extensions/github1s-ai/src/controllers/runner.ts index 8fe6e344a..3ffbdba2f 100644 --- a/extensions/github1s-ai/src/controllers/runner.ts +++ b/extensions/github1s-ai/src/controllers/runner.ts @@ -4,12 +4,12 @@ import { addLanguageModelUsage, createNullLanguageModelUsage } from 'ai/internal import { createAssistantMessage, createUserMessage, - getRetryableMessage, withMessageStatus, type Conversation, type ConversationMessage, } from '@/common/conversation'; import { resolvePrompts } from '@/common/prompts-config'; +import type { ChatPhase } from '@/common/protocol'; import type { RuntimeState } from '@/common/state'; import { buildModelMessages } from '@/llm/helpers'; import { connectMcpTools } from '@/llm/mcp'; @@ -31,7 +31,7 @@ type MessagePreparation = { export class ConversationRunner { private readonly requests = new Map(); - private preparation: symbol | undefined; + private preparation: AbortController | undefined; constructor( private readonly stores: Stores, @@ -56,15 +56,55 @@ export class ConversationRunner { async retry(messageId: string): Promise { return this.run((chat) => { const messages = chat.conversation?.messages ?? []; - if (getRetryableMessage(messages)?.id !== messageId) return; + const index = messages.findIndex((message) => message.id === messageId && message.role === 'assistant'); + const assistant = messages[index]; + const user = messages[index - 1]; + if ( + !assistant || + assistant.metadata.status === 'streaming' || + user?.role !== 'user' || + user.metadata.turnId !== assistant.metadata.turnId + ) + return; return { - history: messages.slice(0, -2), - createMessage: async () => messages[messages.length - 2], + history: messages.slice(0, index - 1), + createMessage: async () => user, clearPendingAttachments: false, }; }); } + async fork(messageId: string): Promise { + return this.withPreparation('Unable to fork the conversation.', async (chat, { signal }) => { + const previous = chat.conversation; + if (!previous || chat.editing) return; + const index = previous.messages.findIndex((message) => message.id === messageId && message.role === 'assistant'); + if (index < 0 || previous.messages[index].metadata.status === 'streaming') return; + const now = Date.now(); + const conversation: Conversation = { + id: globalThis.crypto.randomUUID(), + title: `Fork: ${previous.title}`, + createdAt: now, + updatedAt: now, + messages: structuredClone(previous.messages.slice(0, index + 1)), + }; + await this.stores.conversations.append(conversation); + signal.throwIfAborted(); + await this.stores.conversations.select(conversation.id); + const runtime = await this.stores.runtime.get(); + if (signal.aborted || runtime.page !== 'chat' || runtime.chat.conversation?.id !== previous.id) { + await this.stores.conversations.select(runtime.chat.conversation?.id, conversation.id); + return; + } + await this.stores.runtime.setIn('chat', { + ...runtime.chat, + conversation, + pendingAttachments: [], + notice: { severity: 'success', message: "You're now in a forked conversation." }, + }); + }); + } + async edit(text: string): Promise { if (!text.trim()) return; return this.run((chat) => { @@ -100,71 +140,48 @@ export class ConversationRunner { } private async run(prepare: (chat: RuntimeState['chat']) => MessagePreparation | undefined): Promise { - if (this.preparation) return; - - const [promptsConfig, config] = await Promise.all([ - this.stores.promptsConfig.get(), - this.stores.modelConfigs.getSelected(), - ]); - const prompts = resolvePrompts(promptsConfig); - - if (!config) { - await this.stores.runtime.setIn('chat.notice', { - severity: 'error', - message: 'Select a model before sending a message.', + return this.withPreparation('Unable to prepare the conversation.', async (chat, controller) => { + const { signal } = controller; + const previous = chat.conversation; + const prepared = prepare(chat); + if (!prepared) return; + const [promptsConfig, config] = await Promise.all([ + this.stores.promptsConfig.get(), + this.stores.modelConfigs.getSelected(), + ]); + signal.throwIfAborted(); + if (!config) { + await this.stores.runtime.setIn('chat.notice', { + severity: 'error', + message: 'Select a model before sending a message.', + }); + return; + } + const prompts = resolvePrompts(promptsConfig); + const conversationId = previous?.id ?? globalThis.crypto.randomUUID(); + const userMessage = await prepared.createMessage(); + signal.throwIfAborted(); + const startedAt = Date.now(); + const providerMessages = await buildModelMessages(prepared.history, [userMessage]); + signal.throwIfAborted(); + const assistantMessage = createAssistantMessage(globalThis.crypto.randomUUID(), { + turnId: userMessage.metadata.turnId, + modelId: config.modelId, + createdAt: startedAt, }); - return; - } - const runtime = await this.stores.runtime.get(); - if (this.preparation) return; - const previous = runtime.chat.conversation; - const prepared = prepare(runtime.chat); - if (!prepared) return; - const conversationId = previous?.id ?? globalThis.crypto.randomUUID(); - if (this.requests.has(conversationId)) return; - const preparation = Symbol('conversation-preparation'); - this.preparation = preparation; - await this.stores.runtime.setIn('chat', { ...runtime.chat, preparing: true, notice: undefined }); - - let userMessage: ConversationMessage; - try { - await this.publishState(); - userMessage = await prepared.createMessage(); - } catch (error) { - const detail = error instanceof Error ? error.message : 'Unknown error.'; - await this.finishPreparation(preparation, `Unable to read the selected context attachment. ${detail}`); - return; - } - if (this.preparation !== preparation) return; - - const startedAt = Date.now(); - const turnId = userMessage.metadata.turnId; - const history = prepared.history; - let providerMessages; - try { - providerMessages = await buildModelMessages(history, [userMessage]); - } catch (error) { - const detail = error instanceof Error ? error.message : 'Unknown error.'; - await this.finishPreparation(preparation, `Unable to prepare the conversation. ${detail}`); - return; - } - if (this.preparation !== preparation) return; - - const assistantMessage = createAssistantMessage(globalThis.crypto.randomUUID(), turnId); - const conversation: Conversation = previous - ? { - ...previous, - messages: [...history, userMessage, assistantMessage], - updatedAt: startedAt, - } - : { - id: conversationId, - title: createConversationTitle(userMessage), - messages: [userMessage, assistantMessage], - createdAt: startedAt, - updatedAt: startedAt, - }; - try { + const conversation: Conversation = previous + ? { + ...previous, + messages: [...prepared.history, userMessage, assistantMessage], + updatedAt: startedAt, + } + : { + id: conversationId, + title: createConversationTitle(userMessage), + messages: [userMessage, assistantMessage], + createdAt: startedAt, + updatedAt: startedAt, + }; if (previous) { await this.stores.conversations.update(conversationId, { messages: conversation.messages, @@ -173,66 +190,54 @@ export class ConversationRunner { } else { await this.stores.conversations.append(conversation); } - } catch (error) { - const detail = error instanceof Error ? error.message : 'Unknown error.'; - await this.finishPreparation(preparation, `Unable to save the conversation. ${detail}`); - return; - } - if (this.preparation !== preparation) { - await this.setMessageStatus(conversationId, assistantMessage.id, 'aborted'); - return; - } - - this.preparation = undefined; - const abortController = new AbortController(); - const request: ActiveRequest = { - controller: abortController, - messageId: assistantMessage.id, - }; - this.requests.set(conversationId, request); - let mcp: Awaited> | undefined; - try { - const currentRuntime = await this.stores.runtime.get(); - if (currentRuntime.chat.conversation?.id === previous?.id) { - await this.stores.runtime.setIn('chat', { - ...currentRuntime.chat, - conversation, - pendingAttachments: prepared.clearPendingAttachments ? [] : currentRuntime.chat.pendingAttachments, - editing: undefined, - preparing: false, - }); - await this.stores.conversations.select(conversationId); - await this.publishState(); - } - mcp = await connectMcpTools(await this.stores.mcpConfig.get(), abortController.signal); - abortController.signal.throwIfAborted(); - const agentStream = streamLLMAgent({ ...config }, providerMessages, abortController.signal, { - instructions: prompts.instructions, - responseMessage: assistantMessage, - tools: mcp.tools, - }); - for await (const message of agentStream.stream) { - if (abortController.signal.aborted || this.requests.get(conversationId) !== request) break; - await this.persistAssistantMessage(conversationId, request, withMessageStatus(message, 'streaming')); + if (signal.aborted) { + await this.setMessageStatus(conversationId, assistantMessage.id, 'aborted'); + return; } - if (!abortController.signal.aborted && this.requests.get(conversationId) === request) { - const usage = await agentStream.usage; - if (!abortController.signal.aborted && this.requests.get(conversationId) === request) { - await this.setMessageStatus(conversationId, request.messageId, 'completed', undefined, usage); + const request: ActiveRequest = { controller, messageId: assistantMessage.id }; + this.requests.set(conversationId, request); + this.preparation = undefined; + let mcp: Awaited> | undefined; + try { + const currentRuntime = await this.stores.runtime.get(); + signal.throwIfAborted(); + if (currentRuntime.chat.conversation?.id === previous?.id) { + await this.stores.runtime.setIn('chat', { + ...currentRuntime.chat, + conversation, + pendingAttachments: prepared.clearPendingAttachments ? [] : currentRuntime.chat.pendingAttachments, + editing: undefined, + }); + await this.stores.conversations.select(conversationId); + await this.publishState(); } + mcp = await connectMcpTools(await this.stores.mcpConfig.get(), signal); + signal.throwIfAborted(); + const agentStream = streamLLMAgent({ ...config }, providerMessages, signal, { + instructions: prompts.instructions, + responseMessage: assistantMessage, + tools: mcp.tools, + }); + for await (const message of agentStream.stream) { + if (signal.aborted) break; + await this.persistAssistantMessage(conversationId, request, withMessageStatus(message, 'streaming')); + } + if (!signal.aborted) { + const usage = await agentStream.usage; + if (!signal.aborted) { + await this.setMessageStatus(conversationId, request.messageId, 'completed', undefined, usage); + } + } + } catch (error) { + if (!signal.aborted) { + const message = error instanceof Error ? error.message : 'Unknown error.'; + await this.setMessageStatus(conversationId, request.messageId, 'failed', message); + } + } finally { + if (this.requests.get(conversationId) === request) this.requests.delete(conversationId); + await Promise.all([this.publishState(), mcp?.close()]); } - } catch (error) { - if (this.requests.get(conversationId) !== request) return; - if (abortController.signal.aborted) { - await this.setMessageStatus(conversationId, request.messageId, 'aborted'); - } else { - const message = error instanceof Error ? error.message : 'Unknown error.'; - await this.setMessageStatus(conversationId, request.messageId, 'failed', message); - } - } finally { - if (this.requests.get(conversationId) === request) this.requests.delete(conversationId); - await mcp?.close(); - } + }); } async cancelCurrent(): Promise { @@ -256,8 +261,16 @@ export class ConversationRunner { return conversationId !== undefined && this.requests.has(conversationId); } + getPhase(conversationId: string | undefined): ChatPhase { + if (this.preparation) return 'preparing'; + return this.isRequestActive(conversationId) ? 'generating' : 'idle'; + } + async cancelPreparation(): Promise { - if (this.preparation) await this.finishPreparation(this.preparation); + if (!this.preparation) return; + this.preparation.abort(); + this.preparation = undefined; + await this.publishState(); } async cancelAll(): Promise { @@ -272,13 +285,13 @@ export class ConversationRunner { request: ActiveRequest, message: ConversationMessage, ): Promise { - if (this.requests.get(conversationId) !== request) return; + if (request.controller.signal.aborted) return; const conversation = await this.stores.conversations.get(conversationId); - if (!conversation || this.requests.get(conversationId) !== request) return; + if (!conversation || request.controller.signal.aborted) return; const messages = conversation.messages.map((candidate) => (candidate.id === message.id ? message : candidate)); await this.stores.conversations.update(conversationId, { messages }); const updated = { ...conversation, messages }; - await this.setCurrentConversation(updated); + await this.setCurrentConversation(updated, request.controller.signal); await this.publishState(); } @@ -305,21 +318,34 @@ export class ConversationRunner { await this.publishState(); } - private async setCurrentConversation(conversation: Conversation): Promise { + private async setCurrentConversation(conversation: Conversation, signal?: AbortSignal): Promise { const runtime = await this.stores.runtime.get(); - if (runtime.chat.conversation?.id !== conversation.id) return; + if (runtime.chat.conversation?.id !== conversation.id || signal?.aborted) return; await this.stores.runtime.setIn('chat.conversation', conversation); } - private async finishPreparation(preparation: symbol, message?: string): Promise { - if (this.preparation !== preparation) return; - this.preparation = undefined; - const runtime = await this.stores.runtime.get(); - await this.stores.runtime.setIn('chat', { - ...runtime.chat, - preparing: false, - ...(message ? { notice: { severity: 'error', message } } : {}), - }); + private async withPreparation( + failureMessage: string, + operation: (chat: RuntimeState['chat'], controller: AbortController) => Promise, + ): Promise { + const { chat } = await this.stores.runtime.get(); + if (this.getPhase(chat.conversation?.id) !== 'idle') return; + const controller = new AbortController(); + this.preparation = controller; + try { + await this.stores.runtime.setIn('chat.notice', undefined); + await this.publishState(); + controller.signal.throwIfAborted(); + await operation(chat, controller); + } catch (error) { + if (!controller.signal.aborted) { + const detail = error instanceof Error ? error.message : 'Unknown error.'; + await this.stores.runtime.setIn('chat.notice', { severity: 'error', message: `${failureMessage} ${detail}` }); + } + } finally { + if (this.preparation === controller) this.preparation = undefined; + await this.publishState(); + } } } diff --git a/extensions/github1s-ai/src/stores/conversations.ts b/extensions/github1s-ai/src/stores/conversations.ts index 3108fff88..876560797 100644 --- a/extensions/github1s-ai/src/stores/conversations.ts +++ b/extensions/github1s-ai/src/stores/conversations.ts @@ -55,9 +55,10 @@ export class ConversationsStore { return selectedId === undefined ? undefined : this.get(selectedId); } - async select(id: string | undefined): Promise { + async select(id: string | undefined, expectedId?: string): Promise { return this.enqueue(async () => { const index = await this.readIndex(); + if (expectedId !== undefined && index.selectedId !== expectedId) return; if (id !== undefined && !index.summaries.some((conversation) => conversation.id === id)) { throw new Error(`Conversation with id ${id} not found.`); } diff --git a/extensions/github1s-ai/src/webview/components/ChatPage.ts b/extensions/github1s-ai/src/webview/components/ChatPage.ts index 31f5c385f..c8473cfbf 100644 --- a/extensions/github1s-ai/src/webview/components/ChatPage.ts +++ b/extensions/github1s-ai/src/webview/components/ChatPage.ts @@ -1,7 +1,7 @@ import { html } from 'htm/preact'; import { useLayoutEffect, useRef } from 'preact/hooks'; -import { getRetryableMessage, type ConversationMessage } from '@/common/conversation'; +import type { ConversationMessage } from '@/common/conversation'; import type { ViewEvent, ViewState } from '@/common/protocol'; import { QUICK_ACTIONS } from '@/common/quick-actions'; @@ -25,37 +25,28 @@ export const ChatPage = ({ state, active, post }: ChatPageProps) => { const conversation = state.runtime.chat.conversation; const conversationId = conversation?.id; const messages = conversation?.messages ?? EMPTY_MESSAGES; - const busy = - state.runtime.chat.preparing === true || messages.some(({ metadata }) => metadata.status === 'streaming'); - const notice = state.runtime.chat.notice?.message; + const notice = state.runtime.chat.notice; const editingId = state.runtime.chat.editing?.messageId; return html` - ${notice && !editingId ? html`

${notice}

` : null} - <${Transcript} state=${state} messages=${messages} busy=${busy} active=${active} post=${post} /> + ${notice && !editingId + ? html`

+ ${notice.severity === 'success' ? html`<${Icon} name="check" />` : null} ${notice.message} +

` + : null} + <${Transcript} state=${state} messages=${messages} active=${active} post=${post} /> ${state.modelConfigs.configs.length > 0 - ? html`<${Composer} - key=${conversationId ?? 'new'} - state=${state} - busy=${busy} - active=${active && !editingId} - post=${post} - />` + ? html`<${Composer} key=${conversationId ?? 'new'} state=${state} active=${active && !editingId} post=${post} />` : null} `; }; -interface ChatContentProps extends ChatContextProps { - busy: boolean; -} - -interface TranscriptProps extends ChatContentProps { +interface TranscriptProps extends ChatContextProps { messages: readonly ConversationMessage[]; active: boolean; } -const Transcript = ({ state, messages, busy, active, post }: TranscriptProps) => { - const retryableMessage = busy ? undefined : getRetryableMessage(messages); +const Transcript = ({ state, messages, active, post }: TranscriptProps) => { const editingId = state.runtime.chat.editing?.messageId; const lastMessageBeforeEditing = useRef(); const transcript = useRef(null); @@ -98,17 +89,17 @@ const Transcript = ({ state, messages, busy, active, post }: TranscriptProps) => return html`
${messages.length === 0 - ? html`<${EmptyChat} state=${state} busy=${busy} post=${post} />` + ? html`<${EmptyChat} state=${state} post=${post} />` : messages.map((message) => message.id === editingId ? html`
- <${Composer} state=${state} busy=${busy} active=${active} post=${post} message=${message} /> + <${Composer} state=${state} active=${active} post=${post} message=${message} />
` : html`<${MessageView} key=${message.id} message=${message} - canRetry=${message === retryableMessage} - canEdit=${!busy && !editingId && state.modelConfigs.configs.length > 0} + busy=${state.chatPhase !== 'idle'} + hasModel=${state.modelConfigs.configs.length > 0} inactive=${Boolean(editingId)} post=${post} />`, @@ -121,7 +112,7 @@ const scrollToBottom = (element: HTMLElement): void => { element.scrollTop = element.scrollHeight; }; -const EmptyChat = ({ state, busy, post }: ChatContentProps) => { +const EmptyChat = ({ state, post }: ChatContextProps) => { if (state.modelConfigs.configs.length === 0) { return html`

Set up GitHub1s AI

@@ -133,11 +124,11 @@ const EmptyChat = ({ state, busy, post }: ChatContentProps) => { return html`

Ask about this repository

Choose a quick action or ask a question below.

- <${QuickActions} state=${state} busy=${busy} post=${post} /> + <${QuickActions} state=${state} post=${post} />
`; }; -const QuickActions = ({ state, busy, post }: ChatContentProps) => { +const QuickActions = ({ state, post }: ChatContextProps) => { const chat = state.runtime.chat; return html`
${QUICK_ACTIONS.map((item) => { @@ -146,7 +137,7 @@ const QuickActions = ({ state, busy, post }: ChatContentProps) => { key=${item.action} class="quick-action" type="button" - disabled=${busy || !available} + disabled=${state.chatPhase !== 'idle' || !available} onClick=${() => post({ type: 'chat.runQuickAction', action: item.action })} > <${Icon} name=${item.icon} /> diff --git a/extensions/github1s-ai/src/webview/components/Composer.ts b/extensions/github1s-ai/src/webview/components/Composer.ts index f7816830e..f2f6946f7 100644 --- a/extensions/github1s-ai/src/webview/components/Composer.ts +++ b/extensions/github1s-ai/src/webview/components/Composer.ts @@ -5,7 +5,7 @@ import type { ConversationMessage } from '@/common/conversation'; import type { ViewEvent, ViewState } from '@/common/protocol'; import { resizeComposer, shouldSubmitComposer } from '../helpers/composer'; -import { presentConversationUsage } from '../helpers/presentation'; +import { getMessageText, presentConversationUsage } from '../helpers/presentation'; import { AttachmentChips } from './AttachmentChips'; import { Icon } from './Icon'; import { RecentFilesTooltip } from './RecentFiles'; @@ -33,20 +33,18 @@ const ATTACHMENT_ACTIONS = [ interface ComposerProps { state: ViewState; - busy: boolean; active: boolean; post: (event: ViewEvent) => void; message?: ConversationMessage; } -export const Composer = ({ state, busy, active, post, message: editedMessage }: ComposerProps) => { - const [draft, setDraft] = useState(() => - editedMessage ? editedMessage.parts.flatMap((part) => (part.type === 'text' ? [part.text] : [])).join('') : '', - ); +export const Composer = ({ state, active, post, message: editedMessage }: ComposerProps) => { + const [draft, setDraft] = useState(() => (editedMessage ? getMessageText(editedMessage) : '')); const textarea = useRef(null); const chat = state.runtime.chat; const context = editedMessage ? (chat.editing ?? chat) : chat; - const preparing = chat.preparing === true; + const preparing = state.chatPhase === 'preparing'; + const busy = state.chatPhase !== 'idle'; const recentFiles = editedMessage ? editedMessage.parts.flatMap((part) => (part.type === 'data-recentFiles' ? part.data : [])) : (chat.recentFiles ?? []); diff --git a/extensions/github1s-ai/src/webview/components/Icon.ts b/extensions/github1s-ai/src/webview/components/Icon.ts index 0bd98f943..43e549768 100644 --- a/extensions/github1s-ai/src/webview/components/Icon.ts +++ b/extensions/github1s-ai/src/webview/components/Icon.ts @@ -6,9 +6,11 @@ const ICON_PATHS = { check: 'M13.2 4.3 6.5 11 2.8 7.3l.8-.8 2.9 2.9 5.9-5.9z', 'chevron-right': 'M5.7 3.3 10.4 8l-4.7 4.7-.8-.8L8.8 8 4.9 4.1z', close: 'M4 4l8 8m0-8-8 8', + copy: 'M5 1h9v11h-3v3H2V4h3zm1 3h5v7h2V2H6zM3 5v9h7V5z', download: 'M7.5 1h1v8.1l2.8-2.8.7.7-4 4-4-4 .7-.7 2.8 2.8zM2 12h1v2h10v-2h1v3H2z', edit: 'M10.9 2.1a2.1 2.1 0 0 1 3 3L6 13q-.5.5-1.1.6l-3.4.9.9-3.4q.1-.6.6-1.1zM10.1 3.6l2.3 2.3', 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', 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', @@ -29,7 +31,7 @@ interface IconProps { } export const Icon = ({ name, className }: IconProps) => { - const stroked = name === 'close' || name === 'edit'; + const stroked = name === 'close' || name === 'edit' || name === 'fork'; return html` void; } -const COPY_FEEDBACK_DURATION_MS = 1_600; let diagramSequence = 0; let mermaidTheme: string | undefined; @@ -170,18 +170,13 @@ const copyCodeBlock = async (event: MouseEvent): Promise => { const button = target.closest('button[data-copy-code]'); if (!button || !root.contains(button)) return; const code = button.closest('.code-block')?.querySelector('code')?.textContent; - if (code === undefined || !navigator.clipboard) return; + if (code === undefined || !(await copyText(code || ''))) return; - try { - await navigator.clipboard.writeText(code || ''); - button.textContent = 'Copied'; - button.setAttribute('aria-label', 'Code copied'); - window.setTimeout(() => { - if (!button.isConnected) return; - button.textContent = 'Copy'; - button.setAttribute('aria-label', 'Copy code'); - }, COPY_FEEDBACK_DURATION_MS); - } catch { - // Clipboard access can be disabled by the webview host. Keep the code selectable. - } + button.textContent = 'Copied'; + button.setAttribute('aria-label', 'Code copied'); + window.setTimeout(() => { + if (!button.isConnected) return; + button.textContent = 'Copy'; + button.setAttribute('aria-label', 'Copy code'); + }, COPY_FEEDBACK_DURATION_MS); }; diff --git a/extensions/github1s-ai/src/webview/components/MessageView.ts b/extensions/github1s-ai/src/webview/components/MessageView.ts index 32db019c3..06ba2c31c 100644 --- a/extensions/github1s-ai/src/webview/components/MessageView.ts +++ b/extensions/github1s-ai/src/webview/components/MessageView.ts @@ -1,14 +1,17 @@ import { html } from 'htm/preact'; +import { useEffect, useState } from 'preact/hooks'; import type { ConversationMessage } from '@/common/conversation'; import type { ViewEvent } from '@/common/protocol'; -import { messageStatusLabel } from '../helpers/presentation'; +import { copyText, COPY_FEEDBACK_DURATION_MS } from '../helpers/clipboard'; +import { formatConversationTime, getMessageText, messageStatusLabel } from '../helpers/presentation'; import { AssistantActivity, isAssistantActivityPart, type AssistantActivityPart } from './AssistantActivity'; import { AttachmentChips } from './AttachmentChips'; import { Icon } from './Icon'; import { Markdown } from './Markdown'; import { RecentFilesTooltip } from './RecentFiles'; +import { Tooltip, TooltipButton } from './Tooltip'; type AssistantSegment = | { type: 'activity'; key: string; parts: AssistantActivityPart[]; followedByText: boolean } @@ -16,13 +19,16 @@ type AssistantSegment = interface MessageViewProps { message: ConversationMessage; - canRetry?: boolean; - canEdit?: boolean; + busy: boolean; + hasModel: boolean; inactive?: boolean; post: (event: ViewEvent) => void; } -export const MessageView = ({ message, canRetry, canEdit, inactive, post }: MessageViewProps) => { +export const MessageView = (props: MessageViewProps) => { + const { message, inactive, post } = props; + const [now, setNow] = useState(Date.now); + const refreshTime = () => setNow(Date.now()); if (message.role !== 'user' && message.role !== 'assistant') return null; const segments = message.role === 'assistant' ? assistantSegments(message) : []; const activityRunning = segments.some( @@ -30,9 +36,14 @@ export const MessageView = ({ message, canRetry, canEdit, inactive, post }: Mess ); const status = activityRunning ? undefined : messageStatusLabel(message.metadata); - return html`
+ return html`
${message.role === 'user' - ? html`<${UserRequest} message=${message} canEdit=${canEdit} post=${post} />` + ? html`<${UserRequest} ...${props} />` : html`
${segments.map((segment) => segment.type === 'text' @@ -48,19 +59,65 @@ export const MessageView = ({ message, canRetry, canEdit, inactive, post }: Mess
`} ${status ? html`<${MessageStatus} label=${status} generating=${message.metadata.status === 'streaming'} />` : null} ${message.metadata.error ? html`` : null} - ${canRetry - ? html`` - : null} + ${message.role === 'assistant' ? html`<${AssistantFooter} ...${props} now=${now} />` : null}
`; }; +const AssistantFooter = ({ message, busy, hasModel, inactive, post, now }: MessageViewProps & { now: number }) => { + const [copied, setCopied] = useState(false); + const text = getMessageText(message, '\n\n'); + const disabled = busy || inactive; + const { modelId, createdAt } = message.metadata; + const time = createdAt === undefined ? undefined : formatConversationTime(createdAt, now); + + useEffect(() => { + if (!copied) return; + const timer = window.setTimeout(() => setCopied(false), COPY_FEEDBACK_DURATION_MS); + return () => window.clearTimeout(timer); + }, [copied]); + + return html`
+
+ <${TooltipButton} + class="icon-button" + label="Regenerate response" + disabled=${disabled || !hasModel} + onClick=${() => post({ type: 'chat.retry', id: message.id })} + > + <${Icon} name="refresh" /> + + <${TooltipButton} + class="icon-button" + label=${copied ? 'Copied' : 'Copy message'} + disabled=${!text} + onClick=${async () => setCopied(await copyText(text))} + > + <${Icon} name=${copied ? 'check' : 'copy'} /> + + <${TooltipButton} + class="icon-button" + label="Fork conversation" + disabled=${disabled} + onClick=${() => post({ type: 'chat.fork', id: message.id })} + > + <${Icon} name="fork" /> + +
+
+ ${modelId + ? html`<${Tooltip} content=${modelId}> + ${modelId} + ` + : null} + ${time?.dateTime + ? html`<${Tooltip} content=${time.dateTime}> + + ` + : null} +
+
`; +}; + const MessageStatus = ({ label, generating }: { label: string; generating: boolean }) => { if (!generating) return html`

${label}

`; return html`

@@ -100,8 +157,9 @@ const assistantSegments = (message: ConversationMessage): AssistantSegment[] => return segments; }; -const UserRequest = ({ message, canEdit, post }: MessageViewProps) => { - const text = message.parts.flatMap((part) => (part.type === 'text' ? [part.text] : [])).join(''); +const UserRequest = ({ message, busy, hasModel, inactive, post }: MessageViewProps) => { + const canEdit = !busy && !inactive && hasModel; + const text = getMessageText(message); const attachments = message.parts.flatMap((part) => (part.type === 'data-attachments' ? part.data : [])); const recentFiles = message.parts.flatMap((part) => (part.type === 'data-recentFiles' ? part.data : [])); const edit = (event: MouseEvent | KeyboardEvent) => { diff --git a/extensions/github1s-ai/src/webview/helpers/clipboard.ts b/extensions/github1s-ai/src/webview/helpers/clipboard.ts new file mode 100644 index 000000000..c7acf2654 --- /dev/null +++ b/extensions/github1s-ai/src/webview/helpers/clipboard.ts @@ -0,0 +1,10 @@ +export const COPY_FEEDBACK_DURATION_MS = 1_600; + +export const copyText = async (text: string): Promise => { + try { + await navigator.clipboard.writeText(text); + return true; + } catch { + return false; + } +}; diff --git a/extensions/github1s-ai/src/webview/helpers/presentation.ts b/extensions/github1s-ai/src/webview/helpers/presentation.ts index ee9a6aab6..6ee1ce9ca 100644 --- a/extensions/github1s-ai/src/webview/helpers/presentation.ts +++ b/extensions/github1s-ai/src/webview/helpers/presentation.ts @@ -1,6 +1,6 @@ import type { LanguageModelUsage } from 'ai'; -import type { ConversationMessageMetadata } from '@/common/conversation'; +import type { ConversationMessage, ConversationMessageMetadata } from '@/common/conversation'; const MINUTE_MS = 60_000; const HOUR_MS = 60 * MINUTE_MS; @@ -9,6 +9,9 @@ const MONTH_MS = 30 * DAY_MS; const YEAR_MS = 365 * DAY_MS; const UI_LOCALE = 'en-US'; +export const getMessageText = (message: ConversationMessage, separator = ''): string => + message.parts.flatMap((part) => (part.type === 'text' ? [part.text] : [])).join(separator); + /** * Return the transient status text that belongs beside an assistant response. * @param metadata Message status being presented. diff --git a/extensions/github1s-ai/test/conversation.test.ts b/extensions/github1s-ai/test/conversation.test.ts index f8809f9ed..a97a953a3 100644 --- a/extensions/github1s-ai/test/conversation.test.ts +++ b/extensions/github1s-ai/test/conversation.test.ts @@ -5,20 +5,12 @@ import type { ContextAttachment } from '@/common/context'; import { createAssistantMessage, createUserMessage, - getRetryableMessage, markStreamingMessagesUnknown, validateConversationMessages, withMessageStatus, type Conversation, } from '@/common/conversation'; -test('the latest failed assistant can be retried until completed', () => { - const user = createUserMessage('turn-1', 'Hello', []); - const assistant = withMessageStatus(createAssistantMessage('assistant-1', 'turn-1'), 'failed'); - assert.equal(getRetryableMessage([user, assistant]), assistant); - assert.equal(getRetryableMessage([user, withMessageStatus(assistant, 'completed')]), undefined); -}); - test('user messages capture attachments and pass conversation validation', async () => { const attachment: ContextAttachment = { id: 'file-1', @@ -44,12 +36,13 @@ test('user messages capture attachments and pass conversation validation', async }); test('message status updates preserve content and clear stale errors without mutation', () => { - const message = createAssistantMessage('assistant-1', 'turn-1'); + const metadata = { turnId: 'turn-1', modelId: 'test-model', createdAt: 1234 }; + const message = createAssistantMessage('assistant-1', metadata); message.parts.push({ type: 'text', text: 'Partial answer' }); const failed = withMessageStatus(message, 'failed', 'Connection lost'); - assert.deepEqual(failed.metadata, { turnId: 'turn-1', status: 'failed', error: 'Connection lost' }); + assert.deepEqual(failed.metadata, { ...metadata, status: 'failed', error: 'Connection lost' }); const completed = withMessageStatus(failed, 'completed'); - assert.deepEqual(completed.metadata, { turnId: 'turn-1', status: 'completed' }); + assert.deepEqual(completed.metadata, { ...metadata, status: 'completed' }); assert.deepEqual(completed.parts, message.parts); assert.equal(message.metadata.status, 'streaming'); assert.equal(failed.metadata.error, 'Connection lost'); @@ -61,7 +54,7 @@ test('restoring a conversation marks interrupted streams as unknown', () => { title: 'Test conversation', createdAt: 1, updatedAt: 1, - messages: [createUserMessage('turn-1', 'Hello', []), createAssistantMessage('assistant-1', 'turn-1')], + messages: [createUserMessage('turn-1', 'Hello', []), createAssistantMessage('assistant-1', { turnId: 'turn-1' })], }; const restored = markStreamingMessagesUnknown(conversation); assert.deepEqual( diff --git a/extensions/github1s-ai/test/model-messages.test.ts b/extensions/github1s-ai/test/model-messages.test.ts index 67119ca9c..52adf6ae5 100644 --- a/extensions/github1s-ai/test/model-messages.test.ts +++ b/extensions/github1s-ai/test/model-messages.test.ts @@ -69,7 +69,7 @@ test('model history excludes an entire turn while its assistant is streaming', a [ ...completedTurn('old', 'Previous question'), createUserMessage('pending', 'Pending question', []), - createAssistantMessage('pending-assistant', 'pending'), + createAssistantMessage('pending-assistant', { turnId: 'pending' }), ], [createUserMessage('new', 'New question', [])], ); @@ -161,7 +161,7 @@ test('model history pairs a tool with an unknown result when execution was inter }); test('an empty failed reply gets an interruption marker before the next question', async () => { - const assistant = withMessageStatus(createAssistantMessage('assistant-1', 'turn-1'), 'failed'); + const assistant = withMessageStatus(createAssistantMessage('assistant-1', { turnId: 'turn-1' }), 'failed'); const messages = await buildModelMessages( [createUserMessage('turn-1', 'Question', []), assistant], [createUserMessage('turn-2', 'Next', [])], diff --git a/extensions/github1s-ai/test/protocol.test.ts b/extensions/github1s-ai/test/protocol.test.ts index eccff276a..94576fb2e 100644 --- a/extensions/github1s-ai/test/protocol.test.ts +++ b/extensions/github1s-ai/test/protocol.test.ts @@ -8,6 +8,7 @@ test('view events accept chat commands and context descriptors', () => { { type: 'chat.send', text: 'Explain this repository.' }, { type: 'chat.cancel' }, { type: 'chat.retry', id: 'assistant-1' }, + { type: 'chat.fork', id: 'assistant-1' }, { type: 'chat.setIncludeRecentFiles', enabled: false }, { type: 'chat.setIncludeRecentFiles', enabled: true }, { type: 'chat.runQuickAction', action: 'repositoryOverview' }, diff --git a/extensions/github1s-ai/test/runner.test.ts b/extensions/github1s-ai/test/runner.test.ts index 944b69468..39ecb4481 100644 --- a/extensions/github1s-ai/test/runner.test.ts +++ b/extensions/github1s-ai/test/runner.test.ts @@ -2,7 +2,13 @@ import assert from 'node:assert/strict'; import { registerHooks } from 'node:module'; import { before, test } from 'node:test'; -import { createAssistantMessage, createUserMessage, withMessageStatus, type Conversation } from '@/common/conversation'; +import { + createAssistantMessage, + createUserMessage, + validateConversationMessages, + withMessageStatus, + type Conversation, +} from '@/common/conversation'; import type { ModelConfig } from '@/common/model-config'; import type { Stores } from '@/stores'; import { createRuntimeStateStore } from '@/stores/runtime-state'; @@ -10,7 +16,7 @@ import { createRuntimeStateStore } from '@/stores/runtime-state'; let ConversationRunner: typeof import('@/controllers/runner').ConversationRunner; before(async () => { - // Retrying snapshots must not read VS Code documents or execute repository tools. + // Conversation actions use snapshots without reading VS Code documents or executing repository tools. const hooks = registerHooks({ resolve: (specifier, context, next) => specifier === 'vscode' ? { url: 'mock:vscode', shortCircuit: true } : next(specifier, context), @@ -33,15 +39,21 @@ const setup = async () => { [{ id: 'original-file', type: 'file', label: 'a.ts', source: 'github1s:/a.ts', content: 'original file snapshot' }], [{ source: 'github1s:/original.ts' }], ); - const assistant = withMessageStatus(createAssistantMessage('old-assistant', 'turn-1'), 'failed', 'Old error'); + const assistant = withMessageStatus( + createAssistantMessage('old-assistant', { turnId: 'turn-1' }), + 'failed', + 'Old error', + ); assistant.parts.push({ type: 'text', text: 'Old partial answer' }); - let conversation: Conversation = { + const conversation: Conversation = { id: 'conversation-1', title: 'Original title', createdAt: 1, updatedAt: 1, messages: [user, assistant], }; + const savedConversations = new Map([[conversation.id, conversation]]); + let selectedId: string | undefined = conversation.id; const runtime = createRuntimeStateStore(); await runtime.set({ page: 'chat', @@ -68,14 +80,25 @@ const setup = async () => { promptsConfig: { get: async () => ({ instructions: 'Current instructions', userRules: '', quickActions: {} }) }, mcpConfig: { get: async () => ({ mcpServers: {} }) }, conversations: { - get: async () => conversation, - update: async (_id: string, update: Partial) => { - conversation = { ...conversation, ...update }; + get: async (id: string) => savedConversations.get(id), + append: async (item: Conversation) => { + savedConversations.set(item.id, item); + }, + update: async (id: string, update: Partial) => { + savedConversations.set(id, { ...savedConversations.get(id)!, ...update }); + }, + select: async (id: string | undefined) => { + selectedId = id; }, - select: async () => {}, }, } as unknown as Stores; - return { stores, user, runner: new ConversationRunner(stores, async () => {}), getConversation: () => conversation }; + return { + stores, + user, + runner: new ConversationRunner(stores, async () => {}), + getConversation: () => savedConversations.get(conversation.id)!, + getSelectedId: () => selectedId, + }; }; const response = () => @@ -122,7 +145,101 @@ test('retry replaces the failed reply using the original context and current set assert.notEqual(conversation.messages[1].id, 'old-assistant'); assert.equal(conversation.messages[1].metadata.turnId, user.metadata.turnId); assert.equal(conversation.messages[1].metadata.status, 'completed'); + assert.equal(conversation.messages[1].metadata.modelId, 'current-model'); + assert.ok(conversation.messages[1].metadata.createdAt! > 1); assert.equal(conversation.messages[1].parts.find((part) => part.type === 'text')?.text, 'New answer'); assert.equal(conversation.messages[1].metadata.error, undefined); assert.equal((await stores.runtime.get()).chat.pendingAttachments?.[0].id, 'pending-file'); + assert.deepEqual(await validateConversationMessages(conversation.messages), conversation.messages); +}); + +test('regenerating a completed reply preserves earlier history and removes later turns', async (t) => { + const { stores, runner, getConversation } = await setup(); + const previous = getConversation(); + const history = [previous.messages[0], withMessageStatus(previous.messages[1], 'completed')]; + const targetUser = createUserMessage('turn-2', 'Second question', []); + const target = withMessageStatus(createAssistantMessage('target', { turnId: 'turn-2' }), 'completed'); + target.parts.push({ type: 'text', text: 'Replace this answer' }); + const later = withMessageStatus(createAssistantMessage('later', { turnId: 'turn-3' }), 'completed'); + later.parts.push({ type: 'text', text: 'Later answer' }); + const conversation = { + ...previous, + messages: [...history, targetUser, target, createUserMessage('turn-3', 'Later question', []), later], + }; + await stores.conversations.update(previous.id, conversation); + await stores.runtime.setIn('chat.conversation', conversation); + const fetch = t.mock.method(globalThis, 'fetch', async () => response()); + + await runner.retry(target.id); + + assert.equal(fetch.mock.callCount(), 1); + const request = JSON.parse(fetch.mock.calls[0].arguments[1]?.body as string); + assert.deepEqual( + request.messages.map((message: { role: string }) => message.role), + ['system', 'user', 'assistant', 'user'], + ); + assert.match(JSON.stringify(request.messages), /Original question|Old partial answer/); + assert.match(JSON.stringify(request.messages), /Second question/); + assert.doesNotMatch(JSON.stringify(request.messages), /Replace this answer|Later question|Later answer/); + const messages = getConversation().messages; + assert.equal(messages.length, 4); + assert.deepEqual(messages.slice(0, 3), [...history, targetUser]); + assert.notEqual(messages[3].id, target.id); + assert.equal(messages[3].parts.find((part) => part.type === 'text')?.text, 'New answer'); +}); + +test('fork creates and selects an independent conversation through the chosen reply', async () => { + const { stores, runner, getConversation, getSelectedId } = await setup(); + const previous = getConversation(); + previous.messages[1].metadata.modelId = 'original-model'; + previous.messages[1].metadata.createdAt = 1234; + previous.messages[1].parts.push( + { type: 'reasoning', text: 'Original reasoning', state: 'done' }, + { + type: 'dynamic-tool', + toolCallId: 'read-1', + toolName: 'read', + state: 'output-available', + input: {}, + output: 'File content', + }, + ); + const later = withMessageStatus(createAssistantMessage('later', { turnId: 'turn-2' }), 'completed'); + const conversation = { + ...previous, + messages: [...previous.messages, createUserMessage('turn-2', 'Later question', []), later], + }; + await stores.conversations.update(previous.id, conversation); + await stores.runtime.setIn('chat.conversation', conversation); + + await runner.fork('old-assistant'); + + const fork = (await stores.runtime.get()).chat.conversation!; + assert.notEqual(fork.id, previous.id); + assert.equal(getSelectedId(), fork.id); + assert.deepEqual(await stores.conversations.get(fork.id), fork); + assert.deepEqual(fork.messages, previous.messages); + assert.equal(getConversation().messages.length, 4); + assert.deepEqual((await stores.runtime.get()).chat.pendingAttachments, []); + const attachmentPart = fork.messages[0].parts.find((part) => part.type === 'data-attachments')!; + attachmentPart.data[0].content = 'Changed in fork'; + assert.equal( + getConversation().messages[0].parts.find((part) => part.type === 'data-attachments')!.data[0].content, + 'original file snapshot', + ); +}); + +test('fork preserves navigation that changes while its messages are being saved', async (t) => { + const { stores, runner, getConversation, getSelectedId } = await setup(); + const destination = { ...getConversation(), id: 'other-conversation' }; + const select = stores.conversations.select.bind(stores.conversations); + t.mock.method(stores.conversations, 'select', async (id: string | undefined) => { + await select(id); + await stores.runtime.setIn('chat.conversation', destination); + }); + + await runner.fork('old-assistant'); + + assert.equal(getSelectedId(), destination.id); + assert.deepEqual((await stores.runtime.get()).chat.conversation, destination); }); diff --git a/tests/__tests__/index.test.ts b/tests/__tests__/index.test.ts index bf9210dd5..b310039b3 100644 --- a/tests/__tests__/index.test.ts +++ b/tests/__tests__/index.test.ts @@ -48,13 +48,14 @@ it('should load successfully', async () => { expect(tab).toBe('[Preview] README.md'); // Title updated based on the repo expect(await page.title()).toMatch(/\[Preview\] README\.md . conwnet\/github1s . GitHub1s/); - await page.waitForTimeout(5000); - // README file will be rendered in an iframe - await page.$eval( - 'iframe.webview.ready[sandbox="allow-scripts allow-same-origin allow-forms allow-pointer-lock allow-downloads"][src]', - (el: HTMLElement) => el.innerHTML, - ); + // Wait for the README content and its assets inside the nested webview frames. + const preview = page.frameLocator('iframe.webview.ready').frameLocator('iframe[title="[Preview] README.md"]'); + await preview.getByRole('heading', { name: 'GitHub1s', exact: true }).waitFor(); + await preview.locator('body').evaluate(async () => { + await document.fonts.ready; + await Promise.all(Array.from(document.images, (image) => image.decode())); + }); const image = await page.screenshot(); expect(image).toMatchImageSnapshot(matchImageSnapshotOptions); From bf3d8698f3c9c52720c1434494de0b8616d42840 Mon Sep 17 00:00:00 2001 From: netcon Date: Thu, 5 Nov 2026 10:56:43 +0800 Subject: [PATCH 15/19] feat(ai): allow edit conversation title (#800) * feat(ai): allow edit conversation title * fix(ai): use alt + Enter to send message --- extensions/github1s-ai/assets/chat.css | 39 +++-- extensions/github1s-ai/src/common/protocol.ts | 26 +-- .../github1s-ai/src/controllers/history.ts | 21 +++ .../github1s-ai/src/controllers/runner.ts | 2 +- .../github1s-ai/src/helpers/validate.ts | 9 +- .../src/webview/components/Composer.ts | 8 + .../src/webview/components/HistoryPage.ts | 163 ++++++++++++++---- extensions/github1s-ai/test/protocol.test.ts | 30 +++- 8 files changed, 235 insertions(+), 63 deletions(-) diff --git a/extensions/github1s-ai/assets/chat.css b/extensions/github1s-ai/assets/chat.css index dc95f14cf..6d1f7c750 100644 --- a/extensions/github1s-ai/assets/chat.css +++ b/extensions/github1s-ai/assets/chat.css @@ -178,6 +178,8 @@ summary:focus-visible, .settings-card-actions, .settings-meta, .history-row, +.history-actions, +.history-title-editor, .history-confirm { display: flex; align-items: center; @@ -235,7 +237,7 @@ summary:focus-visible, box-sizing: border-box; display: flex; min-width: 0; - align-items: flex-start; + align-items: center; gap: 6px; padding: 8px; border: 1px solid var(--vscode-widget-border, transparent); @@ -475,7 +477,8 @@ summary:focus-visible, margin: 0; } -.settings-control { +.settings-control, +.history-title-input { width: 100%; min-width: 0; padding: 6px 7px; @@ -485,7 +488,8 @@ summary:focus-visible, border-radius: 3px; } -.settings-control:focus-visible { +.settings-control:focus-visible, +.history-title-input:focus-visible { border-color: var(--vscode-focusBorder); outline: none; } @@ -554,9 +558,11 @@ summary:focus-visible, } .history-row { + box-sizing: border-box; min-width: 0; + height: 46px; gap: 4px; - padding: 6px 8px; + padding: 5px 8px; border: 1px solid transparent; border-radius: 4px; } @@ -591,6 +597,17 @@ summary:focus-visible, white-space: nowrap; } +.history-title-editor { + min-width: 0; + flex: 1; + gap: 4px; +} + +.history-title-input { + height: 24px; + padding: 2px 6px; +} + .history-empty { margin: 12px 0; color: var(--vscode-descriptionForeground); @@ -617,14 +634,16 @@ summary:focus-visible, text-overflow: ellipsis; } -.history-delete { - opacity: 0; +.history-actions { + display: none; + flex: none; + gap: 2px; } -.history-row:hover .history-delete, -.history-row:focus-within .history-delete, -.history-row-active .history-delete { - opacity: 1; +.history-row:hover .history-actions, +.history-row:focus-within .history-actions, +.history-row-active .history-actions { + display: flex; } .ghost-button.history-confirm-delete { diff --git a/extensions/github1s-ai/src/common/protocol.ts b/extensions/github1s-ai/src/common/protocol.ts index e176d494d..029a4d3df 100644 --- a/extensions/github1s-ai/src/common/protocol.ts +++ b/extensions/github1s-ai/src/common/protocol.ts @@ -1,6 +1,6 @@ import { isPlainObject } from 'lodash-es'; -import { exactString, hasExactKeys } from '@/helpers/validate'; +import { exactString, hasExactKeys, isNonBlankString, isNonEmptyString } from '@/helpers/validate'; import { isContextAttachmentAction, @@ -54,6 +54,7 @@ type AllViewEvents = | { type: 'chat.setIncludeRecentFiles'; enabled: boolean } | { type: 'chat.cancel' } | { type: 'history.selectConversation'; id: string } + | { type: 'history.renameConversation'; id: string; title: string } | { type: 'history.deleteConversation'; id: string } | { type: 'markdown.highlight'; requestId: string; languageId: string; source: string } | { type: 'settings.selectModelConfig'; id: string } @@ -90,22 +91,25 @@ export const parseViewEvent = (value: unknown): ViewEvent | undefined => { return hasExactKeys(event, ['type']) ? { type: event.type } : undefined; case 'app.openFile': - return exactString(event, 'source') ? { type: event.type, source: event.source as string } : undefined; + return exactString(event, 'source') ? { type: event.type, source: event.source } : undefined; case 'chat.send': - return hasExactKeys(event, ['type', 'text']) && typeof event.text === 'string' - ? { type: event.type, text: event.text } - : undefined; + return exactString(event, 'text') ? { type: event.type, text: event.text } : undefined; case 'chat.setEditingMessageId': if (hasExactKeys(event, ['type'])) return { type: event.type }; - return exactString(event, 'id') ? { type: event.type, id: event.id as string } : undefined; + return exactString(event, 'id') ? { type: event.type, id: event.id } : undefined; case 'chat.setIncludeRecentFiles': return hasExactKeys(event, ['type', 'enabled']) && typeof event.enabled === 'boolean' ? { type: event.type, enabled: event.enabled } : undefined; + case 'history.renameConversation': + return hasExactKeys(event, ['type', 'id', 'title']) && isNonEmptyString(event.id) && isNonBlankString(event.title) + ? { type: event.type, id: event.id, title: event.title } + : undefined; + case 'chat.retry': case 'chat.fork': case 'chat.removeContextAttachment': @@ -113,7 +117,7 @@ export const parseViewEvent = (value: unknown): ViewEvent | undefined => { case 'history.deleteConversation': case 'settings.selectModelConfig': case 'settings.deleteModelConfig': - return exactString(event, 'id') ? { type: event.type, id: event.id as string } : undefined; + return exactString(event, 'id') ? { type: event.type, id: event.id } : undefined; case 'chat.runQuickAction': return exactString(event, 'action') && isQuickAction(event.action) @@ -133,10 +137,8 @@ export const parseViewEvent = (value: unknown): ViewEvent | undefined => { case 'markdown.highlight': if ( !hasExactKeys(event, ['type', 'requestId', 'languageId', 'source']) || - typeof event.requestId !== 'string' || - event.requestId.length === 0 || - typeof event.languageId !== 'string' || - event.languageId.length === 0 || + !isNonEmptyString(event.requestId) || + !isNonEmptyString(event.languageId) || typeof event.source !== 'string' || event.source.length > MAX_SYNTAX_HIGHLIGHT_SOURCE_LENGTH ) { @@ -158,7 +160,7 @@ export const parseViewEvent = (value: unknown): ViewEvent | undefined => { ? { type: event.type, config: event.config } : undefined; case 'settings.saveMcpConfig': - return exactString(event, 'json') ? { type: event.type, json: event.json as string } : undefined; + return exactString(event, 'json') ? { type: event.type, json: event.json } : undefined; default: return undefined; } diff --git a/extensions/github1s-ai/src/controllers/history.ts b/extensions/github1s-ai/src/controllers/history.ts index cc40eb417..4afc8379d 100644 --- a/extensions/github1s-ai/src/controllers/history.ts +++ b/extensions/github1s-ai/src/controllers/history.ts @@ -44,6 +44,27 @@ export class HistoryController extends Controller { }); } + @Controller.handler('history.renameConversation') + async handleRenameConversation(event: ViewEvent<'history.renameConversation'>): Promise { + const title = event.title.trim(); + if (!title) return; + try { + await this.stores.conversations.update(event.id, { title }); + } catch (error) { + const detail = error instanceof Error ? error.message : 'Unknown error.'; + await this.stores.runtime.setIn('history.notice', { + severity: 'error', + message: `Unable to rename the conversation. ${detail}`, + }); + return; + } + const runtime = await this.stores.runtime.get(); + if (runtime.chat.conversation?.id === event.id) { + await this.stores.runtime.setIn('chat.conversation.title', title); + } + await this.stores.runtime.setIn('history.notice', undefined); + } + @Controller.handler('history.deleteConversation') async handleDeleteConversation(event: ViewEvent<'history.deleteConversation'>): Promise { const selected = (await this.stores.runtime.get()).chat.conversation?.id === event.id; diff --git a/extensions/github1s-ai/src/controllers/runner.ts b/extensions/github1s-ai/src/controllers/runner.ts index 3ffbdba2f..36e765c1d 100644 --- a/extensions/github1s-ai/src/controllers/runner.ts +++ b/extensions/github1s-ai/src/controllers/runner.ts @@ -321,7 +321,7 @@ export class ConversationRunner { private async setCurrentConversation(conversation: Conversation, signal?: AbortSignal): Promise { const runtime = await this.stores.runtime.get(); if (runtime.chat.conversation?.id !== conversation.id || signal?.aborted) return; - await this.stores.runtime.setIn('chat.conversation', conversation); + await this.stores.runtime.setIn('chat.conversation', { ...conversation, title: runtime.chat.conversation.title }); } private async withPreparation( diff --git a/extensions/github1s-ai/src/helpers/validate.ts b/extensions/github1s-ai/src/helpers/validate.ts index b72d426c5..41a8d8eb2 100644 --- a/extensions/github1s-ai/src/helpers/validate.ts +++ b/extensions/github1s-ai/src/helpers/validate.ts @@ -1,5 +1,12 @@ -export const exactString = (value: Record, key: string): boolean => +export const exactString = ( + value: Record, + key: Key, +): value is Record & Record => hasExactKeys(value, ['type', key]) && typeof value[key] === 'string'; export const hasExactKeys = (value: Record, keys: readonly string[]): boolean => Object.keys(value).length === keys.length && keys.every((key) => Object.prototype.hasOwnProperty.call(value, key)); + +export const isNonEmptyString = (value: unknown): value is string => typeof value === 'string' && value.length > 0; + +export const isNonBlankString = (value: unknown): value is string => isNonEmptyString(value) && value.trim().length > 0; diff --git a/extensions/github1s-ai/src/webview/components/Composer.ts b/extensions/github1s-ai/src/webview/components/Composer.ts index f2f6946f7..de264f68f 100644 --- a/extensions/github1s-ai/src/webview/components/Composer.ts +++ b/extensions/github1s-ai/src/webview/components/Composer.ts @@ -98,6 +98,14 @@ export const Composer = ({ state, active, post, message: editedMessage }: Compos }; const onKeyDown = (event: KeyboardEvent) => { + if (event.key === 'Enter' && event.altKey && !event.isComposing) { + event.preventDefault(); + const input = event.currentTarget as HTMLTextAreaElement; + // Use a native editing command to preserve undo history. + document.execCommand('insertText', false, '\n'); + setDraft(input.value); + return; + } if (!shouldSubmitComposer(event)) return; event.preventDefault(); submit(); diff --git a/extensions/github1s-ai/src/webview/components/HistoryPage.ts b/extensions/github1s-ai/src/webview/components/HistoryPage.ts index fcd04f8c0..9e3403ac3 100644 --- a/extensions/github1s-ai/src/webview/components/HistoryPage.ts +++ b/extensions/github1s-ai/src/webview/components/HistoryPage.ts @@ -1,5 +1,5 @@ import { html } from 'htm/preact'; -import { useEffect, useState } from 'preact/hooks'; +import { useEffect, useLayoutEffect, useRef, useState } from 'preact/hooks'; import type { ViewEvent, ViewState } from '@/common/protocol'; @@ -15,7 +15,7 @@ interface HistoryPageProps { const RELATIVE_TIME_REFRESH_INTERVAL_MS = 60_000; export const HistoryPage = ({ state, post }: HistoryPageProps) => { - const [confirmingId, setConfirmingId] = useState(); + const [rowAction, setRowAction] = useState<{ id: string; type: 'edit' | 'delete' }>(); const [now, setNow] = useState(Date.now()); useEffect(() => { @@ -35,53 +35,144 @@ export const HistoryPage = ({ state, post }: HistoryPageProps) => { ${conversations.map((conversation) => { const title = conversation.title; const isActive = conversation.id === state.runtime.chat.conversation?.id; + const action = rowAction?.id === conversation.id ? rowAction.type : undefined; const time = formatConversationTime(conversation.updatedAt, now); const usage = presentConversationUsage(conversation.usage); + const editLabel = `Edit ${title}`; const deleteLabel = `Delete ${title}`; return html`

- - ${confirmingId === conversation.id - ? html`
- - -
` + ${action === 'edit' + ? html`<${HistoryTitleEditor} + title=${title} + onSave=${(title: string) => + post({ type: 'history.renameConversation', id: conversation.id, title })} + onCancel=${() => setRowAction(undefined)} + />` : html``} + ${action === 'edit' + ? null + : action === 'delete' + ? html`
+ + +
` + : html`
+ + +
`}
`; })}
`}
`; }; + +interface HistoryTitleEditorProps { + title: string; + onSave: (title: string) => void; + onCancel: () => void; +} + +const HistoryTitleEditor = ({ title, onSave, onCancel }: HistoryTitleEditorProps) => { + const [draft, setDraft] = useState(title); + const [submittedTitle, setSubmittedTitle] = useState(); + const input = useRef(null); + const nextTitle = draft.trim(); + + useLayoutEffect(() => { + input.current?.focus(); + input.current?.select(); + }, []); + + useEffect(() => { + if (submittedTitle !== title) return; + setSubmittedTitle(undefined); + if (nextTitle === title) onCancel(); + }, [title, submittedTitle, nextTitle, onCancel]); + + return html`
{ + event.preventDefault(); + if (!nextTitle) return; + if (nextTitle === title && submittedTitle === undefined) { + onCancel(); + return; + } + setSubmittedTitle(nextTitle); + onSave(nextTitle); + }} + onKeyDown=${(event: KeyboardEvent) => { + if (event.isComposing || event.keyCode === 229) { + if (event.key === 'Enter') event.preventDefault(); + return; + } + if (event.key === 'Escape') { + event.preventDefault(); + onCancel(); + } + }} + > + setDraft((event.currentTarget as HTMLInputElement).value)} + /> +
+ + +
+
`; +}; diff --git a/extensions/github1s-ai/test/protocol.test.ts b/extensions/github1s-ai/test/protocol.test.ts index 94576fb2e..3e755bea0 100644 --- a/extensions/github1s-ai/test/protocol.test.ts +++ b/extensions/github1s-ai/test/protocol.test.ts @@ -38,6 +38,22 @@ test('view events reject malformed payloads, unknown actions and unexpected fiel } }); +test('conversation title updates require an ID and a nonblank title', () => { + const event = { type: 'history.renameConversation', id: 'conversation-1', title: ' A new title ' }; + assert.deepEqual(parseViewEvent(event), event); + for (const invalid of [ + { ...event, id: '' }, + { ...event, id: 123 }, + { ...event, title: '' }, + { ...event, title: ' \t\n ' }, + { ...event, title: 123 }, + { type: event.type, id: event.id }, + { ...event, extra: true }, + ]) { + assert.equal(parseViewEvent(invalid), undefined, JSON.stringify(invalid)); + } +}); + test('highlight requests enforce the source length limit and required fields', () => { const request = { type: 'markdown.highlight', @@ -46,7 +62,15 @@ test('highlight requests enforce the source length limit and required fields', ( source: 'x'.repeat(MAX_SYNTAX_HIGHLIGHT_SOURCE_LENGTH), }; assert.deepEqual(parseViewEvent(request), request); - assert.equal(parseViewEvent({ ...request, source: `${request.source}x` }), undefined); - assert.equal(parseViewEvent({ ...request, requestId: '' }), undefined); - assert.equal(parseViewEvent({ ...request, extra: true }), undefined); + for (const invalid of [ + { ...request, source: `${request.source}x` }, + { ...request, source: 123 }, + { ...request, requestId: '' }, + { ...request, requestId: 123 }, + { ...request, languageId: '' }, + { ...request, languageId: 123 }, + { ...request, extra: true }, + ]) { + assert.equal(parseViewEvent(invalid), undefined); + } }); From b895b692ba476312c2866306d6a4705a008e7543 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 5 Nov 2026 10:57:30 +0800 Subject: [PATCH 16/19] chore(deps): bump zod from 4.4.3 to 4.6.7 in /extensions/github1s-ai (#798) Bumps [zod](https://github.com/colinhacks/zod) from 4.4.3 to 4.6.7. - [Release notes](https://github.com/colinhacks/zod/releases) - [Commits](https://github.com/colinhacks/zod/compare/v4.4.3...v4.6.7) --- updated-dependencies: - dependency-name: zod dependency-version: 4.6.7 dependency-type: indirect ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- extensions/github1s-ai/package-lock.json | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/extensions/github1s-ai/package-lock.json b/extensions/github1s-ai/package-lock.json index a457412d6..a3c240835 100644 --- a/extensions/github1s-ai/package-lock.json +++ b/extensions/github1s-ai/package-lock.json @@ -4899,9 +4899,9 @@ "license": "MIT" }, "node_modules/zod": { - "version": "4.4.3", - "resolved": "https://registry.npmjs.org/zod/-/zod-4.4.3.tgz", - "integrity": "sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ==", + "version": "4.6.7", + "resolved": "https://registry.npmjs.org/zod/-/zod-4.6.7.tgz", + "integrity": "sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg==", "license": "MIT", "peer": true, "funding": { From 7c545b1c41f430d96dc41b89d69322dca4fcb056 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 5 Nov 2026 10:57:59 +0800 Subject: [PATCH 17/19] chore(deps): bump serialize-javascript in /extensions/github1s-ai (#797) Bumps [serialize-javascript](https://github.com/yahoo/serialize-javascript) from 7.1.0 to 7.1.4. - [Release notes](https://github.com/yahoo/serialize-javascript/releases) - [Commits](https://github.com/yahoo/serialize-javascript/compare/v7.1.0...v7.1.4) --- updated-dependencies: - dependency-name: serialize-javascript dependency-version: 7.1.4 dependency-type: indirect ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- extensions/github1s-ai/package-lock.json | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/extensions/github1s-ai/package-lock.json b/extensions/github1s-ai/package-lock.json index a3c240835..ed014b68c 100644 --- a/extensions/github1s-ai/package-lock.json +++ b/extensions/github1s-ai/package-lock.json @@ -4373,9 +4373,9 @@ } }, "node_modules/serialize-javascript": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/serialize-javascript/-/serialize-javascript-7.1.0.tgz", - "integrity": "sha512-RNEqWOyhhUQYN9V1GfHwu9AR/g+NTciH6Z5u3/no6X3/w+04J2lVDL+svFQVXgXrEGBMG2puMVN3gq2SNGuTGw==", + "version": "7.1.4", + "resolved": "https://registry.npmjs.org/serialize-javascript/-/serialize-javascript-7.1.4.tgz", + "integrity": "sha512-FqlEuoTq/zRmA4Lg6aOqyH3lCHbUtCB0bmHCeFniX2GBdDqMJM3FwdvEhlE5Pim1dlt2FfBdVPmUNNiGhhKqpw==", "dev": true, "license": "BSD-3-Clause", "engines": { From c415af3c02d9fccd64ecf5ce8efead0da5c9740c Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 5 Nov 2026 11:09:40 +0800 Subject: [PATCH 18/19] chore(deps): bump minimatch from 9.0.9 to 11.0.1 in /extensions/github1s (#801) Bumps [minimatch](https://github.com/isaacs/minimatch) from 9.0.9 to 11.0.1. - [Changelog](https://github.com/isaacs/minimatch/blob/main/changelog.md) - [Commits](https://github.com/isaacs/minimatch/compare/v9.0.9...v11.0.1) --- updated-dependencies: - dependency-name: minimatch dependency-version: 11.0.1 dependency-type: direct:production ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- extensions/github1s/package-lock.json | 43 +++++++++++++++++---------- extensions/github1s/package.json | 2 +- 2 files changed, 29 insertions(+), 16 deletions(-) diff --git a/extensions/github1s/package-lock.json b/extensions/github1s/package-lock.json index 9806fe069..5c6ee93ae 100644 --- a/extensions/github1s/package-lock.json +++ b/extensions/github1s/package-lock.json @@ -17,7 +17,7 @@ "js-base64": "^3.7.2", "json-stable-stringify": "^1.0.1", "match-sorter": "^6.3.1", - "minimatch": "^9.0.9", + "minimatch": "^11.0.1", "p-finally": "^3.0.0", "process": "^0.11.10", "query-string": "^9.5.0" @@ -108,6 +108,12 @@ "graphql": "^0.8.0 || ^0.9.0 || ^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^14.0.0 || ^15.0.0 || ^16.0.0 || ^17.0.0" } }, + "node_modules/@isaacs/nonrecursive-glob-match": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/@isaacs/nonrecursive-glob-match/-/nonrecursive-glob-match-1.0.3.tgz", + "integrity": "sha512-SI7kyKHq4XXDRozw+r9GlRZkia1ZkFrpLW98r2IC2Bpr8YkFGE3fvjzmxCG0x78A++69HmDNrDvSMYBZmHGpKA==", + "license": "BlueOak-1.0.0" + }, "node_modules/@jridgewell/gen-mapping": { "version": "0.3.13", "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", @@ -689,10 +695,13 @@ } }, "node_modules/balanced-match": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", - "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", - "license": "MIT" + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", + "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==", + "license": "MIT", + "engines": { + "node": "18 || 20 || >=22" + } }, "node_modules/base64-js": { "version": "1.5.1", @@ -742,12 +751,15 @@ "license": "MIT" }, "node_modules/brace-expansion": { - "version": "2.1.7", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.7.tgz", - "integrity": "sha512-uZbew1NqdmPDTMJ8ah1y+b+9QEJrfkXFk3RcTQw3X0jW/xRUvFKsg1CfQdSYGdTbXZWExtU3J3ccxtnfw1Fi0g==", + "version": "5.0.12", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.12.tgz", + "integrity": "sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==", "license": "MIT", "dependencies": { - "balanced-match": "^1.0.0" + "balanced-match": "^4.0.2" + }, + "engines": { + "node": "20 || >=22" } }, "node_modules/braces": { @@ -2461,15 +2473,16 @@ "license": "MIT" }, "node_modules/minimatch": { - "version": "9.0.9", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.9.tgz", - "integrity": "sha512-OBwBN9AL4dqmETlpS2zasx+vTeWclWzkblfZk7KTA5j3jeOONz/tRCnZomUyvNg83wL5Zv9Ss6HMJXAgL8R2Yg==", - "license": "ISC", + "version": "11.0.1", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-11.0.1.tgz", + "integrity": "sha512-t+Vn6DX4wPCxS23y03C0uhF7S1jpi1GfqPrnlEipCJaA2ykiNbMkVlDutZtmvLfRcUN6R8AYVlzTsQrT4RZoLQ==", + "license": "BlueOak-1.0.0", "dependencies": { - "brace-expansion": "^2.0.2" + "@isaacs/nonrecursive-glob-match": "^1.0.1", + "brace-expansion": "^5.0.12" }, "engines": { - "node": ">=16 || 14 >=14.17" + "node": "18 || 20 || >=22" }, "funding": { "url": "https://github.com/sponsors/isaacs" diff --git a/extensions/github1s/package.json b/extensions/github1s/package.json index 6ce5881c1..99d781d25 100644 --- a/extensions/github1s/package.json +++ b/extensions/github1s/package.json @@ -621,7 +621,7 @@ "js-base64": "^3.7.2", "json-stable-stringify": "^1.0.1", "match-sorter": "^6.3.1", - "minimatch": "^9.0.9", + "minimatch": "^11.0.1", "p-finally": "^3.0.0", "process": "^0.11.10", "query-string": "^9.5.0" From 98ddf0fbd549c398ffbd2bb6f62051d156d50394 Mon Sep 17 00:00:00 2001 From: netcon Date: Tue, 17 Nov 2026 19:10:13 +0800 Subject: [PATCH 19/19] feat(ai): allow import/export conversations (#802) * feat(ai): allow import/export conversations * chore: fix ci --- .github/workflows/build.yml | 2 +- .github/workflows/test-wtih-vscode-build.yml | 2 +- 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 ++ 16 files changed, 711 insertions(+), 183 deletions(-) create mode 100644 extensions/github1s-ai/src/webview/components/HistoryImportDialog.ts 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 }} 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',