From 531f043ab797cb39e839cac4d2e313554830588d Mon Sep 17 00:00:00 2001 From: batchema Date: Wed, 11 Nov 2026 11:48:13 -0500 Subject: [PATCH 01/20] docs: add fork TODO list --- TODO.md | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 TODO.md diff --git a/TODO.md b/TODO.md new file mode 100644 index 0000000000000..cc136e3cf0039 --- /dev/null +++ b/TODO.md @@ -0,0 +1,20 @@ +# TODO + +- [ ] **Vim motions in the composer.** An opt-in vim mode for the chat input, like Claude Code's + `/vim`: normal and insert modes, common motions (`hjkl`, `w`/`b`/`e`, `0`/`$`, `gg`/`G`), + operators (`d`, `c`, `y`) with motions and text objects, and a visible mode indicator. +- [ ] **`ctrl+`` toggles the terminal.** Match VS Code: `ctrl+`` opens and closes the terminal + drawer, alongside the existing `mod+j`, including while the terminal has focus. +- [ ] **Setting to hide thread details by default.** New threads always open the Thread Details + card because `inlineOpen: true` is hardcoded in `apps/web/src/rightPanelStore.ts`. Add a + setting such as "Show thread details in new threads" that feeds that default. Leave it on by + default to match today's behavior. Toggling per thread (button or `mod+shift+b`) should keep + working as it does now. +- [ ] **Agents can drive all of T3 Code.** Extend the T3 MCP server beyond orchestration + (threads, projects, previews, devices) so agents can also control the app itself: settings, + keybindings, panels and layout, navigation, and any action a user can trigger from the UI or + command palette. +- [ ] **Agents know about linked environments.** Agents can't currently see the other machines + linked to T3 Code (e.g. a devbox): the environment-listing MCP tool isn't exposed, so an + agent only knows its own environment. Let agents list linked environments (label, platform, + ID) when they need to, so they can act on or hand work off to another machine. From b34e7d84ccc86d73c8fca0ab431d0d4da4305ffe Mon Sep 17 00:00:00 2001 From: Batch Processor <46352227+batchema@users.noreply.github.com> Date: Wed, 11 Nov 2026 11:52:45 -0500 Subject: [PATCH 02/20] feat(web): vim mode for the composer (#1) Vim users had to leave their muscle memory at the composer. An opt-in vim mode (Settings > Chat > Vim mode, the command palette, or the unbound `composer.toggleVimMode` keybinding) adds insert and normal modes modeled on Claude Code's `/vim`. A pure engine in `composer-vim.ts` parses keys and computes motions, operators, text objects, counts, `.` repeat and the unnamed register over flat text where a chip is one character. `composer-vim-editor.ts` maps that text to the Tiptap document with the existing coordinate helpers and applies each command as ProseMirror transactions, so undo and redo use the editor's history and each command is one undo step. Yanks keep their Markdown, so a put restores chips. Menus and suggestions still take Escape first, Escape in normal mode keeps its existing meaning, and Enter in normal mode goes through the send shortcut. A footer badge shows the mode and normal mode draws a block cursor. Mobile is not supported. Co-authored-by: batchema --- apps/web/src/components/CommandPalette.tsx | 14 + .../src/components/CommandPaletteLookups.ts | 1 + .../components/ComposerPromptEditorTiptap.tsx | 121 ++- ...serPromptEditorTiptap.vim.browser.test.tsx | 114 +++ apps/web/src/components/chat/ChatComposer.tsx | 12 + .../src/components/chat/composerShortcuts.ts | 6 +- .../src/components/chat/composerVimMode.ts | 12 + .../components/settings/SettingsPanels.tsx | 23 + .../src/components/settings/settingsSearch.ts | 6 + apps/web/src/composer-vim-editor.ts | 244 +++++ apps/web/src/composer-vim.test.ts | 202 ++++ apps/web/src/composer-vim.ts | 881 ++++++++++++++++++ apps/web/src/index.css | 19 + docs/user/composer.md | 23 + docs/user/keybindings.md | 3 + packages/contracts/src/keybindings.ts | 1 + packages/contracts/src/settings.ts | 2 + 17 files changed, 1655 insertions(+), 29 deletions(-) create mode 100644 apps/web/src/components/ComposerPromptEditorTiptap.vim.browser.test.tsx create mode 100644 apps/web/src/components/chat/composerVimMode.ts create mode 100644 apps/web/src/composer-vim-editor.ts create mode 100644 apps/web/src/composer-vim.test.ts create mode 100644 apps/web/src/composer-vim.ts diff --git a/apps/web/src/components/CommandPalette.tsx b/apps/web/src/components/CommandPalette.tsx index a73322fc65114..126fac928909b 100644 --- a/apps/web/src/components/CommandPalette.tsx +++ b/apps/web/src/components/CommandPalette.tsx @@ -65,6 +65,7 @@ import { FolderGit2Icon, FolderIcon, FolderPlusIcon, + KeyboardIcon, MessageSquareDashedIcon, LinkIcon, MessageSquareIcon, @@ -80,6 +81,7 @@ import { UserPlusIcon, } from "lucide-react"; import { openThreadFind } from "./chat/threadFindStore"; +import { toggleComposerVimMode } from "./chat/composerVimMode"; import { useDeferredValue, useEffect, @@ -1662,6 +1664,18 @@ function OpenCommandPaletteDialog(props: { }); } + actionItems.push({ + kind: "action", + value: "action:toggle-vim-mode", + searchTerms: ["vim", "vi", "normal mode", "insert mode", "composer", "keyboard"], + title: clientSettings.composerVimMode ? "Turn off vim mode" : "Turn on vim mode", + icon: , + shortcutCommand: "composer.toggleVimMode", + run: async () => { + toggleComposerVimMode(); + }, + }); + actionItems.push({ kind: "action", value: "action:settings", diff --git a/apps/web/src/components/CommandPaletteLookups.ts b/apps/web/src/components/CommandPaletteLookups.ts index 3eb0ff69bf1c7..0849caca24584 100644 --- a/apps/web/src/components/CommandPaletteLookups.ts +++ b/apps/web/src/components/CommandPaletteLookups.ts @@ -51,6 +51,7 @@ export const selectCommandPaletteClientSettings = (settings: ClientSettings) => sidebarProjectGroupingOverrides: settings.sidebarProjectGroupingOverrides, sidebarProjectSortOrder: settings.sidebarProjectSortOrder, sidebarThreadSortOrder: settings.sidebarThreadSortOrder, + composerVimMode: settings.composerVimMode, }); export function useSortedProjectGroups(environmentLabelById: ReadonlyMap) { diff --git a/apps/web/src/components/ComposerPromptEditorTiptap.tsx b/apps/web/src/components/ComposerPromptEditorTiptap.tsx index 1986cc888efba..96fd5544ac722 100644 --- a/apps/web/src/components/ComposerPromptEditorTiptap.tsx +++ b/apps/web/src/components/ComposerPromptEditorTiptap.tsx @@ -110,6 +110,14 @@ import { groupUndoByChangeKind, markAsClipboardEdit, } from "~/composer-undo-grouping"; +import { INITIAL_VIM_STATE, type VimMode, type VimState } from "~/composer-vim"; +import { + ComposerVimExtension, + type ComposerVimContext, + composerVimMode, + handleComposerVimKeyDown, + showComposerVimMode, +} from "~/composer-vim-editor"; import { collectInlineContextIds } from "~/lib/composerContextReferences"; import { resolveDiffThemeName } from "~/lib/diffRendering"; import { cn, isMacPlatform } from "~/lib/utils"; @@ -156,6 +164,9 @@ export interface ComposerPromptEditorProps { cursor: number; richTextEnabled?: boolean; literalText?: boolean; + vimEnabled?: boolean; + /** The vim mode after each change, or null while vim mode is off. */ + onVimModeChange?: (mode: VimMode | null) => void; contextRecords: ComposerDraftContextRecords; buildContextClipboardFragment?: | ((contextIds: ReadonlyArray) => string | null) @@ -753,6 +764,8 @@ function replaceSkillChips( export function ComposerPromptEditorTiptap(props: ComposerPromptEditorProps) { const restoreFocusRef = useRef(false); + // Outlives the keyed editor so the mode and register survive switching drafts. + const vimStateRef = useRef(INITIAL_VIM_STATE); const { onChange: onPromptChange } = props; const [selection, setSelection] = useState<{ value: string; @@ -775,6 +788,7 @@ export function ComposerPromptEditorTiptap(props: ComposerPromptEditorProps) { key={`${props.draftKey ?? ""}:${props.literalText ? "literal" : props.richTextEnabled ? "rich" : "plain"}`} {...props} restoreFocusRef={restoreFocusRef} + vimStateRef={vimStateRef} initialExpandedCursor={ selection?.value === props.value && selection.cursor === props.cursor ? selection.expandedCursor @@ -831,6 +845,7 @@ function createComposerExtensions(richText: boolean) { ComposerCitationExtension, ComposerContextReferenceExtension, ComposerChipSelectionExtension, + ComposerVimExtension, ...(richText ? [ ComposerMarkdownSourceExtension, @@ -915,6 +930,7 @@ function ComposerPromptEditorTiptapInner( props: ComposerPromptEditorProps & { initialExpandedCursor: number; restoreFocusRef: RefObject; + vimStateRef: RefObject; }, ) { const { @@ -947,6 +963,9 @@ function ComposerPromptEditorTiptapInner( onPaste, editorRef, restoreFocusRef, + vimEnabled = false, + onVimModeChange, + vimStateRef, } = props; const richText = !literalText && (richTextEnabled ?? false); const clampEditorCursor = (text: string, position: number) => @@ -967,6 +986,8 @@ function ComposerPromptEditorTiptapInner( onCommandKeyDown, isPathQueryActive, importContextFragment, + vimEnabled, + onVimModeChange, })); const { environmentId } = use(ComposerContextActionsContext); @@ -1060,6 +1081,7 @@ function ComposerPromptEditorTiptapInner( const suppressTrigger = literalText || inCodeBlock || + composerVimMode(updated.state) === "normal" || [updated.state.selection.$from.nodeBefore, updated.state.selection.$from.nodeAfter].some( (node) => node?.isInline && node.isAtom && !node.isText && node.type.name !== "hardBreak", ); @@ -1072,6 +1094,33 @@ function ComposerPromptEditorTiptapInner( ); }; + const vimContext: ComposerVimContext = { + state: vimStateRef, + onModeChange: (mode) => readCallbacks().onVimModeChange?.(mode), + commandKey: (key, event) => readCallbacks().onCommandKeyDown?.(key, event) ?? false, + insertNewline: (view) => { + const dispatch = (tr: Transaction) => view.dispatch(tr.scrollIntoView()); + if (!selectionInOneCodeBlock(view.state) || !newlineInCode(view.state, dispatch)) { + insertComposerNewline(view, richText); + } + }, + insertMarkdown: (view, markdown) => { + const instance = (view.dom as TiptapEditorHTMLElement).editor; + if (!instance) return; + const nested = ["listItem", "taskItem", "blockquote"].some((name) => + hasAncestor(view.state.selection.$from, name), + ); + insertMarkdownParagraphs( + markdown, + skillLabelFor, + { styling: richText, blocks: !nested, literalText, isKnownModel }, + (content) => { + instance.chain().command(collapseShownMarkdownSource).insertContent(content).run(); + }, + ); + }, + }; + const editorAttributes = { class: cn( "composer-tiptap -m-1 block max-h-52 min-h-[calc(2lh+--spacing(2))] overflow-y-auto p-1 whitespace-pre-wrap wrap-break-word bg-transparent leading-relaxed text-foreground focus:outline-none", @@ -1110,6 +1159,9 @@ function ComposerPromptEditorTiptapInner( editorProps: { attributes: editorAttributes, handleKeyDown: (view, event) => { + if (readCallbacks().vimEnabled && handleComposerVimKeyDown(view, event, vimContext)) { + return true; + } // In a right-to-left line the start is on the right. const backArrow = caretLineDirection(view.state) === "rtl" ? "ArrowRight" : "ArrowLeft"; const boundary = event.metaKey @@ -1287,34 +1339,7 @@ function ComposerPromptEditorTiptapInner( return true; } event.preventDefault(); - if ( - (isTaskItem || isListItem) && - instance && - splitOrLiftListItem(instance, collapseShownMarkdownSource) - ) { - return true; - } - if ( - richText && - instance && - hasAncestor(view.state.selection.$from, "blockquote") && - view.state.selection.$from.parent.content.size === 0 && - instance.commands.lift("blockquote") - ) { - return true; - } - // Parse shown Markdown first, or the split leaves each half with one delimiter. - if (instance) { - return instance - .chain() - .command(collapseShownMarkdownSource) - .command(({ state, dispatch }) => splitBlockKeepMarks(state, dispatch)) - .scrollIntoView() - .run(); - } - return splitBlockKeepMarks(view.state, (tr) => { - view.dispatch(tr.scrollIntoView()); - }); + return insertComposerNewline(view, richText); } if (!handler) return false; const handled = handler(event.key, event); @@ -1325,6 +1350,7 @@ function ComposerPromptEditorTiptapInner( return handled; }, handleTextInput: (view, from, to, text) => { + if (composerVimMode(view.state) === "normal") return true; if (literalText || view.composing || text.length !== 1) return false; const closer = SURROUND_CLOSE[text]; const { selection } = view.state; @@ -1486,6 +1512,15 @@ function ComposerPromptEditorTiptapInner( editor?.setEditable(!disabled); }, [disabled, editor]); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- mirrors the vim setting into the editor's plugin state and reports the mode to the indicator + useLayoutEffect(() => { + if (!editor) return; + if (!vimEnabled) vimStateRef.current = INITIAL_VIM_STATE; + const mode = vimEnabled ? vimStateRef.current.mode : null; + showComposerVimMode(editor.view, mode); + readCallbacks().onVimModeChange?.(mode); + }, [editor, readCallbacks, vimEnabled, vimStateRef]); + // Push attributes before layout measurements; Tiptap updates them later in a passive effect. // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- pushes DOM attributes into the ProseMirror view before layout measurements read them useLayoutEffect(() => { @@ -1868,6 +1903,36 @@ function ComposerPromptEditorTiptapInner( ); } +/** Starts a new line at the selection, continuing or leaving a list or quote like Enter. */ +function insertComposerNewline(view: EditorView, richText: boolean): boolean { + const instance = (view.dom as TiptapEditorHTMLElement).editor; + const inList = richText && (instance?.isActive("taskItem") || instance?.isActive("listItem")); + if (inList && instance && splitOrLiftListItem(instance, collapseShownMarkdownSource)) { + return true; + } + if ( + richText && + instance && + hasAncestor(view.state.selection.$from, "blockquote") && + view.state.selection.$from.parent.content.size === 0 && + instance.commands.lift("blockquote") + ) { + return true; + } + // Parse shown Markdown first, or the split leaves each half with one delimiter. + if (instance) { + return instance + .chain() + .command(collapseShownMarkdownSource) + .command(({ state, dispatch }) => splitBlockKeepMarks(state, dispatch)) + .scrollIntoView() + .run(); + } + return splitBlockKeepMarks(view.state, (tr) => { + view.dispatch(tr.scrollIntoView()); + }); +} + /** Split newlines into paragraphs; trailing hard breaks render no visible line. */ function insertMarkdownParagraphs( value: string, diff --git a/apps/web/src/components/ComposerPromptEditorTiptap.vim.browser.test.tsx b/apps/web/src/components/ComposerPromptEditorTiptap.vim.browser.test.tsx new file mode 100644 index 0000000000000..66b0babaff85c --- /dev/null +++ b/apps/web/src/components/ComposerPromptEditorTiptap.vim.browser.test.tsx @@ -0,0 +1,114 @@ +import type { Editor } from "@tiptap/core"; +import { createRef, useState } from "react"; +import { describe, expect, it, vi } from "vite-plus/test"; +import { userEvent } from "vite-plus/test/browser"; + +import { render } from "../../test/render"; + +import { serializeEditorDoc } from "~/composer-rich-text-doc"; +import { + ComposerPromptEditorTiptap as ComposerPromptEditor, + type ComposerPromptEditorHandle, + type ComposerPromptEditorProps, +} from "./ComposerPromptEditorTiptap"; + +type VimProps = Pick; + +function VimComposer({ value, ...props }: VimProps & { value: string }) { + const [prompt, setPrompt] = useState({ value, cursor: value.length }); + return ( + ()} + value={prompt.value} + cursor={prompt.cursor} + richTextEnabled + vimEnabled + contextRecords={new Map()} + skills={[]} + disabled={false} + placeholder="" + onChange={(...args) => setPrompt({ value: args[0], cursor: args[1] })} + onPaste={() => {}} + {...props} + /> + ); +} + +async function mountVim(value: string, props: VimProps = {}) { + await using stack = new AsyncDisposableStack(); + const screen = stack.use(await render()); + const element = screen.container.querySelector(".tiptap"); + if (!element) throw new Error("Composer did not mount"); + const { editor } = element; + editor.view.focus(); + const environment = stack.move(); + return Object.assign(screen, { + [Symbol.asyncDispose]: () => environment.disposeAsync(), + editor, + text: () => serializeEditorDoc(editor.state.doc).value, + }); +} + +describe("composer vim mode", () => { + it("edits from normal mode and undoes one command at a time", async () => { + await using screen = await mountVim("foo bar baz"); + await userEvent.keyboard("{Escape}"); + expect(screen.editor.view.dom.dataset.vimMode).toBe("normal"); + await userEvent.keyboard("0dwxq"); + expect(screen.text()).toBe("ar baz"); + await userEvent.keyboard("u"); + expect(screen.text()).toBe("bar baz"); + await userEvent.keyboard("u"); + expect(screen.text()).toBe("foo bar baz"); + }); + + it("keeps chips when putting a yanked line", async () => { + await using screen = await mountVim("see @a.md now\nnext"); + await userEvent.keyboard("{Escape}ggyyp"); + expect(screen.text()).toBe("see @a.md now\nsee @a.md now\nnext"); + let chips = 0; + screen.editor.state.doc.descendants((node) => { + if (node.type.name === "composer-mention") chips += 1; + }); + expect(chips).toBe(2); + }); + + it("deletes, puts and joins lines across paragraphs", async () => { + await using screen = await mountVim("a\nb\nc"); + await userEvent.keyboard("{Escape}ggjdd"); + expect(screen.text()).toBe("a\nc"); + await userEvent.keyboard("P"); + expect(screen.text()).toBe("a\nb\nc"); + await userEvent.keyboard("ggJ"); + expect(screen.text()).toBe("a b\nc"); + await userEvent.keyboard("0cwx{Escape}w."); + expect(screen.text()).toBe("x x\nc"); + expect(screen.editor.view.dom.querySelector(".composer-vim-cursor")?.textContent).toBe("x"); + }); + + it("continues a list when opening a line below an item", async () => { + await using screen = await mountVim("- a\n- b"); + await userEvent.keyboard("{Escape}ggoc{Escape}"); + expect(screen.text()).toBe("- a\n- c\n- b"); + }); + + it("sends with Enter from normal mode without adding a line", async () => { + const onCommandKeyDown = vi.fn((key: string) => key === "Enter"); + await using screen = await mountVim("hello", { onCommandKeyDown }); + await userEvent.keyboard("{Escape}{Enter}"); + expect(onCommandKeyDown).toHaveBeenCalledWith("Enter", expect.anything()); + expect(screen.text()).toBe("hello"); + }); + + it("lets an open menu take Escape before leaving insert mode", async () => { + const onCommandKeyDown = vi.fn((key: string) => key === "Escape"); + const onVimModeChange = vi.fn(); + await using screen = await mountVim("@a", { onCommandKeyDown, onVimModeChange }); + await userEvent.keyboard("{Escape}"); + expect(onVimModeChange).not.toHaveBeenCalledWith("normal"); + onCommandKeyDown.mockReturnValue(false); + await userEvent.keyboard("{Escape}"); + expect(onVimModeChange).toHaveBeenLastCalledWith("normal"); + expect(screen.editor.view.dom.dataset.vimMode).toBe("normal"); + }); +}); diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index cba7c434b1bab..13222e968a256 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -106,6 +106,8 @@ import { useComposerThreadDraft, } from "../../composerDraftStore"; import { ComposerStashBadge } from "./ComposerStashBadge"; +import { Badge } from "../ui/badge"; +import type { VimMode } from "../../composer-vim"; import { ComposerStashMenu } from "./ComposerStashMenu"; import { useComposerTriggerState } from "./useComposerTriggerState"; import { useComposerMenuItems } from "./useComposerMenuItems"; @@ -988,6 +990,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const isMobileViewport = useMediaQuery("max-sm"); const isSoftwareKeyboardOpen = useSoftwareKeyboardOpen(); const [isComposerFocused, setIsComposerFocused] = useState(false); + const [vimMode, setVimMode] = useState(null); const [composerSubmissionError, setComposerSubmissionError] = useState(null); const [providerInputSubmissionError, setProviderInputSubmissionError] = useState( null, @@ -3459,6 +3462,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) } editorRef={composerEditorRef} richTextEnabled={settings.composerRichTextEnabled} + vimEnabled={settings.composerVimMode} + onVimModeChange={setVimMode} literalText={isLiteralPendingAnswer} isPathQueryActive={isPathQueryActiveStable} value={activePendingProgress ? activePendingProgress.customAnswer : prompt} @@ -3561,6 +3566,13 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) )} > {composerAttachButton ?
{composerAttachButton}
: null} + {vimMode ? ( +
+ + {vimMode === "normal" ? "NORMAL" : "INSERT"} + +
+ ) : null}
{ if (!event.repeat) branchToolbarRef.current?.usePreviousWorktree(); }, + "composer.toggleVimMode": ({ event }) => { + if (!event.repeat) toggleComposerVimMode(); + }, } satisfies ChatShortcutCommands; } diff --git a/apps/web/src/components/chat/composerVimMode.ts b/apps/web/src/components/chat/composerVimMode.ts new file mode 100644 index 0000000000000..9676a74548ac6 --- /dev/null +++ b/apps/web/src/components/chat/composerVimMode.ts @@ -0,0 +1,12 @@ +import { getClientSettings, updateClientSettings } from "../../hooks/useSettings"; +import { toastManager } from "../ui/toast"; + +export function toggleComposerVimMode(): void { + const enabled = !getClientSettings().composerVimMode; + void updateClientSettings({ composerVimMode: enabled }); + toastManager.add({ + id: "composer-vim-mode", + title: enabled ? "Vim mode on" : "Vim mode off", + timeout: 1500, + }); +} diff --git a/apps/web/src/components/settings/SettingsPanels.tsx b/apps/web/src/components/settings/SettingsPanels.tsx index a37bf1581990e..f34051b16885e 100644 --- a/apps/web/src/components/settings/SettingsPanels.tsx +++ b/apps/web/src/components/settings/SettingsPanels.tsx @@ -532,6 +532,7 @@ export function useSettingsRestore(onRestored?: () => void) { ...(settings.composerRichTextEnabled !== DEFAULT_UNIFIED_SETTINGS.composerRichTextEnabled ? ["Rich text composer"] : []), + ...(settings.composerVimMode !== DEFAULT_UNIFIED_SETTINGS.composerVimMode ? ["Vim mode"] : []), ...(settings.sendShortcut !== DEFAULT_UNIFIED_SETTINGS.sendShortcut ? ["Send shortcut"] : []), ...(settings.followUpBehavior !== DEFAULT_UNIFIED_SETTINGS.followUpBehavior ? ["Follow-up behavior"] @@ -651,6 +652,7 @@ export function useSettingsRestore(onRestored?: () => void) { proactivePanelsEnabled: DEFAULT_UNIFIED_SETTINGS.proactivePanelsEnabled, showSkillsInSlashMenu: DEFAULT_UNIFIED_SETTINGS.showSkillsInSlashMenu, composerRichTextEnabled: DEFAULT_UNIFIED_SETTINGS.composerRichTextEnabled, + composerVimMode: DEFAULT_UNIFIED_SETTINGS.composerVimMode, sendShortcut: DEFAULT_UNIFIED_SETTINGS.sendShortcut, followUpBehavior: DEFAULT_UNIFIED_SETTINGS.followUpBehavior, toolCallVisibility: DEFAULT_UNIFIED_SETTINGS.toolCallVisibility, @@ -1087,6 +1089,27 @@ export function ChatSettingsPanel() { /> } /> + + updateSettings({ composerVimMode: DEFAULT_UNIFIED_SETTINGS.composerVimMode }) + } + /> + ) : null + } + control={ + updateSettings({ composerVimMode: Boolean(checked) })} + aria-label="Vim mode" + /> + } + /> ("composer-vim"); +const CURSOR_CLASS = "composer-vim-cursor"; + +/** The vim mode the editor shows, or null when vim mode is off. */ +export function composerVimMode(state: EditorState): VimMode | null { + return vimPluginKey.getState(state) ?? null; +} + +export function showComposerVimMode(view: EditorView, mode: VimMode | null): void { + if (composerVimMode(view.state) !== mode) + view.dispatch(view.state.tr.setMeta(vimPluginKey, mode)); +} + +function emptyLineCursor(): HTMLElement { + const cursor = document.createElement("span"); + cursor.className = `${CURSOR_CLASS} composer-vim-cursor-empty`; + cursor.textContent = "\u00a0"; + return cursor; +} + +/** Normal mode covers the character after the caret, or a placeholder cell at a line end. */ +function blockCursor(state: EditorState): DecorationSet | null { + const { selection } = state; + if (!selection.empty) return null; + const { $head } = selection; + const next = $head.nodeAfter; + const decoration = + next?.isText && next.text?.[0] !== "\n" + ? Decoration.inline($head.pos, $head.pos + 1, { class: CURSOR_CLASS }) + : next?.isInline && !next.isText && next.type.name !== "hardBreak" + ? Decoration.node($head.pos, $head.pos + next.nodeSize, { class: CURSOR_CLASS }) + : Decoration.widget($head.pos, emptyLineCursor, { key: CURSOR_CLASS, side: 1 }); + return DecorationSet.create(state.doc, [decoration]); +} + +export const ComposerVimExtension = Extension.create({ + name: "composer-vim", + addProseMirrorPlugins() { + return [ + new Plugin({ + key: vimPluginKey, + state: { + init: () => null, + apply: (tr, mode) => { + const next = tr.getMeta(vimPluginKey) as VimMode | null | undefined; + return next === undefined ? mode : next; + }, + }, + props: { + attributes: (state): Record => { + const mode = vimPluginKey.getState(state); + return mode ? { "data-vim-mode": mode } : {}; + }, + decorations: (state) => + vimPluginKey.getState(state) === "normal" ? blockCursor(state) : null, + }, + }), + ]; + }, +}); + +// The engine's text: one character per document position, so offsets are flat offsets. +const flatTexts = new WeakMap(); + +function flatText(map: RichDocMap): string { + let text = flatTexts.get(map); + if (text === undefined) { + text = map.runs + .map((run) => { + if (run.kind === "token") return VIM_CHIP; + if (run.kind === "break") return "\n"; + if (run.kind === "prefix") return ""; + const start = run.mdStart + run.openLen; + return map.value.slice(start, start + run.docLen); + }) + .join(""); + flatTexts.set(map, text); + } + return text; +} + +export interface ComposerVimContext { + readonly state: { current: VimState }; + readonly onModeChange: (mode: VimMode) => void; + /** The composer's own Enter and Escape handling: sending, menus and suggestions. */ + readonly commandKey: (key: "Enter" | "Escape", event: KeyboardEvent) => boolean; + /** Starts a new line at the selection the way a non-sending Enter does. */ + readonly insertNewline: (view: EditorView) => void; + /** Inserts Markdown at the selection the way a paste does. */ + readonly insertMarkdown: (view: EditorView, markdown: string) => void; +} + +function consume(event: KeyboardEvent): void { + event.preventDefault(); + event.stopPropagation(); +} + +function engineKey(event: KeyboardEvent): string | null { + if (event.metaKey) return null; + if (event.ctrlKey) return !event.altKey && event.key.toLowerCase() === "r" ? "" : null; + if (event.key === "Backspace") return ""; + if (event.key === "Delete") return ""; + return event.key.length === 1 ? event.key : null; +} + +function selectFlat(view: EditorView, offset: number) { + const map = serializeEditorDoc(view.state.doc); + return view.state.tr.setSelection(Selection.near(view.state.doc.resolve(flatToPm(map, offset)))); +} + +function placeCursor(view: EditorView, offset: number, mode: VimMode): void { + const target = + mode === "normal" + ? clampNormalCursor(flatText(serializeEditorDoc(view.state.doc)), offset) + : offset; + const tr = selectFlat(view, target); + // Same transaction as the move, so change handlers already see the new mode. + if (composerVimMode(view.state) !== mode) tr.setMeta(vimPluginKey, mode); + view.dispatch(tr.scrollIntoView()); +} + +function applyOutcome(view: EditorView, outcome: VimOutcome, context: ComposerVimContext): void { + let state = outcome.state; + if (outcome.yank && state.register) { + const map = serializeEditorDoc(view.state.doc); + const source = serializeSelection( + view.state.doc, + flatToPm(map, outcome.yank.from), + flatToPm(map, outcome.yank.to), + ); + state = { ...state, register: { ...state.register, source } }; + } + context.state.current = state; + if (state.pending.length > 0) return; + if (outcome.history) { + (outcome.history === "undo" ? undo : redo)(view.state, (tr) => view.dispatch(tr)); + const map = serializeEditorDoc(view.state.doc); + placeCursor(view, pmToFlat(map, view.state.selection.head), "normal"); + return; + } + // Each command is its own undo step, even when typed within the grouping delay. + if (outcome.steps.length > 0) view.dispatch(closeHistory(view.state.tr)); + for (const step of outcome.steps) { + if (step.type === "replace") { + const map = serializeEditorDoc(view.state.doc); + const from = flatToPm(map, step.from); + const to = flatToPm(map, step.to); + view.dispatch( + step.text ? view.state.tr.insertText(step.text, from, to) : view.state.tr.delete(from, to), + ); + continue; + } + view.dispatch(selectFlat(view, step.at)); + if (step.type === "newline") { + context.insertNewline(view); + } else if (state.register) { + const { register } = state; + context.insertMarkdown( + view, + registerText(register, register.source ?? register.text, step.count), + ); + } + } + placeCursor(view, outcome.cursor, state.mode); + if (state.mode === "insert") context.onModeChange("insert"); +} + +/** Returns true when vim handled the key. Normal mode swallows every key that would type text. */ +export function handleComposerVimKeyDown( + view: EditorView, + event: KeyboardEvent, + context: ComposerVimContext, +): boolean { + if (event.isComposing || event.keyCode === 229 || event.target !== view.dom) return false; + const vim = context.state; + if (vim.current.mode === "insert") { + if ( + event.key !== "Escape" || + event.shiftKey || + event.altKey || + event.metaKey || + event.ctrlKey + ) { + return false; + } + consume(event); + // An open menu or suggestion closes first, like it does without vim. + if (context.commandKey("Escape", event)) return true; + const map = serializeEditorDoc(view.state.doc); + const next = vimEscape(vim.current, flatText(map), pmToFlat(map, view.state.selection.head)); + vim.current = next.state; + placeCursor(view, next.cursor, "normal"); + context.onModeChange("normal"); + return true; + } + if (event.key === "Escape") { + // Without a pending command, Escape keeps its usual meaning. + if (vim.current.pending.length === 0) return false; + vim.current = { ...vim.current, pending: [] }; + consume(event); + return true; + } + if (event.key === "Enter") { + vim.current = { ...vim.current, pending: [] }; + context.commandKey("Enter", event); + consume(event); + return true; + } + const key = engineKey(event); + if (key === null) return false; + consume(event); + const map = serializeEditorDoc(view.state.doc); + const outcome = vimNormalKey( + vim.current, + key, + flatText(map), + pmToFlat(map, view.state.selection.head), + ); + applyOutcome(view, outcome, context); + return true; +} diff --git a/apps/web/src/composer-vim.test.ts b/apps/web/src/composer-vim.test.ts new file mode 100644 index 0000000000000..c8ec24772185b --- /dev/null +++ b/apps/web/src/composer-vim.test.ts @@ -0,0 +1,202 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { + applyVimSteps, + INITIAL_VIM_STATE, + type VimState, + vimEscape, + vimNormalKey, +} from "./composer-vim"; + +/** Runs keys from normal mode on `start`, where `|` marks the cursor; insert mode types text. */ +function vim(start: string, keys: string, initial: Partial = {}) { + let text = start.replace("|", ""); + let cursor = start.indexOf("|"); + let state: VimState = { ...INITIAL_VIM_STATE, mode: "normal", ...initial }; + for (const key of keys.match(/<[^>]+>|[\s\S]/gu) ?? []) { + if (state.mode === "insert") { + if (key === "") { + ({ state, cursor } = vimEscape(state, text, cursor)); + continue; + } + const typed = key === "" ? "\n" : key; + text = text.slice(0, cursor) + typed + text.slice(cursor); + cursor += typed.length; + continue; + } + const outcome = vimNormalKey(state, key, text, cursor); + text = applyVimSteps(text, outcome.steps, outcome.state.register); + state = outcome.state; + cursor = outcome.cursor; + } + return `${text.slice(0, cursor)}|${text.slice(cursor)}`; +} + +describe("vim motions", () => { + it.each([ + ["|foo bar baz", "w", "foo |bar baz"], + ["|foo bar baz", "2w", "foo bar |baz"], + ["|foo.bar baz", "w", "foo|.bar baz"], + ["|foo.bar baz", "W", "foo.bar |baz"], + ["|foo\n\nbar", "w", "foo\n|\nbar"], + ["|a  b", "w", "a | b"], + ["|a  b", "ww", "a  |b"], + ["|a  b", "ww", "a | b"], + ["foo bar |baz", "b", "foo |bar baz"], + ["foo.bar |baz", "B", "|foo.bar baz"], + ["foo\n|bar", "b", "|foo\nbar"], + ["|foo bar", "e", "fo|o bar"], + ["fo|o bar", "e", "foo ba|r"], + ["|foo.bar", "E", "foo.ba|r"], + ["foo b|ar", "0", "|foo bar"], + [" fo|o", "^", " |foo"], + ["|foo bar", "$", "foo ba|r"], + ["a|b", "l", "a|b"], + ["a\n|b", "h", "a\n|b"], + ["|ab", " ", "a|b"], + ["a|b", "", "|ab"], + ["|abc\nde", "j", "abc\n|de"], + ["ab|c\nde", "j", "abc\nd|e"], + ["ab|c\nd\nxyz", "jj", "abc\nd\nxy|z"], + ["|ab\nwxyz", "$j", "ab\nwxy|z"], + ["ab\n|c", "k", "|ab\nc"], + ["|ab", "j", "|ab"], + ["a\nb\n|c", "gg", "|a\nb\nc"], + ["|a\n b\nc", "2G", "a\n |b\nc"], + ["|a\nb\nc", "G", "a\nb\n|c"], + ["|a-b-c", "f-", "a|-b-c"], + ["|a-b-c", "2f-", "a-b|-c"], + ["|a-b-c", "f-;", "a-b|-c"], + ["|a-b-c", "f-;,", "a|-b-c"], + ["|a-b-c", "t-;", "a-|b-c"], + ["a-b-|c", "F-", "a-b|-c"], + ["a-b-|c", "T-", "a-b-|c"], + ["|a\n-", "f-", "|a\n-"], + ])("%j %j -> %j", (start, keys, expected) => { + expect(vim(start, keys)).toBe(expected); + }); +}); + +describe("vim edits", () => { + it.each([ + ["|foo bar", "x", "|oo bar"], + ["fo|o", "x", "f|o"], + ["|foo", "3x", "|"], + ["foo |bar", "X", "foo|bar"], + ["|foo bar baz", "dw", "|bar baz"], + ["|foo bar baz", "d2w", "|baz"], + ["|foo bar baz", "2dw", "|baz"], + ["foo |bar\nbaz", "dw", "foo| \nbaz"], + ["foo |bar baz", "db", "|bar baz"], + ["| b", "dw", "| b"], + ["|foo bar", "de", "| bar"], + ["|foo bar", "cwxy", "x|y bar"], + ["foo |bar", "D", "foo| "], + ["foo |bar", "Cqux", "foo qu|x"], + ["|abc", "sx", "|xbc"], + ["a\n|b\nc", "dd", "a\n|c"], + ["a\nb\n|c", "dd", "a\n|b"], + ["|a\nb\nc", "2dd", "|c"], + [" a\n|b", "dd", " |a"], + ["a\n|b\nc", "dj", "|a"], + ["a\n|b\nc", "ccx", "a\n|x\nc"], + ["a\n|b\nc", "Sx", "a\n|x\nc"], + ["a b|c d", "f d0", "| d"], + ["a\n|b\nc", "yyp", "a\nb\n|b\nc"], + ["a\n|b\nc", "yyP", "a\n|b\nb\nc"], + ["a\n|b", "Yp", "a\nb\n|b"], + ["|a", "ddp", "\n|a"], + ["|ab", "ylp", "a|ab"], + ["|ab", "yl2p", "aa|ab"], + ["|ab", "xp", "b|a"], + ["|foo bar", "dwP", "foo| bar"], + ["|foo bar", "yiwP", "fo|ofoo bar"], + ["a|b\ncd", "J", "ab| cd"], + ["a\n b", "J", "a| b"], + ["a \nb", "J", "a |b"], + ["|a\nb\nc", "3J", "a b| c"], + ["|abc", "rx", "|xbc"], + ["|abc", "2rx", "x|xc"], + ["|abc", "5rx", "|abc"], + ["|ab", "ix", "|xab"], + ["|ab", "ax", "a|xb"], + [" a|b", "Ix", " |xab"], + ["|ab", "Ax", "ab|x"], + ["|a\nb", "ox", "a\n|x\nb"], + ["a\n|b", "Ox", "a\n|x\nb"], + ])("%j %j -> %j", (start, keys, expected) => { + expect(vim(start, keys)).toBe(expected); + }); +}); + +describe("vim text objects", () => { + it.each([ + ["foo |bar baz", "diw", "foo | baz"], + ["foo |bar baz", "daw", "foo |baz"], + ["foo |baz", "daw", "fo|o"], + ["foo.b|ar baz", "diW", "| baz"], + ["a | b", "diw", "a | b"], + ['say "hi |there" ok', 'di"', 'say "|" ok'], + ['say "hi |there" ok', 'da"', "say |ok"], + ['|say "hi"', 'ci"x', 'say "|x"'], + ["it's 'a|b'", "di'", "it's 'a|b'"], + ["x 'a|b' y", "di'", "x '|' y"], + ["foo(|a, (b))", "di(", "foo(|)"], + ["foo(a, (|b))", "di(", "foo(a, (|))"], + ["foo(a, (b)|)", "dib", "foo(|)"], + ["foo(|a)", "da(", "fo|o"], + ["foo(|a)", "ci)x", "foo(|x)"], + ["[a, |b]", "di[", "[|]"], + ["{\n |a\n}", "di{", "{\n|\n}"], + ["{|a}", "daB", "|"], + ["|none", "di(", "|none"], + ])("%j %j -> %j", (start, keys, expected) => { + expect(vim(start, keys)).toBe(expected); + }); +}); + +describe("vim repeat", () => { + it.each([ + ["|a b c", "dw.", "|c"], + ["|abcdef", "2x.", "|ef"], + ["|foo foo", "cwbarw.", "bar ba|r"], + ["|a\nb", "ocj.", "a\nc\nb\n|c"], + ["|a\nb", "Axyj.", "ax\ny\nbx\n|y"], + ["|abc", ".", "|abc"], + ["|ab cd", "yw.", "|ab cd"], + ])("%j %j -> %j", (start, keys, expected) => { + expect(vim(start, keys)).toBe(expected); + }); +}); + +describe("vim state", () => { + it("waits for the rest of a command", () => { + const outcome = vimNormalKey({ ...INITIAL_VIM_STATE, mode: "normal" }, "d", "abc", 0); + expect(outcome.state.pending).toEqual(["d"]); + expect(outcome.steps).toEqual([]); + }); + + it("reports the yanked range so the editor can keep its Markdown", () => { + const outcome = vimNormalKey( + { ...INITIAL_VIM_STATE, mode: "normal", pending: ["d"] }, + "d", + "a\n b\nc", + 2, + ); + expect(outcome.yank).toEqual({ from: 2, to: 5 }); + expect(outcome.state.register).toEqual({ text: " b", linewise: true }); + }); + + it("steps back onto the last typed character when leaving insert mode", () => { + expect(vimEscape(INITIAL_VIM_STATE, "ab\ncd", 3)).toMatchObject({ + state: { mode: "normal" }, + cursor: 3, + }); + expect(vimEscape(INITIAL_VIM_STATE, "ab", 2).cursor).toBe(1); + }); + + it("swallows unknown keys", () => { + const outcome = vimNormalKey({ ...INITIAL_VIM_STATE, mode: "normal" }, "Q", "abc", 1); + expect(outcome).toMatchObject({ steps: [], cursor: 1, state: { pending: [] } }); + }); +}); diff --git a/apps/web/src/composer-vim.ts b/apps/web/src/composer-vim.ts new file mode 100644 index 0000000000000..fd12b09e2bc5c --- /dev/null +++ b/apps/web/src/composer-vim.ts @@ -0,0 +1,881 @@ +/** + * Vim keys for the composer over plain text: lines end with "\n" and a chip is + * one character. Pure; the editor applies the returned steps to its document. + */ + +export type VimMode = "insert" | "normal"; + +export const VIM_CHIP = "\uFFFC"; + +type Operator = "d" | "c" | "y"; +type FindKind = "f" | "F" | "t" | "T"; + +export interface VimRegister { + readonly text: string; + readonly linewise: boolean; + /** Markdown for `text`, so a put restores chips and formatting. */ + readonly source?: string; +} + +export interface VimState { + readonly mode: VimMode; + readonly pending: ReadonlyArray; + readonly register: VimRegister | null; + readonly lastFind: { readonly kind: FindKind; readonly char: string } | null; + readonly lastChange: { readonly keys: ReadonlyArray; readonly inserted: string } | null; + /** The command that entered insert mode and the text it left, completed into `lastChange` on Escape. */ + readonly insert: { readonly keys: ReadonlyArray; readonly baseline: string } | null; + /** Column kept across `j` and `k`; Infinity after `$`. */ + readonly column: number | null; +} + +export const INITIAL_VIM_STATE: VimState = { + mode: "insert", + pending: [], + register: null, + lastFind: null, + lastChange: null, + insert: null, + column: null, +}; + +/** Offsets refer to the text left by the previous step. Replace text never contains "\n". */ +export type VimStep = + | { readonly type: "replace"; readonly from: number; readonly to: number; readonly text: string } + | { readonly type: "newline"; readonly at: number } + | { readonly type: "put"; readonly at: number; readonly count: number }; + +export interface VimOutcome { + readonly state: VimState; + readonly steps: ReadonlyArray; + /** Cursor in the text after the steps. */ + readonly cursor: number; + /** Range of the text before the steps that the register now holds. */ + readonly yank?: { readonly from: number; readonly to: number }; + readonly history?: "undo" | "redo"; +} + +type Motion = { readonly key: string; readonly char?: string }; +type Target = Motion | { readonly object: string } | "line"; +type Command = + | { + readonly kind: "motion"; + readonly motion: Motion; + readonly count: number; + readonly counted: boolean; + } + | { + readonly kind: "operator"; + readonly op: Operator; + readonly target: Target; + readonly count: number; + readonly counted: boolean; + } + | { + readonly kind: "action"; + readonly key: string; + readonly char?: string; + readonly count: number; + }; + +const MOTION_KEYS = new Set([ + "h", + "j", + "k", + "l", + "w", + "W", + "b", + "B", + "e", + "E", + "0", + "^", + "$", + "G", + ";", + ",", +]); +const MOTION_ALIASES: Record = { " ": "l", "": "h" }; +const FIND_KEYS = new Set(["f", "F", "t", "T"]); +const OBJECT_KEYS: Record = { + w: "w", + W: "W", + '"': '"', + "'": "'", + "`": "`", + "(": "(", + ")": "(", + b: "(", + "[": "[", + "]": "[", + "{": "{", + "}": "{", + B: "{", +}; +// Shorthands for an operator and a target. +const SHORTHANDS: Record = { + x: { op: "d", target: { key: "l" } }, + "": { op: "d", target: { key: "l" } }, + X: { op: "d", target: { key: "h" } }, + s: { op: "c", target: { key: "l" } }, + S: { op: "c", target: "line" }, + D: { op: "d", target: { key: "$" } }, + C: { op: "c", target: { key: "$" } }, + Y: { op: "y", target: "line" }, +}; +const ACTION_KEYS = new Set(["i", "a", "I", "A", "o", "O", "p", "P", "J", "u", "", "."]); + +function isSingleChar(key: string | undefined): key is string { + return key !== undefined && key.length === 1; +} + +function parseCommand(keys: ReadonlyArray): Command | "incomplete" | "invalid" { + let index = 0; + const readCount = () => { + let digits = ""; + while (index < keys.length && /^[0-9]$/.test(keys[index]!) && (digits || keys[index] !== "0")) { + digits += keys[index++]; + } + return digits ? Number(digits) : null; + }; + // A motion, or "incomplete" while it waits for its character. + const readMotion = (): Motion | "incomplete" | "invalid" => { + if (index >= keys.length) return "incomplete"; + const raw = keys[index++]!; + const key = MOTION_ALIASES[raw] ?? raw; + if (MOTION_KEYS.has(key)) return { key }; + if (FIND_KEYS.has(key)) { + if (index >= keys.length) return "incomplete"; + const char = keys[index++]; + return isSingleChar(char) ? { key, char } : "invalid"; + } + if (key === "g") { + if (index >= keys.length) return "incomplete"; + return keys[index++] === "g" ? { key: "gg" } : "invalid"; + } + return "invalid"; + }; + + const firstCount = readCount(); + if (index >= keys.length) return "incomplete"; + const key = keys[index]!; + const shorthand = SHORTHANDS[key]; + if (shorthand) { + return { + kind: "operator", + ...shorthand, + count: firstCount ?? 1, + counted: firstCount !== null, + }; + } + if (key === "d" || key === "c" || key === "y") { + index += 1; + const secondCount = readCount(); + const count = (firstCount ?? 1) * (secondCount ?? 1); + const counted = firstCount !== null || secondCount !== null; + if (index >= keys.length) return "incomplete"; + const next = keys[index]!; + if (next === key) return { kind: "operator", op: key, target: "line", count, counted }; + if (next === "i" || next === "a") { + index += 1; + if (index >= keys.length) return "incomplete"; + const object = OBJECT_KEYS[keys[index]!]; + return object + ? { kind: "operator", op: key, target: { object: next + object }, count, counted } + : "invalid"; + } + const motion = readMotion(); + if (typeof motion === "string") return motion; + return { kind: "operator", op: key, target: motion, count, counted }; + } + if (key === "r") { + if (index + 1 >= keys.length) return "incomplete"; + const char = keys[index + 1]; + return isSingleChar(char) ? { kind: "action", key, char, count: firstCount ?? 1 } : "invalid"; + } + if (ACTION_KEYS.has(key)) return { kind: "action", key, count: firstCount ?? 1 }; + const motion = readMotion(); + if (typeof motion === "string") return motion; + return { kind: "motion", motion, count: firstCount ?? 1, counted: firstCount !== null }; +} + +function lineStart(text: string, position: number): number { + return position <= 0 ? 0 : text.lastIndexOf("\n", position - 1) + 1; +} + +function lineEnd(text: string, position: number): number { + const end = text.indexOf("\n", position); + return end === -1 ? text.length : end; +} + +function isBlank(char: string | undefined): boolean { + return char !== undefined && /\s/.test(char); +} + +function firstNonBlank(text: string, position: number): number { + const end = lineEnd(text, position); + let index = lineStart(text, position); + while (index < end && isBlank(text[index])) index += 1; + return index; +} + +/** Normal mode rests on a character, never after the last one in a line. */ +export function clampNormalCursor(text: string, position: number): number { + const bounded = Math.max(0, Math.min(position, text.length)); + const start = lineStart(text, bounded); + const end = lineEnd(text, bounded); + return end > start && bounded >= end ? end - 1 : bounded; +} + +/** 0 blank, 1 word, 2 punctuation, 3 chip. A WORD is any run of non-blanks. */ +function charClass(char: string | undefined, big: boolean): number { + if (char === undefined || isBlank(char)) return 0; + if (big) return 1; + if (char === VIM_CHIP) return 3; + return /[\p{L}\p{N}_]/u.test(char) ? 1 : 2; +} + +/** Whether `char` continues a run of `kind`; every chip is a word of its own. */ +function joins(kind: number, char: string | undefined, big: boolean): boolean { + return kind !== 3 && charClass(char, big) === kind; +} + +function nextWordStart(text: string, position: number, big: boolean): number { + let index = position; + const kind = charClass(text[index], big); + if (kind !== 0) { + index += 1; + while (index < text.length && joins(kind, text[index], big)) index += 1; + } + while (index < text.length && isBlank(text[index])) { + index += 1; + // An empty line counts as a word. + if (text[index] === "\n" && text[index - 1] === "\n") return index; + } + return index; +} + +function previousWordStart(text: string, position: number, big: boolean): number { + if (position <= 0) return 0; + let index = position - 1; + while (index > 0 && isBlank(text[index])) { + if (text[index] === "\n" && text[index - 1] === "\n") return index; + index -= 1; + } + const kind = charClass(text[index], big); + if (kind !== 0) while (index > 0 && joins(kind, text[index - 1], big)) index -= 1; + return index; +} + +function wordEnd(text: string, position: number, big: boolean): number { + let index = position + 1; + while (index < text.length && isBlank(text[index])) index += 1; + if (index >= text.length) return Math.max(position, text.length - 1); + const kind = charClass(text[index], big); + while (index + 1 < text.length && joins(kind, text[index + 1], big)) index += 1; + return index; +} + +function findInLine( + text: string, + cursor: number, + kind: FindKind, + char: string, + count: number, + repeat: boolean, +): number | null { + if (kind === "f" || kind === "t") { + const end = lineEnd(text, cursor); + // Repeating `t` from just before a match would find that match again. + let index = cursor + (kind === "t" && repeat ? 1 : 0); + for (let step = 0; step < count; step += 1) { + index = text.indexOf(char, index + 1); + if (index === -1 || index >= end) return null; + } + return kind === "f" ? index : index - 1; + } + const start = lineStart(text, cursor); + let index = cursor - (kind === "T" && repeat ? 1 : 0); + for (let step = 0; step < count; step += 1) { + if (index - 1 < start) return null; + index = text.lastIndexOf(char, index - 1); + if (index < start) return null; + } + return kind === "F" ? index : index + 1; +} + +const REVERSED_FIND: Record = { f: "F", F: "f", t: "T", T: "t" }; + +type MotionResult = { + position: number; + type: "exclusive" | "inclusive" | "linewise"; + column?: number; + lastFind?: VimState["lastFind"]; +}; + +function lineIndexStart(text: string, line: number): number { + let start = 0; + for (let index = 0; index < line; index += 1) { + const end = text.indexOf("\n", start); + if (end === -1) return start; + start = end + 1; + } + return start; +} + +function motionTarget( + state: VimState, + text: string, + cursor: number, + motion: Motion, + count: number, + counted: boolean, +): MotionResult | null { + const start = lineStart(text, cursor); + const end = lineEnd(text, cursor); + const repeatWord = (step: (position: number) => number) => { + let position = cursor; + for (let index = 0; index < count; index += 1) position = step(position); + return position; + }; + switch (motion.key) { + case "h": + return { position: Math.max(start, cursor - count), type: "exclusive" }; + case "l": + return { position: Math.min(end, cursor + count), type: "exclusive" }; + case "0": + return { position: start, type: "exclusive" }; + case "^": + return { position: firstNonBlank(text, cursor), type: "exclusive" }; + case "$": { + let lineEndPosition = end; + for (let index = 1; index < count && lineEndPosition < text.length; index += 1) { + lineEndPosition = lineEnd(text, lineEndPosition + 1); + } + return { position: lineEndPosition, type: "exclusive", column: Infinity }; + } + case "w": + case "W": + return { + position: repeatWord((position) => nextWordStart(text, position, motion.key === "W")), + type: "exclusive", + }; + case "b": + case "B": + return { + position: repeatWord((position) => previousWordStart(text, position, motion.key === "B")), + type: "exclusive", + }; + case "e": + case "E": + return { + position: repeatWord((position) => wordEnd(text, position, motion.key === "E")), + type: "inclusive", + }; + case "j": + case "k": { + const column = state.column ?? cursor - start; + let targetStart = start; + let moved = 0; + for (; moved < count; moved += 1) { + if (motion.key === "j") { + const targetEnd = lineEnd(text, targetStart); + if (targetEnd >= text.length) break; + targetStart = targetEnd + 1; + } else { + if (targetStart === 0) break; + targetStart = lineStart(text, targetStart - 1); + } + } + if (moved === 0) return null; + const targetEnd = lineEnd(text, targetStart); + return { + position: Math.min(targetStart + column, Math.max(targetStart, targetEnd - 1)), + type: "linewise", + column, + }; + } + case "G": + case "gg": { + const lines = text.split("\n").length; + const line = counted ? Math.min(count, lines) - 1 : motion.key === "G" ? lines - 1 : 0; + return { position: firstNonBlank(text, lineIndexStart(text, line)), type: "linewise" }; + } + case ";": + case ",": { + const last = state.lastFind; + if (!last) return null; + const kind = motion.key === ";" ? last.kind : REVERSED_FIND[last.kind]; + const position = findInLine(text, cursor, kind, last.char, count, true); + if (position === null) return null; + return { position, type: kind === "f" || kind === "t" ? "inclusive" : "exclusive" }; + } + default: { + const kind = motion.key as FindKind; + const char = motion.char!; + const position = findInLine(text, cursor, kind, char, count, false); + if (position === null) return null; + return { + position, + type: kind === "f" || kind === "t" ? "inclusive" : "exclusive", + lastFind: { kind, char }, + }; + } + } +} + +function wordObject(text: string, cursor: number, around: boolean, big: boolean) { + const start = lineStart(text, cursor); + const end = lineEnd(text, cursor); + if (start === end) return null; + const position = Math.min(cursor, end - 1); + const kind = charClass(text[position], big); + let from = position; + let to = position + 1; + while (from > start && joins(kind, text[from - 1], big)) from -= 1; + while (to < end && joins(kind, text[to], big)) to += 1; + if (!around) return { from, to }; + if (kind === 0) { + const next = charClass(text[to], big); + if (to < end && next !== 0) { + to += 1; + while (to < end && joins(next, text[to], big)) to += 1; + } + } else if (to < end && isBlank(text[to])) { + while (to < end && isBlank(text[to])) to += 1; + } else { + while (from > start && isBlank(text[from - 1])) from -= 1; + } + return { from, to }; +} + +function quoteObject(text: string, cursor: number, quote: string, around: boolean) { + const start = lineStart(text, cursor); + const end = lineEnd(text, cursor); + const quotes: number[] = []; + for (let index = start; index < end; index += 1) { + if (text[index] === quote && text[index - 1] !== "\\") quotes.push(index); + } + // Quotes pair up from the start of the line. + for (let index = 0; index + 1 < quotes.length; index += 2) { + const open = quotes[index]!; + const close = quotes[index + 1]!; + if (cursor > close) continue; + if (!around) return { from: open + 1, to: close }; + let from = open; + let to = close + 1; + if (to < end && isBlank(text[to])) { + while (to < end && isBlank(text[to])) to += 1; + } else { + while (from > start && isBlank(text[from - 1])) from -= 1; + } + return { from, to }; + } + return null; +} + +const BRACKET_CLOSE: Record = { "(": ")", "[": "]", "{": "}" }; + +function bracketObject(text: string, cursor: number, open: string, around: boolean) { + const close = BRACKET_CLOSE[open]!; + let from = -1; + let depth = 0; + for (let index = text[cursor] === close ? cursor - 1 : cursor; index >= 0; index -= 1) { + const char = text[index]; + if (char === close) depth += 1; + else if (char === open) { + if (depth === 0) { + from = index; + break; + } + depth -= 1; + } + } + if (from === -1) return null; + let to = -1; + depth = 0; + for (let index = from + 1; index < text.length; index += 1) { + const char = text[index]; + if (char === open) depth += 1; + else if (char === close) { + if (depth === 0) { + to = index; + break; + } + depth -= 1; + } + } + if (to === -1) return null; + if (around) return { from, to: to + 1 }; + let innerFrom = from + 1; + let innerTo = to; + // A block that opens and closes on its own lines keeps those lines. + if (text[innerFrom] === "\n") innerFrom += 1; + const lastBreak = text.lastIndexOf("\n", innerTo - 1); + if (lastBreak >= innerFrom && /^\s*$/.test(text.slice(lastBreak, innerTo))) innerTo = lastBreak; + return { from: innerFrom, to: Math.max(innerFrom, innerTo) }; +} + +function textObject(text: string, cursor: number, object: string) { + const around = object[0] === "a"; + const kind = object.slice(1); + if (kind === "w" || kind === "W") return wordObject(text, cursor, around, kind === "W"); + if (kind === '"' || kind === "'" || kind === "`") return quoteObject(text, cursor, kind, around); + return bracketObject(text, cursor, kind, around); +} + +/** End (inclusive) of `cw`, which changes to the end of the word under the cursor. */ +function changeWordEnd(text: string, cursor: number, count: number, big: boolean): number { + const kind = charClass(text[cursor], big); + let end = cursor; + while (end + 1 < text.length && joins(kind, text[end + 1], big)) end += 1; + for (let index = 1; index < count; index += 1) end = wordEnd(text, end, big); + return end; +} + +export function registerText(register: Pick, text: string, count: number) { + return Array.from({ length: count }, () => text).join(register.linewise ? "\n" : ""); +} + +export function applyVimSteps( + text: string, + steps: ReadonlyArray, + register: VimRegister | null, +): string { + let next = text; + for (const step of steps) { + if (step.type === "replace") { + next = next.slice(0, step.from) + step.text + next.slice(step.to); + } else if (step.type === "newline") { + next = `${next.slice(0, step.at)}\n${next.slice(step.at)}`; + } else if (register) { + next = + next.slice(0, step.at) + + registerText(register, register.text, step.count) + + next.slice(step.at); + } + } + return next; +} + +/** The text typed into `baseline` to produce `text`, or null when it was not a plain insertion. */ +function insertedText(baseline: string, text: string): string | null { + const shortest = Math.min(baseline.length, text.length); + let prefix = 0; + while (prefix < shortest && baseline[prefix] === text[prefix]) prefix += 1; + let suffix = 0; + while ( + suffix < shortest - prefix && + baseline[baseline.length - 1 - suffix] === text[text.length - 1 - suffix] + ) { + suffix += 1; + } + if (prefix + suffix !== baseline.length) return null; + const inserted = text.slice(prefix, text.length - suffix); + return inserted.includes(VIM_CHIP) ? null : inserted; +} + +/** Steps that type `text` at `at`, splitting lines the way Enter would. */ +function typingSteps(at: number, text: string): VimStep[] { + const steps: VimStep[] = []; + let position = at; + text.split("\n").forEach((line, index) => { + if (index > 0) { + steps.push({ type: "newline", at: position }); + position += 1; + } + if (line) steps.push({ type: "replace", from: position, to: position, text: line }); + position += line.length; + }); + return steps; +} + +function escapeCursor(text: string, cursor: number): number { + return Math.max(lineStart(text, cursor), cursor - 1); +} + +/** Leaves insert mode: the cursor steps back onto the last typed character. */ +export function vimEscape( + state: VimState, + text: string, + cursor: number, +): { state: VimState; cursor: number } { + const lastChange = state.insert + ? { keys: state.insert.keys, inserted: insertedText(state.insert.baseline, text) ?? "" } + : state.lastChange; + return { + state: { ...state, mode: "normal", pending: [], insert: null, column: null, lastChange }, + cursor: escapeCursor(text, cursor), + }; +} + +function operate( + state: VimState, + keys: ReadonlyArray, + text: string, + cursor: number, + op: Operator, + target: Target, + count: number, + counted: boolean, +): VimOutcome | null { + let from: number; + let to: number; + let linewise = false; + let lastFind = state.lastFind; + if (target === "line") { + from = lineStart(text, cursor); + to = lineEnd(text, cursor); + for (let index = 1; index < count && to < text.length; index += 1) to = lineEnd(text, to + 1); + linewise = true; + } else if ("object" in target) { + const range = textObject(text, cursor, target.object); + if (!range) return null; + ({ from, to } = range); + } else if ( + op === "c" && + (target.key === "w" || target.key === "W") && + !isBlank(text[cursor]) && + cursor < text.length + ) { + from = cursor; + to = changeWordEnd(text, cursor, count, target.key === "W") + 1; + } else { + const motion = motionTarget(state, text, cursor, target, count, counted); + if (!motion) return null; + lastFind = motion.lastFind ?? lastFind; + from = Math.min(cursor, motion.position); + to = Math.max(cursor, motion.position); + if (motion.type === "linewise") { + from = lineStart(text, from); + to = lineEnd(text, to); + linewise = true; + } else if (motion.type === "inclusive") { + to = Math.min(text.length, to + 1); + } else if (target.key === "w" || target.key === "W") { + // A word motion that crosses into the next line stops at the end of this one. + const lastBreak = text.lastIndexOf("\n", to - 1); + if (lastBreak >= from) to = lastBreak; + } + } + + if (from === to && !linewise && op !== "c") return null; + const register: VimRegister = { text: text.slice(from, to), linewise }; + const yank = { from, to }; + const base: VimState = { ...state, register, lastFind, column: null }; + if (op === "y") { + const position = linewise && lineStart(text, cursor) === from ? cursor : from; + return { state: base, steps: [], cursor: clampNormalCursor(text, position), yank }; + } + if (op === "c") { + const steps: VimStep[] = from === to ? [] : [{ type: "replace", from, to, text: "" }]; + return { + state: { + ...base, + mode: "insert", + insert: { keys, baseline: applyVimSteps(text, steps, register) }, + }, + steps, + cursor: from, + yank, + }; + } + let deleteFrom = from; + let deleteTo = to; + if (linewise) { + if (to < text.length) deleteTo = to + 1; + else if (from > 0) deleteFrom = from - 1; + } + const steps: VimStep[] = [{ type: "replace", from: deleteFrom, to: deleteTo, text: "" }]; + const next = applyVimSteps(text, steps, register); + return { + state: { ...base, lastChange: { keys, inserted: "" } }, + steps, + cursor: linewise + ? firstNonBlank(next, Math.min(deleteFrom, next.length)) + : clampNormalCursor(next, from), + yank, + }; +} + +function act( + state: VimState, + keys: ReadonlyArray, + text: string, + cursor: number, + key: string, + count: number, + char: string | undefined, +): VimOutcome | null { + const start = lineStart(text, cursor); + const end = lineEnd(text, cursor); + const enterInsert = (position: number, steps: VimStep[] = []): VimOutcome => ({ + state: { + ...state, + mode: "insert", + column: null, + insert: { keys, baseline: applyVimSteps(text, steps, state.register) }, + }, + steps, + cursor: position, + }); + const change = (steps: VimStep[], position: number): VimOutcome => ({ + state: { ...state, column: null, lastChange: { keys, inserted: "" } }, + steps, + cursor: clampNormalCursor(applyVimSteps(text, steps, state.register), position), + }); + switch (key) { + case "i": + return enterInsert(cursor); + case "a": + return enterInsert(Math.min(cursor + 1, end)); + case "I": + return enterInsert(firstNonBlank(text, cursor)); + case "A": + return enterInsert(end); + case "o": + return enterInsert(end + 1, [{ type: "newline", at: end }]); + case "O": + return enterInsert(start, [{ type: "newline", at: start }]); + case "u": + return { state, steps: [], cursor, history: "undo" }; + case "": + return { state, steps: [], cursor, history: "redo" }; + case "p": + case "P": { + const register = state.register; + if (!register) return null; + if (register.linewise) { + const at = key === "p" ? end : start; + const lineAt = key === "p" ? end + 1 : start; + const steps: VimStep[] = [ + { type: "newline", at }, + { type: "put", at: lineAt, count }, + ]; + return change(steps, firstNonBlank(applyVimSteps(text, steps, register), lineAt)); + } + const at = key === "p" ? Math.min(cursor + 1, end) : cursor; + return change([{ type: "put", at, count }], at + register.text.length * count - 1); + } + case "J": { + let next = text; + let position = cursor; + const steps: VimStep[] = []; + for (let join = 0; join < Math.max(1, count - 1); join += 1) { + const joinAt = lineEnd(next, position); + if (joinAt >= next.length) break; + let contentStart = joinAt + 1; + while ( + contentStart < next.length && + next[contentStart] !== "\n" && + isBlank(next[contentStart]) + ) { + contentStart += 1; + } + const separator = + joinAt === lineStart(next, joinAt) || + isBlank(next[joinAt - 1]) || + contentStart >= next.length || + next[contentStart] === "\n" || + next[contentStart] === ")" + ? "" + : " "; + const step: VimStep = { type: "replace", from: joinAt, to: contentStart, text: separator }; + steps.push(step); + next = applyVimSteps(next, [step], null); + position = joinAt; + } + if (steps.length === 0) return null; + return change(steps, position); + } + case "r": { + if (cursor + count > end || !char) return null; + return change( + [{ type: "replace", from: cursor, to: cursor + count, text: char.repeat(count) }], + cursor + count - 1, + ); + } + case ".": { + const last = state.lastChange; + if (!last) return null; + const replay = run({ ...state, pending: [] }, last.keys, text, cursor); + if (!replay) return null; + if (replay.state.mode !== "insert") + return { ...replay, state: { ...replay.state, lastChange: last } }; + const steps = [...replay.steps]; + const typed = typingSteps(replay.cursor, last.inserted); + const previous = steps.at(-1); + const first = typed[0]; + // Merge the deletion and the typing so one undo reverts the repeat. + if ( + previous?.type === "replace" && + first?.type === "replace" && + previous.from + previous.text.length === first.from + ) { + steps[steps.length - 1] = { ...previous, text: previous.text + first.text }; + typed.shift(); + } + steps.push(...typed); + const next = applyVimSteps(text, steps, replay.state.register); + return { + ...replay, + state: { ...replay.state, mode: "normal", insert: null, lastChange: last }, + steps, + cursor: escapeCursor(next, replay.cursor + last.inserted.length), + }; + } + default: + return null; + } +} + +function run( + state: VimState, + keys: ReadonlyArray, + text: string, + cursor: number, +): VimOutcome | null { + const command = parseCommand(keys); + if (typeof command === "string") return null; + if (command.kind === "operator") { + return operate( + state, + keys, + text, + cursor, + command.op, + command.target, + command.count, + command.counted, + ); + } + if (command.kind === "action") { + return act(state, keys, text, cursor, command.key, command.count, command.char); + } + const motion = motionTarget(state, text, cursor, command.motion, command.count, command.counted); + if (!motion) return null; + return { + state: { ...state, column: motion.column ?? null, lastFind: motion.lastFind ?? state.lastFind }, + steps: [], + cursor: clampNormalCursor(text, motion.position), + }; +} + +/** + * Handles one key in normal mode. `key` is a single character, or ``, `` or ``. + * Unknown or failed commands are swallowed without changes, like Vim's beep. + */ +export function vimNormalKey( + state: VimState, + key: string, + text: string, + cursor: number, +): VimOutcome { + const keys = [...state.pending, key]; + const parsed = parseCommand(keys); + if (parsed === "incomplete") return { state: { ...state, pending: keys }, steps: [], cursor }; + const idle = { ...state, pending: [] }; + if (parsed === "invalid") return { state: idle, steps: [], cursor }; + return run(idle, keys, text, cursor) ?? { state: idle, steps: [], cursor }; +} diff --git a/apps/web/src/index.css b/apps/web/src/index.css index b24265d02197e..9e866511284ad 100644 --- a/apps/web/src/index.css +++ b/apps/web/src/index.css @@ -1875,6 +1875,25 @@ code { margin-bottom: 0; } +/* Vim normal mode draws a block over the character under the hidden caret. */ +.composer-tiptap[data-vim-mode="normal"] { + caret-color: transparent; +} + +.composer-tiptap[data-vim-mode="normal"]:focus .composer-vim-cursor { + background-color: var(--color-foreground); + color: var(--color-background); +} + +.composer-vim-cursor-empty { + display: inline-block; + min-width: 1ch; +} + +.composer-tiptap:not(:focus) .composer-vim-cursor-empty { + display: none; +} + .chat-markdown p, .chat-markdown ul, .chat-markdown ol, diff --git a/docs/user/composer.md b/docs/user/composer.md index df880e49c6ca5..e705388b684d1 100644 --- a/docs/user/composer.md +++ b/docs/user/composer.md @@ -37,6 +37,29 @@ at the end, leave the block. **Backspace** at the start of a code block turns it back into plain lines. Choose the language in a code block's corner to change it. Very large code blocks are shown without syntax highlighting. +## Vim mode + +On web and desktop, turn on **Settings → Chat → Vim mode** to edit prompts with +Vim keys. You can also toggle it from the command palette, or assign a shortcut to +`composer.toggleVimMode` in **Settings → Keybindings**. The composer starts in +insert mode; **Escape** switches to normal mode, and the composer footer shows +the current mode. When a menu or prompt suggestion is open, Escape closes it +first. In normal mode, Escape does what it does without vim mode. + +Normal mode supports: + +- Motions `h j k l`, `w b e`, `W B E`, `0 ^ $`, `gg G`, and `f F t T` with `;` + and `,`, with counts such as `3w`. +- `i I a A o O` to insert. +- `x X s S r`, `d c y` with a motion or text object, `dd cc yy`, `D C Y`, `p P`, + `J`, `.` to repeat, `u` to undo and `Ctrl+R` to redo. +- Text objects `iw aw iW aW`, `i" a"`, `i' a'`, `i( a(`, `i[ a[` and `i{ a{`. + +Enter sends from normal mode when your **Send shortcut** would send. A file, +skill or other chip counts as one character. Yanked and deleted text stays in +the composer rather than the clipboard. Lines follow the composer's paragraphs, +not wrapped lines. + ## Attach files Attach up to 100 files per message. Each image can be up to 10 MiB, with at most diff --git a/docs/user/keybindings.md b/docs/user/keybindings.md index 5eb5a4c96d514..ea33a40434f47 100644 --- a/docs/user/keybindings.md +++ b/docs/user/keybindings.md @@ -167,6 +167,9 @@ shortcut; assign one in **Settings → Keybindings**. `thread.regenerateTitle` generates a new title for the focused thread, like **Regenerate title** in the thread menu. It has no default shortcut. +`composer.toggleVimMode` turns [vim mode](./composer.md#vim-mode) on or off. It +has no default shortcut. + `thread.undo` (`mod+z` by default) reverses the actions shown in the notice at the bottom of the sidebar, such as unpin, settle, snooze, archive, or discarding a draft. Consecutive diff --git a/packages/contracts/src/keybindings.ts b/packages/contracts/src/keybindings.ts index 8c9e35afcda10..0e41fcfd4c294 100644 --- a/packages/contracts/src/keybindings.ts +++ b/packages/contracts/src/keybindings.ts @@ -92,6 +92,7 @@ export const STATIC_KEYBINDING_COMMANDS = [ "composer.sendBackground", "composer.sendAndNewThread", "composer.dictation", + "composer.toggleVimMode", "composer.host", "composer.cycleHost", "composer.effort", diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index cd112d84bf9f4..c6c79c8ae1a5d 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -502,6 +502,7 @@ export const ClientSettingsSchema = Schema.Struct({ pullRequestLinksOpenInApp: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))), composerRichTextEnabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))), + composerVimMode: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))), sendShortcut: Schema.Literals(["enter", "mod-enter-multiline", "mod-enter"]).pipe( Schema.withDecodingDefault(Effect.succeed("enter")), ), @@ -2022,6 +2023,7 @@ export const ClientSettingsPatch = Schema.Struct({ ), pullRequestLinksOpenInApp: Schema.optionalKey(Schema.Boolean), composerRichTextEnabled: Schema.optionalKey(Schema.Boolean), + composerVimMode: Schema.optionalKey(Schema.Boolean), sendShortcut: Schema.optionalKey(Schema.Literals(["enter", "mod-enter-multiline", "mod-enter"])), followUpBehavior: Schema.optionalKey(Schema.Literals(["queue", "steer"])), proactivePanelsEnabled: Schema.optionalKey(Schema.Boolean), From 2d20157cbf3aff9262b0c6eec595346f014e23b3 Mon Sep 17 00:00:00 2001 From: Batch Processor <46352227+batchema@users.noreply.github.com> Date: Wed, 11 Nov 2026 11:56:58 -0500 Subject: [PATCH 03/20] feat(web): ctrl+` toggles the terminal (#2) VS Code users reach for Ctrl+` to open and close the terminal. Add it as a second default for terminal.toggle, with literal Ctrl on every platform. Existing keybindings.json files only get it as a late default when they still have the stock mod+j binding, so customized terminal shortcuts stay untouched. mod+j stays the shortcut shown in labels, and Reset to default in Settings now restores the default a command is missing instead of one it already has. Co-authored-by: batchema --- apps/server/src/keybindings.test.ts | 34 ++++++++++-------- apps/server/src/keybindings.ts | 5 +++ .../KeybindingsSettings.logic.test.ts | 10 ++++++ .../settings/KeybindingsSettings.logic.ts | 36 ++++++++++++------- apps/web/src/keybindings.test.ts | 31 ++++++++++++++++ docs/user/keybindings.md | 7 ++++ packages/shared/src/keybindings.ts | 2 ++ 7 files changed, 98 insertions(+), 27 deletions(-) diff --git a/apps/server/src/keybindings.test.ts b/apps/server/src/keybindings.test.ts index cb92c24242d47..e80f2ba836992 100644 --- a/apps/server/src/keybindings.test.ts +++ b/apps/server/src/keybindings.test.ts @@ -229,11 +229,9 @@ it.layer(NodeServices.layer)("keybindings", (it) => { const persisted = yield* readKeybindingsConfig(keybindingsConfigPath); const byCommand = new Map(persisted.map((entry) => [entry.command, entry])); - const persistedToggle = byCommand.get("terminal.toggle"); - assert.isNotNull(persistedToggle); - assert.equal(persistedToggle?.key, "mod+shift+y"); - assert.isFalse( - persisted.some((entry) => entry.command === "terminal.toggle" && entry.key === "mod+j"), + assert.deepStrictEqual( + persisted.filter((entry) => entry.command === "terminal.toggle"), + [{ key: "mod+shift+y", command: "terminal.toggle" }], ); for (const defaultRule of SharedKeybindings.DEFAULT_KEYBINDINGS) { @@ -256,21 +254,26 @@ it.layer(NodeServices.layer)("keybindings", (it) => { const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig; const keybindings = yield* Keybindings.Keybindings; const when = "composerFocus && draftThreadRoute"; - const existing = { key: "mod+alt+enter", command: "composer.sendBackground", when } as const; - const backgroundRules = Effect.map(readKeybindingsConfig(keybindingsConfigPath), (rules) => - rules.filter((entry) => entry.command === "composer.sendBackground"), + const existing: KeybindingRule[] = [ + { key: "mod+alt+enter", command: "composer.sendBackground", when }, + { key: "mod+j", command: "terminal.toggle" }, + ]; + const lateCommands = new Set(existing.map((entry) => entry.command)); + const lateRules = Effect.map(readKeybindingsConfig(keybindingsConfigPath), (rules) => + rules.filter((entry) => lateCommands.has(entry.command)), ); - yield* writeKeybindingsConfig(keybindingsConfigPath, [existing]); + yield* writeKeybindingsConfig(keybindingsConfigPath, existing); yield* keybindings.syncDefaultKeybindingsOnStartup; - assert.deepStrictEqual(yield* backgroundRules, [ + assert.deepStrictEqual(yield* lateRules, [ { key: "mod+enter", command: "composer.sendBackground", when }, - existing, + { key: "ctrl+`", command: "terminal.toggle" }, + ...existing, ]); - yield* writeKeybindingsConfig(keybindingsConfigPath, [existing]); + yield* writeKeybindingsConfig(keybindingsConfigPath, existing); yield* keybindings.syncDefaultKeybindingsOnStartup; - assert.deepStrictEqual(yield* backgroundRules, [existing]); + assert.deepStrictEqual(yield* lateRules, existing); }).pipe(Effect.provide(layerKeybindings())), ); @@ -338,7 +341,10 @@ it.layer(NodeServices.layer)("keybindings", (it) => { }); const persisted = yield* readKeybindingsConfig(keybindingsConfigPath); - assert.isFalse(persisted.some((entry) => entry.command === "terminal.toggle")); + assert.deepStrictEqual( + persisted.filter((entry) => entry.command === "terminal.toggle"), + [{ key: "ctrl+`", command: "terminal.toggle" }], + ); assert.isTrue(persisted.some((entry) => entry.command === "script.custom-action.run")); assert.isTrue( diff --git a/apps/server/src/keybindings.ts b/apps/server/src/keybindings.ts index 0a5bfdd4246ca..adf1e0fce0538 100644 --- a/apps/server/src/keybindings.ts +++ b/apps/server/src/keybindings.ts @@ -112,6 +112,11 @@ const LATE_DEFAULT_KEYBINDINGS: ReadonlyArray<{ when: "composerFocus && draftThreadRoute", }, }, + { + id: "terminal.toggle:ctrl+`", + alongside: { key: "mod+j", command: "terminal.toggle" }, + rule: { key: "ctrl+`", command: "terminal.toggle" }, + }, ]; function keybindingShortcutContext(rule: KeybindingRule): string | null { diff --git a/apps/web/src/components/settings/KeybindingsSettings.logic.test.ts b/apps/web/src/components/settings/KeybindingsSettings.logic.test.ts index 6098239492d70..448bf84300167 100644 --- a/apps/web/src/components/settings/KeybindingsSettings.logic.test.ts +++ b/apps/web/src/components/settings/KeybindingsSettings.logic.test.ts @@ -61,6 +61,16 @@ describe("KeybindingsSettings.logic", () => { ); }); + it("resets a customized shortcut to the default its command no longer has", () => { + const rows = buildKeybindingRows( + compileResolvedKeybindingsConfig([ + { command: "terminal.toggle", key: "ctrl+`" }, + { command: "terminal.toggle", key: "mod+shift+y" }, + ]), + ); + expect(rows.find((row) => row.key === "mod+shift+y")?.defaultKey).toBe("mod+j"); + }); + it("captures platform-specific mod shortcuts", () => { expect( keybindingFromKeyboardEvent( diff --git a/apps/web/src/components/settings/KeybindingsSettings.logic.ts b/apps/web/src/components/settings/KeybindingsSettings.logic.ts index d185901e845aa..5eafe22be31e5 100644 --- a/apps/web/src/components/settings/KeybindingsSettings.logic.ts +++ b/apps/web/src/components/settings/KeybindingsSettings.logic.ts @@ -152,22 +152,23 @@ function sourceForBinding(binding: ResolvedKeybindingRule): KeybindingSource { function defaultBindingForBinding( binding: ResolvedKeybindingRule, + boundIds: ReadonlySet, ): ResolvedKeybindingRule | undefined { - const bindingKey = shortcutToKeybindingInput(binding.shortcut); + const id = bindingRowId(binding); const bindingWhen = whenAstToExpression(binding.whenAst); + const defaults = DEFAULT_RESOLVED_KEYBINDINGS.filter( + (entry) => entry.command === binding.command, + ); + // Reset restores a default the command lost before one it still has. + const candidates = [ + ...defaults.filter((entry) => !boundIds.has(bindingRowId(entry))), + ...defaults.filter((entry) => boundIds.has(bindingRowId(entry))), + ]; return ( - DEFAULT_RESOLVED_KEYBINDINGS.find( - (entry) => - entry.command === binding.command && - shortcutToKeybindingInput(entry.shortcut) === bindingKey && - whenAstToExpression(entry.whenAst) === bindingWhen, - ) ?? - DEFAULT_RESOLVED_KEYBINDINGS.find( - (entry) => - entry.command === binding.command && whenAstToExpression(entry.whenAst) === bindingWhen, - ) ?? - DEFAULT_RESOLVED_KEYBINDINGS.find((entry) => entry.command === binding.command) + defaults.find((entry) => bindingRowId(entry) === id) ?? + candidates.find((entry) => whenAstToExpression(entry.whenAst) === bindingWhen) ?? + candidates[0] ); } @@ -175,6 +176,14 @@ function keybindingRowId(command: KeybindingCommand, key: string, when: string): return `${command}\u0000${key}\u0000${when}`; } +function bindingRowId(binding: ResolvedKeybindingRule): string { + return keybindingRowId( + binding.command, + shortcutToKeybindingInput(binding.shortcut), + whenAstToExpression(binding.whenAst), + ); +} + function conflictsWithWhen(leftWhen: string, rightWhen: string): boolean { return leftWhen.length === 0 || rightWhen.length === 0 || leftWhen === rightWhen; } @@ -252,8 +261,9 @@ export function buildKeybindingRows( platform = navigator.platform, ): ReadonlyArray { const rowsById = new Map(); + const boundIds = new Set(keybindings.map(bindingRowId)); for (const binding of keybindings) { - const defaultBinding = defaultBindingForBinding(binding); + const defaultBinding = defaultBindingForBinding(binding, boundIds); const key = shortcutToKeybindingInput(binding.shortcut); const when = whenAstToExpression(binding.whenAst); const id = keybindingRowId(binding.command, key, when); diff --git a/apps/web/src/keybindings.test.ts b/apps/web/src/keybindings.test.ts index 8708bbd297a91..116109412eb97 100644 --- a/apps/web/src/keybindings.test.ts +++ b/apps/web/src/keybindings.test.ts @@ -17,6 +17,7 @@ import { isRichTextBoldShortcut, isTerminalNewShortcut, isTerminalSplitShortcut, + isTerminalToggleShortcut, resolveChatShortcutCommand, resolveShortcutCommand, shouldShowThreadJumpHintsForModifiers, @@ -299,6 +300,36 @@ describe("split/new/close terminal shortcuts", () => { }), ); }); + + it("toggles with Ctrl+` on every platform, even from the terminal, labelled by mod+j", () => { + const backtick = { key: "`", code: "Backquote" }; + // German layouts put a dead circumflex on the same physical key. + const germanBacktick = { key: "Dead", code: "Backquote" }; + for (const platform of ["MacIntel", "Win32", "Linux"]) { + for (const terminalFocus of [false, true]) { + for (const keys of [backtick, germanBacktick]) { + assert.isTrue( + isTerminalToggleShortcut( + event({ ...keys, ctrlKey: true }), + DEFAULT_RESOLVED_KEYBINDINGS, + { platform, context: { terminalFocus } }, + ), + ); + } + } + } + assert.isFalse( + isTerminalToggleShortcut( + event({ ...backtick, metaKey: true }), + DEFAULT_RESOLVED_KEYBINDINGS, + { platform: "MacIntel" }, + ), + ); + assert.strictEqual( + shortcutLabelForCommand(DEFAULT_RESOLVED_KEYBINDINGS, "terminal.toggle", "MacIntel"), + "⌘J", + ); + }); }); describe("shortcutLabelForCommand", () => { diff --git a/docs/user/keybindings.md b/docs/user/keybindings.md index ea33a40434f47..45b7168493ad7 100644 --- a/docs/user/keybindings.md +++ b/docs/user/keybindings.md @@ -51,6 +51,13 @@ on macOS and Ctrl on Windows and Linux, including GNOME, KDE Plasma, Niri, and Hyprland. If a custom desktop shortcut takes the same keys, choose another binding in Settings. +## Toggle the terminal + +`mod+j` and ``ctrl+` `` open and close the terminal drawer, even while the terminal +has focus. Like VS Code, ``ctrl+` `` uses Control on every platform, including macOS. +If you changed the terminal shortcut earlier, T3 Code leaves it alone and does not +add ``ctrl+` ``; add it under **Terminal: Toggle** in Keybindings. + ## Copy pull request references With a PR open in the right panel or on the Pull requests page, use `mod+shift+c` diff --git a/packages/shared/src/keybindings.ts b/packages/shared/src/keybindings.ts index ba4d1d925be48..28bc998af3e2b 100644 --- a/packages/shared/src/keybindings.ts +++ b/packages/shared/src/keybindings.ts @@ -63,6 +63,8 @@ export const DEFAULT_KEYBINDINGS: ReadonlyArray = [ { key: "mod+shift+f6", command: "workspace.focusPrevious" }, { key: "mod+[", command: "navigation.back", when: "!terminalFocus" }, { key: "mod+]", command: "navigation.forward", when: "!terminalFocus" }, + // VS Code's chord uses Ctrl on every platform. Listed before mod+j so labels show mod+j. + { key: "ctrl+`", command: "terminal.toggle" }, { key: "mod+j", command: "terminal.toggle" }, { key: "mod+alt+b", command: "rightPanel.toggle" }, { key: "mod+shift+b", command: "threadPanel.toggle", when: "!terminalFocus" }, From e34ad55dbb36edcbcf8f2f4a5f3a086669839d7e Mon Sep 17 00:00:00 2001 From: batchema Date: Wed, 11 Nov 2026 11:57:04 -0500 Subject: [PATCH 04/20] docs: check off merged TODO items --- TODO.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/TODO.md b/TODO.md index cc136e3cf0039..6f77154462894 100644 --- a/TODO.md +++ b/TODO.md @@ -1,9 +1,9 @@ # TODO -- [ ] **Vim motions in the composer.** An opt-in vim mode for the chat input, like Claude Code's +- [x] **Vim motions in the composer.** An opt-in vim mode for the chat input, like Claude Code's `/vim`: normal and insert modes, common motions (`hjkl`, `w`/`b`/`e`, `0`/`$`, `gg`/`G`), operators (`d`, `c`, `y`) with motions and text objects, and a visible mode indicator. -- [ ] **`ctrl+`` toggles the terminal.** Match VS Code: `ctrl+`` opens and closes the terminal +- [x] **`ctrl+`` toggles the terminal.** Match VS Code: `ctrl+`` opens and closes the terminal drawer, alongside the existing `mod+j`, including while the terminal has focus. - [ ] **Setting to hide thread details by default.** New threads always open the Thread Details card because `inlineOpen: true` is hardcoded in `apps/web/src/rightPanelStore.ts`. Add a From e88b44a52a325dc10b557304a0af4c8358dd5eac Mon Sep 17 00:00:00 2001 From: Batch Processor <46352227+batchema@users.noreply.github.com> Date: Wed, 11 Nov 2026 12:29:38 -0500 Subject: [PATCH 05/20] feat(web): thread details default setting, vim mode on by default (#3) The thread details card was always open in threads without a per-thread choice. Add Settings > Appearance > Open thread details by default (off), and store per-thread choices as explicit overrides in both directions so they survive changes to the setting. Older saved "closed" choices still load as closed. Also turn composer vim mode on by default. Co-authored-by: batchema --- TODO.md | 6 +-- apps/web/src/components/ChatView.tsx | 11 +++++- apps/web/src/components/chat/ChatCanvas.tsx | 11 +++++- .../chat/ThreadDetailsCard.browser.test.tsx | 8 +++- .../src/components/chat/ThreadDetailsCard.tsx | 18 ++++++++- .../components/chat/useRightPanelActions.ts | 14 ++++--- .../settings/AppearanceSettingsPanel.tsx | 26 +++++++++++++ .../components/settings/SettingsPanels.tsx | 4 ++ .../src/components/settings/settingsSearch.ts | 6 +++ apps/web/src/rightPanelStore.test.ts | 38 +++++++++++++++---- apps/web/src/rightPanelStore.ts | 38 +++++++------------ docs/user/composer.md | 13 ++++--- docs/user/thread-sidebar.md | 5 +++ packages/contracts/src/settings.ts | 6 ++- 14 files changed, 152 insertions(+), 52 deletions(-) diff --git a/TODO.md b/TODO.md index 6f77154462894..7e178f931ad61 100644 --- a/TODO.md +++ b/TODO.md @@ -5,10 +5,10 @@ operators (`d`, `c`, `y`) with motions and text objects, and a visible mode indicator. - [x] **`ctrl+`` toggles the terminal.** Match VS Code: `ctrl+`` opens and closes the terminal drawer, alongside the existing `mod+j`, including while the terminal has focus. -- [ ] **Setting to hide thread details by default.** New threads always open the Thread Details +- [x] **Setting to hide thread details by default.** New threads always open the Thread Details card because `inlineOpen: true` is hardcoded in `apps/web/src/rightPanelStore.ts`. Add a - setting such as "Show thread details in new threads" that feeds that default. Leave it on by - default to match today's behavior. Toggling per thread (button or `mod+shift+b`) should keep + setting such as "Show thread details in new threads" that feeds that default. It defaults to + off, so the card starts closed. Toggling per thread (button or `mod+shift+b`) should keep working as it does now. - [ ] **Agents can drive all of T3 Code.** Extend the T3 MCP server beyond orchestration (threads, projects, previews, devices) so agents can also control the app itself: settings, diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index f4561188df0cc..337d1b2c74f39 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -1923,8 +1923,16 @@ export default function ChatView(props: ChatViewProps) { ? activePreviewMiniPlayer : null; const canvasPreview = useThreadPreviewCanvasSource(activeThreadRef, shownPreviewMiniPlayer); + const threadDetailsOpenByDefault = useClientSettings( + (settings) => settings.threadDetailsOpenByDefault, + ); const threadPanelInlineOpen = useRightPanelStore((state) => - selectThreadPanelOpen(state.threadPanelVisibilityByThreadKey, activeThreadRef, "inline"), + selectThreadPanelOpen( + state.threadPanelVisibilityByThreadKey, + activeThreadRef, + "inline", + threadDetailsOpenByDefault, + ), ); // Selects only the mode, so canvas resizes rerender the chat view only when the // card switches presentation. @@ -1944,6 +1952,7 @@ export default function ChatView(props: ChatViewProps) { state.threadPanelVisibilityByThreadKey, activeThreadRef, threadPanelPresentation, + threadDetailsOpenByDefault, ), ); const supportsThreadPullRequests = serverConfig !== null; diff --git a/apps/web/src/components/chat/ChatCanvas.tsx b/apps/web/src/components/chat/ChatCanvas.tsx index e05d3befcc138..401763beaefa8 100644 --- a/apps/web/src/components/chat/ChatCanvas.tsx +++ b/apps/web/src/components/chat/ChatCanvas.tsx @@ -4,6 +4,7 @@ import { ChatCanvasContext } from "./ChatCanvasContext"; import type { ChatCanvasPreview } from "./chatCanvasLayout"; import { resolveChatCanvasModel, type ChatCanvasStore } from "./canvasStore"; import { selectThreadPanelOpen, useRightPanelStore } from "../../rightPanelStore"; +import { useClientSettings } from "../../hooks/useSettings"; import { observeResize } from "../../lib/observeResize"; import type { ScopedThreadRef } from "@t3tools/contracts"; @@ -67,10 +68,18 @@ export function ChatCanvas({ if (timelineElement) observed.push(timelineElement); return observeResize(observed, measure); }, [store, composerOverlayElement, timelineElement, detailsCardTopInset]); + const threadDetailsOpenByDefault = useClientSettings( + (settings) => settings.threadDetailsOpenByDefault, + ); const detailsCardInlineOpen = useRightPanelStore((state) => threadRef === null ? false - : selectThreadPanelOpen(state.threadPanelVisibilityByThreadKey, threadRef, "inline"), + : selectThreadPanelOpen( + state.threadPanelVisibilityByThreadKey, + threadRef, + "inline", + threadDetailsOpenByDefault, + ), ); const model = resolveChatCanvasModel({ measurements, diff --git a/apps/web/src/components/chat/ThreadDetailsCard.browser.test.tsx b/apps/web/src/components/chat/ThreadDetailsCard.browser.test.tsx index e234686d6ff0c..5c1d45782411b 100644 --- a/apps/web/src/components/chat/ThreadDetailsCard.browser.test.tsx +++ b/apps/web/src/components/chat/ThreadDetailsCard.browser.test.tsx @@ -1,4 +1,5 @@ import { StrictMode } from "react"; +import { scopedThreadKey } from "@t3tools/client-runtime/environment"; import { EnvironmentId, ThreadId, type ScopedThreadRef } from "@t3tools/contracts"; import { expect, it } from "vite-plus/test"; import { page } from "vite-plus/test/browser"; @@ -21,7 +22,11 @@ const container = { width: 1200, height: 800 }; const placement = { x: 908, y: 0, right: 12, width: 280, height: 400 } as const; function setup() { - useRightPanelStore.setState({ threadPanelVisibilityByThreadKey: {} }); + useRightPanelStore.setState({ + threadPanelVisibilityByThreadKey: { + [scopedThreadKey(threadB)]: { inlineOpen: true, popoverOpen: false }, + }, + }); const anchor = document.createElement("div"); document.body.append(anchor); return { @@ -36,6 +41,7 @@ const popoverOpen = (threadRef: ScopedThreadRef) => useRightPanelStore.getState().threadPanelVisibilityByThreadKey, threadRef, "popover", + false, ); function Card({ diff --git a/apps/web/src/components/chat/ThreadDetailsCard.tsx b/apps/web/src/components/chat/ThreadDetailsCard.tsx index 4e8a47a39791a..835daeacf9697 100644 --- a/apps/web/src/components/chat/ThreadDetailsCard.tsx +++ b/apps/web/src/components/chat/ThreadDetailsCard.tsx @@ -11,6 +11,7 @@ import { ScrollArea } from "../ui/scroll-area"; import { cn } from "../../lib/utils"; import { Popover, PopoverPopup, PopoverCreateHandle } from "../ui/popover"; import { selectThreadPanelOpen, useRightPanelStore } from "../../rightPanelStore"; +import { useClientSettings } from "../../hooks/useSettings"; import { useChatCanvas } from "./ChatCanvasContext"; import { THREAD_DETAILS_CARD_GAP, @@ -41,11 +42,24 @@ export function ThreadDetailsCard({ const placement = canvas?.detailsCardPlacement ?? null; const mode = placement ? "inline" : "popover"; const topInset = canvas?.detailsCardTopInset ?? 0; + const threadDetailsOpenByDefault = useClientSettings( + (settings) => settings.threadDetailsOpenByDefault, + ); const inlineOpen = useRightPanelStore((state) => - selectThreadPanelOpen(state.threadPanelVisibilityByThreadKey, threadRef, "inline"), + selectThreadPanelOpen( + state.threadPanelVisibilityByThreadKey, + threadRef, + "inline", + threadDetailsOpenByDefault, + ), ); const popoverOpen = useRightPanelStore((state) => - selectThreadPanelOpen(state.threadPanelVisibilityByThreadKey, threadRef, "popover"), + selectThreadPanelOpen( + state.threadPanelVisibilityByThreadKey, + threadRef, + "popover", + threadDetailsOpenByDefault, + ), ); const measurementKey = `${threadRef.environmentId}:${threadRef.threadId}:${preferredPlacement?.width ?? "popup"}:${contentKey}`; const [measurements, setMeasurements] = useState({ diff --git a/apps/web/src/components/chat/useRightPanelActions.ts b/apps/web/src/components/chat/useRightPanelActions.ts index 25ec5c22c2e1a..4b7342125002c 100644 --- a/apps/web/src/components/chat/useRightPanelActions.ts +++ b/apps/web/src/components/chat/useRightPanelActions.ts @@ -13,6 +13,7 @@ import { squashAtomCommandFailure, } from "@t3tools/client-runtime/state/runtime"; import { useDiffPanelStore } from "../../diffPanelStore"; +import { getClientSettings } from "../../hooks/useSettings"; import { type ThreadPanelPresentation } from "../../rightPanelLayout"; import { selectActiveRightPanel, @@ -231,17 +232,18 @@ export function useRightPanelActions(input: RightPanelActionsInput) { const toggleThreadPanel = () => { if (!activeThreadRef) return; const store = useRightPanelStore.getState(); + const open = selectThreadPanelOpen( + store.threadPanelVisibilityByThreadKey, + activeThreadRef, + threadPanelPresentation, + getClientSettings().threadDetailsOpenByDefault, + ); if (threadPanelPresentation === "inline") { - const open = selectThreadPanelOpen( - store.threadPanelVisibilityByThreadKey, - activeThreadRef, - "inline", - ); if (!open) requestWorkspaceFocus({ area: "details" }); else if (document.activeElement?.closest('[data-workspace-area="details"]')) requestWorkspaceContentFocus(); } - store.toggleThreadPanel(activeThreadRef, threadPanelPresentation); + store.setThreadPanelOpen(activeThreadRef, threadPanelPresentation, !open); }; const toggleThreadPanelStable = useStableCallback(toggleThreadPanel); const toggleRightPanelMaximized = () => { diff --git a/apps/web/src/components/settings/AppearanceSettingsPanel.tsx b/apps/web/src/components/settings/AppearanceSettingsPanel.tsx index 00783b085d609..bbefef57ecff6 100644 --- a/apps/web/src/components/settings/AppearanceSettingsPanel.tsx +++ b/apps/web/src/components/settings/AppearanceSettingsPanel.tsx @@ -290,6 +290,32 @@ export function AppearanceSettingsPanel() { } /> + + updateSettings({ + threadDetailsOpenByDefault: DEFAULT_UNIFIED_SETTINGS.threadDetailsOpenByDefault, + }) + } + /> + ) : null + } + control={ + + updateSettings({ threadDetailsOpenByDefault: Boolean(checked) }) + } + aria-label="Open thread details by default" + /> + } + /> void) { ? ["Diff colors"] : []), ...(settings.chatWidth !== DEFAULT_UNIFIED_SETTINGS.chatWidth ? ["Chat width"] : []), + ...(settings.threadDetailsOpenByDefault !== DEFAULT_UNIFIED_SETTINGS.threadDetailsOpenByDefault + ? ["Open thread details by default"] + : []), ...(settings.effortDisplay !== DEFAULT_UNIFIED_SETTINGS.effortDisplay ? ["Effort display"] : []), @@ -639,6 +642,7 @@ export function useSettingsRestore(onRestored?: () => void) { appearanceContrast: DEFAULT_UNIFIED_SETTINGS.appearanceContrast, diffColorScheme: DEFAULT_UNIFIED_SETTINGS.diffColorScheme, chatWidth: DEFAULT_UNIFIED_SETTINGS.chatWidth, + threadDetailsOpenByDefault: DEFAULT_UNIFIED_SETTINGS.threadDetailsOpenByDefault, effortDisplay: DEFAULT_UNIFIED_SETTINGS.effortDisplay, mathRenderingEnabled: DEFAULT_UNIFIED_SETTINGS.mathRenderingEnabled, timestampFormat: DEFAULT_UNIFIED_SETTINGS.timestampFormat, diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts index c8935c9ecfaac..f0bbffbeddb06 100644 --- a/apps/web/src/components/settings/settingsSearch.ts +++ b/apps/web/src/components/settings/settingsSearch.ts @@ -351,6 +351,12 @@ export const SETTINGS_SEARCH_ITEMS = [ "customize show hide panel card environment editor scripts branch pull request git changes servers automations lineage usage limits 5 hour weekly quota tokens context window", ], }, + { + id: "thread-details-open-by-default", + title: "Open thread details by default", + to: "/settings/appearance", + searchTerms: ["show hide panel card new threads collapsed closed"], + }, { id: "effort-display", title: "Effort display", diff --git a/apps/web/src/rightPanelStore.test.ts b/apps/web/src/rightPanelStore.test.ts index ec0f4e87c12e8..39e3f7b1eaec5 100644 --- a/apps/web/src/rightPanelStore.test.ts +++ b/apps/web/src/rightPanelStore.test.ts @@ -11,6 +11,7 @@ import { pullRequestSurfaceId, selectActiveRightPanel, selectActiveRightPanelSurface, + selectThreadPanelOpen, selectThreadPanelVisibility, selectThreadRightPanelState, useRightPanelStore, @@ -695,16 +696,33 @@ describe("rightPanelStore", () => { threadPanelVisibilityByThreadKey: { "env-1:thread-A": { inlineOpen: false, popoverOpen: true }, "env-1:thread-B": { inlineOpen: true, popoverOpen: true }, + "env-1:thread-C": { popoverOpen: true }, }, }), ).toEqual({ byThreadKey: {}, threadPanelVisibilityByThreadKey: { "env-1:thread-A": { inlineOpen: false, popoverOpen: false }, + "env-1:thread-B": { inlineOpen: true, popoverOpen: false }, }, }); }); + it("opens the inline card from the setting until the thread has its own choice", async () => { + const visibility = () => useRightPanelStore.getState().threadPanelVisibilityByThreadKey; + expect(selectThreadPanelOpen(visibility(), refA, "inline", false)).toBe(false); + expect(selectThreadPanelOpen(visibility(), refA, "inline", true)).toBe(true); + + useRightPanelStore.getState().setThreadPanelOpen(refA, "inline", true); + useRightPanelStore.getState().setThreadPanelOpen(refB, "inline", false); + await reloadRightPanelStore(); + + for (const openByDefault of [false, true]) { + expect(selectThreadPanelOpen(visibility(), refA, "inline", openByDefault)).toBe(true); + expect(selectThreadPanelOpen(visibility(), refB, "inline", openByDefault)).toBe(false); + } + }); + it("closes the popover atomically when the real right panel opens", () => { useRightPanelStore.getState().setThreadPanelOpen(refA, "popover", true); useRightPanelStore.getState().open(refA, "diff"); @@ -714,7 +732,7 @@ describe("rightPanelStore", () => { useRightPanelStore.getState().threadPanelVisibilityByThreadKey, refA, ), - ).toEqual({ inlineOpen: true, popoverOpen: false }); + ).toEqual({ popoverOpen: false }); }); it("keeps an open popover visible by promoting it to inline when the real panel closes", () => { @@ -723,13 +741,19 @@ describe("rightPanelStore", () => { store.setThreadPanelOpen(refA, "inline", false); store.setThreadPanelOpen(refA, "popover", true); store.close(refA); + store.open(refB, "diff"); + store.setThreadPanelOpen(refB, "popover", true); + store.close(refB); - expect( - selectThreadPanelVisibility( - useRightPanelStore.getState().threadPanelVisibilityByThreadKey, - refA, - ), - ).toEqual({ inlineOpen: true, popoverOpen: true }); + const { threadPanelVisibilityByThreadKey } = useRightPanelStore.getState(); + expect(selectThreadPanelVisibility(threadPanelVisibilityByThreadKey, refA)).toEqual({ + inlineOpen: true, + popoverOpen: true, + }); + expect(selectThreadPanelVisibility(threadPanelVisibilityByThreadKey, refB)).toEqual({ + inlineOpen: true, + popoverOpen: true, + }); }); it("opens workspace-root links as the singleton files explorer", () => { diff --git a/apps/web/src/rightPanelStore.ts b/apps/web/src/rightPanelStore.ts index 1f736d4f119ae..22f3832009fe5 100644 --- a/apps/web/src/rightPanelStore.ts +++ b/apps/web/src/rightPanelStore.ts @@ -98,7 +98,8 @@ export interface ThreadRightPanelState { } export interface ThreadPanelVisibility { - inlineOpen: boolean; + /** The user's choice for this thread. Absent, the threadDetailsOpenByDefault setting applies. */ + inlineOpen?: boolean; popoverOpen: boolean; } @@ -192,7 +193,6 @@ interface RightPanelStoreState { presentation: ThreadPanelPresentation, open: boolean, ) => void; - toggleThreadPanel: (ref: ScopedThreadRef, presentation: ThreadPanelPresentation) => void; removeThread: (ref: ScopedThreadRef) => void; } @@ -202,10 +202,7 @@ const EMPTY_THREAD_STATE: ThreadRightPanelState = { surfaces: [], }; -const DEFAULT_THREAD_PANEL_VISIBILITY: ThreadPanelVisibility = { - inlineOpen: true, - popoverOpen: false, -}; +const DEFAULT_THREAD_PANEL_VISIBILITY: ThreadPanelVisibility = { popoverOpen: false }; const singletonSurface = ( kind: Exclude, @@ -335,7 +332,7 @@ const updateThreadPanelVisibilityMap = ( ): Record => { const current = byThreadKey[threadKey] ?? DEFAULT_THREAD_PANEL_VISIBILITY; const next = updater(current); - if (next.inlineOpen && !next.popoverOpen) { + if (next.inlineOpen === undefined && !next.popoverOpen) { if (!(threadKey in byThreadKey)) return byThreadKey; const { [threadKey]: _removed, ...rest } = byThreadKey; return rest; @@ -366,11 +363,12 @@ const updateThread = ( (visibility) => (visibility.popoverOpen ? { ...visibility, popoverOpen: false } : visibility), ); } else if (current.isOpen && !next.isOpen) { + // The store can't see the default setting, so an open popover becomes an explicit inline choice. threadPanelVisibilityByThreadKey = updateThreadPanelVisibilityMap( threadPanelVisibilityByThreadKey, threadKey, (visibility) => - visibility.popoverOpen && !visibility.inlineOpen + visibility.popoverOpen && visibility.inlineOpen !== true ? { ...visibility, inlineOpen: true } : visibility, ); @@ -612,8 +610,8 @@ export function migratePersistedRightPanelState(persistedState: unknown): { persistedState.threadPanelVisibilityByThreadKey as Record, ).flatMap(([threadKey, value]) => { if (!value || typeof value !== "object" || !("inlineOpen" in value)) return []; - return value.inlineOpen === false - ? [[threadKey, { inlineOpen: false, popoverOpen: false }]] + return typeof value.inlineOpen === "boolean" + ? [[threadKey, { inlineOpen: value.inlineOpen, popoverOpen: false }]] : []; }), ) @@ -1119,17 +1117,6 @@ export const useRightPanelStore = create()( }, ), })), - toggleThreadPanel: (ref, presentation) => - set((state) => ({ - threadPanelVisibilityByThreadKey: updateThreadPanelVisibilityMap( - state.threadPanelVisibilityByThreadKey, - scopedThreadKey(ref), - (visibility) => - presentation === "inline" - ? { ...visibility, inlineOpen: !visibility.inlineOpen } - : { ...visibility, popoverOpen: !visibility.popoverOpen }, - ), - })), removeThread: (ref) => set((state) => { const threadKey = scopedThreadKey(ref); @@ -1170,8 +1157,8 @@ export const useRightPanelStore = create()( ), threadPanelVisibilityByThreadKey: Object.fromEntries( Object.entries(state.threadPanelVisibilityByThreadKey).flatMap( - ([threadKey, visibility]) => - visibility.inlineOpen ? [] : [[threadKey, { inlineOpen: false, popoverOpen: false }]], + ([threadKey, { inlineOpen }]) => + inlineOpen === undefined ? [] : [[threadKey, { inlineOpen, popoverOpen: false }]], ), ), }), @@ -1226,9 +1213,12 @@ export function selectThreadPanelOpen( byThreadKey: Record, ref: ScopedThreadRef | null | undefined, presentation: ThreadPanelPresentation, + inlineOpenByDefault: boolean, ): boolean { const visibility = selectThreadPanelVisibility(byThreadKey, ref); - return presentation === "inline" ? visibility.inlineOpen : visibility.popoverOpen; + return presentation === "inline" + ? (visibility.inlineOpen ?? inlineOpenByDefault) + : visibility.popoverOpen; } export function selectActiveRightPanel( diff --git a/docs/user/composer.md b/docs/user/composer.md index e705388b684d1..cb276443a6822 100644 --- a/docs/user/composer.md +++ b/docs/user/composer.md @@ -39,12 +39,13 @@ it. Very large code blocks are shown without syntax highlighting. ## Vim mode -On web and desktop, turn on **Settings → Chat → Vim mode** to edit prompts with -Vim keys. You can also toggle it from the command palette, or assign a shortcut to -`composer.toggleVimMode` in **Settings → Keybindings**. The composer starts in -insert mode; **Escape** switches to normal mode, and the composer footer shows -the current mode. When a menu or prompt suggestion is open, Escape closes it -first. In normal mode, Escape does what it does without vim mode. +On web and desktop, vim mode is on by default, so you can edit prompts with Vim +keys. Turn it off in **Settings → Chat → Vim mode**. You can also toggle it from +the command palette, or assign a shortcut to `composer.toggleVimMode` in +**Settings → Keybindings**. The composer starts in insert mode; **Escape** +switches to normal mode, and the composer footer shows the current mode. When a +menu or prompt suggestion is open, Escape closes it first. In normal mode, Escape +does what it does without vim mode. Normal mode supports: diff --git a/docs/user/thread-sidebar.md b/docs/user/thread-sidebar.md index 09ce63e2a3e65..2b7da7cc3ba65 100644 --- a/docs/user/thread-sidebar.md +++ b/docs/user/thread-sidebar.md @@ -290,6 +290,11 @@ Select a server to open it in the browser panel. **Stop** ends the server's job and keeps the agent, the terminal, and T3 Code running. Stop needs terminal access to the environment and is not available on Windows. +The thread details card starts closed in each thread. Show or hide it with +`mod+shift+b`, and the thread remembers your choice. To show it in every thread you +haven't opened or closed it in, turn on **Settings → Appearance → Open thread +details by default**. + To choose what the thread details card shows, right-click the card or open **Settings → Appearance → Thread details**. Hidden rows keep their keyboard shortcuts, such as Open in editor and project scripts. **Reset to default** brings diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index c6c79c8ae1a5d..c9c4350192a96 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -502,7 +502,7 @@ export const ClientSettingsSchema = Schema.Struct({ pullRequestLinksOpenInApp: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))), composerRichTextEnabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))), - composerVimMode: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))), + composerVimMode: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))), sendShortcut: Schema.Literals(["enter", "mod-enter-multiline", "mod-enter"]).pipe( Schema.withDecodingDefault(Effect.succeed("enter")), ), @@ -525,6 +525,9 @@ export const ClientSettingsSchema = Schema.Struct({ threadDetailsItems: Schema.Record(Schema.String, Schema.Boolean).pipe( Schema.withDecodingDefault(Effect.succeed({})), ), + threadDetailsOpenByDefault: Schema.Boolean.pipe( + Schema.withDecodingDefault(Effect.succeed(false)), + ), sidebarWorkingShelfEnabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))), sidebarProjectGroupingMode: SidebarProjectGroupingMode.pipe( Schema.withDecodingDefault(Effect.succeed(DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE)), @@ -2033,6 +2036,7 @@ export const ClientSettingsPatch = Schema.Struct({ toolCallVisibility: Schema.optionalKey(ToolCallVisibility), threadDetailsUsageEnabled: Schema.optionalKey(Schema.Boolean), threadDetailsItems: Schema.optionalKey(Schema.Record(Schema.String, Schema.Boolean)), + threadDetailsOpenByDefault: Schema.optionalKey(Schema.Boolean), sidebarWorkingShelfEnabled: Schema.optionalKey(Schema.Boolean), sidebarProjectGroupingMode: Schema.optionalKey(SidebarProjectGroupingMode), sidebarProjectGroupingOverrides: Schema.optionalKey( From 01f625d6988eaac88486a44a6824d42ea144fd4f Mon Sep 17 00:00:00 2001 From: Batch Processor <46352227+batchema@users.noreply.github.com> Date: Fri, 13 Nov 2026 14:02:13 +0100 Subject: [PATCH 06/20] docs: track fork to-dos in GitHub Issues The to-do list moves from TODO.md to the fork's issues (#5, #6) so every branch sees the same list. AGENTS.md tells agents to file new to-dos there. --- AGENTS.md | 8 ++++++++ TODO.md | 20 -------------------- 2 files changed, 8 insertions(+), 20 deletions(-) delete mode 100644 TODO.md diff --git a/AGENTS.md b/AGENTS.md index 2effa629d25e0..02c2cc5e03146 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -210,3 +210,11 @@ Architecture and its constraints: `docs/internals/overview.md`. Glossary: `docs/ ## Additional tips - Security is important, but should not be over-indexed on, especially for dev mode/maintainer-only features. + +## This fork + +This checkout is `batchema/t3code`, a personal fork. Its to-do list is the fork's GitHub Issues, not a file in the repo, so every branch sees the same list. + +- When asked to add a to-do, open an issue: `gh issue create --repo batchema/t3code`. Never file it upstream. +- `gh issue list --repo batchema/t3code` shows open work. +- A PR that finishes an issue says `Closes #N`; one that finishes part of it says `Part of #N`. diff --git a/TODO.md b/TODO.md deleted file mode 100644 index 7e178f931ad61..0000000000000 --- a/TODO.md +++ /dev/null @@ -1,20 +0,0 @@ -# TODO - -- [x] **Vim motions in the composer.** An opt-in vim mode for the chat input, like Claude Code's - `/vim`: normal and insert modes, common motions (`hjkl`, `w`/`b`/`e`, `0`/`$`, `gg`/`G`), - operators (`d`, `c`, `y`) with motions and text objects, and a visible mode indicator. -- [x] **`ctrl+`` toggles the terminal.** Match VS Code: `ctrl+`` opens and closes the terminal - drawer, alongside the existing `mod+j`, including while the terminal has focus. -- [x] **Setting to hide thread details by default.** New threads always open the Thread Details - card because `inlineOpen: true` is hardcoded in `apps/web/src/rightPanelStore.ts`. Add a - setting such as "Show thread details in new threads" that feeds that default. It defaults to - off, so the card starts closed. Toggling per thread (button or `mod+shift+b`) should keep - working as it does now. -- [ ] **Agents can drive all of T3 Code.** Extend the T3 MCP server beyond orchestration - (threads, projects, previews, devices) so agents can also control the app itself: settings, - keybindings, panels and layout, navigation, and any action a user can trigger from the UI or - command palette. -- [ ] **Agents know about linked environments.** Agents can't currently see the other machines - linked to T3 Code (e.g. a devbox): the environment-listing MCP tool isn't exposed, so an - agent only knows its own environment. Let agents list linked environments (label, platform, - ID) when they need to, so they can act on or hand work off to another machine. From d5dab250c5573044521f1a0512f735065c5b8d16 Mon Sep 17 00:00:00 2001 From: Batch Processor <46352227+batchema@users.noreply.github.com> Date: Fri, 13 Nov 2026 08:08:39 -0500 Subject: [PATCH 07/20] feat(server): agents can change settings and keyboard shortcuts (#4) * feat(server): agents can change settings and keyboard shortcuts Agents could only change five curated preferences, so a request like "turn on linked environments" ended with the user editing settings.json by hand. Replace t3_environment_preferences_update with tools over the services the Settings page already uses: t3_environment_settings_read/update and t3_keybindings_read, t3_keybinding_upsert and t3_keybinding_remove. Settings travel as plain JSON validated server-side, so the tool list grows by 1.4 KB rather than the full settings schema. Agents cannot grant themselves browser or device access, and secrets read back redacted. * fix(server): agents cannot regain access through project overrides Review found two holes in the new settings and keybinding tools. A project override could grant an agent browser or device access, or clear a denial, because only top-level keys were checked. Compare the effective access for every project before and after the patch instead, so agents can give access up but never take it. Reading shortcuts re-encoded each rule through the 256-character config schema, and the fully parenthesized `when` of a valid rule near the limit overflowed it, failing the whole read. List rules in an unbounded text form, validate new rules as the Settings page path does, and match replace and remove targets against the listed rules. * fix(server): check agent access inside the settings write lock The access check read one settings snapshot and the write applied the patch to whatever was current once it took the settings lock, so a user change landing in between could turn an agent's harmless patch into a grant. updateSettings takes an optional check that runs inside the write lock against the exact settings the patch is applied to; failing it aborts the write. The environment tools pass their access check through it. Handler tests now run against the in-memory settings service. * fix(server): listed shortcut conditions write back within the limit Listed rules printed `when` fully parenthesized, so a valid condition near the 256-character limit came back too long to pass to t3_keybinding_upsert. Print only the parentheses the parser needs to rebuild the same tree, so a rule read back is no longer than its stored form. Matching still compares parsed trees. Restores the long-condition round-trip test that the previous commit dropped by mistake. --- apps/server/src/keybindings.test.ts | 20 ++ apps/server/src/keybindings.ts | 38 ++- .../mcp/toolkits/environment/handlers.test.ts | 225 ++++++++++++++---- .../src/mcp/toolkits/environment/handlers.ts | 204 ++++++++++++++-- .../src/mcp/toolkits/environment/tools.ts | 85 ++++++- .../Adapters/ClaudeAdapterV2.ts | 2 + .../src/provider/AgentContextBudget.test.ts | 2 + .../src/provider/agentContextBudget.json | 2 +- apps/server/src/serverSettings.test.ts | 18 ++ apps/server/src/serverSettings.ts | 41 ++-- evals/mcp-tool-use/cases/settings.ndjson | 1 + packages/client-runtime/src/t3ToolSummary.ts | 4 +- packages/shared/src/t3McpToolPresentation.ts | 20 +- 13 files changed, 556 insertions(+), 106 deletions(-) create mode 100644 evals/mcp-tool-use/cases/settings.ndjson diff --git a/apps/server/src/keybindings.test.ts b/apps/server/src/keybindings.test.ts index e80f2ba836992..93960e1bddbd7 100644 --- a/apps/server/src/keybindings.test.ts +++ b/apps/server/src/keybindings.test.ts @@ -102,6 +102,26 @@ it.layer(NodeServices.layer)("keybindings", (it) => { }), ); + it.effect("writes a rule's condition back with only the parentheses its meaning needs", () => + Effect.sync(() => { + for (const [when, expected] of [ + ["a && b && c", "a && b && c"], + ["a && (b && c)", "a && (b && c)"], + ["a || b && c", "a || b && c"], + ["(a || b) && !c", "(a || b) && !c"], + ["!(a && b) || !!c", "!(a && b) || !!c"], + ["((a))", "a"], + ] as const) { + const rule = { key: "mod+k", command: "terminal.toggle" as const, when }; + const resolved = SharedKeybindings.compileResolvedKeybindingRule(rule); + assert.ok(resolved); + const text = Keybindings.keybindingRuleText(resolved); + assert.equal(text.when, expected); + assert.deepEqual(SharedKeybindings.compileResolvedKeybindingRule(text), resolved); + } + }), + ); + it.effect("rejects invalid rules", () => Effect.sync(() => { assert.isNull( diff --git a/apps/server/src/keybindings.ts b/apps/server/src/keybindings.ts index adf1e0fce0538..bef5e4a902a45 100644 --- a/apps/server/src/keybindings.ts +++ b/apps/server/src/keybindings.ts @@ -1,4 +1,5 @@ import { + type KeybindingCommand, KeybindingRule, KeybindingsConfigError, KeybindingShortcut, @@ -82,7 +83,7 @@ export const ResolvedKeybindingFromConfig = KeybindingRule.pipe( // Settings sends replace/remove targets in its own normalized spelling, which can differ from a // hand-edited file ("cmd+k" vs "meta+k", "a&&b" vs "a && b"), so compare parsed forms. -function keybindingRuleIdentity(rule: KeybindingRule): string { +function keybindingRuleIdentity(rule: KeybindingRuleText): string { const shortcut = parseKeybindingShortcut(rule.key); const key = (shortcut && encodeShortcut(shortcut)) ?? rule.key; if (rule.when === undefined) return JSON.stringify([rule.command, key, null]); @@ -90,10 +91,28 @@ function keybindingRuleIdentity(rule: KeybindingRule): string { return JSON.stringify([rule.command, key, whenAst ? encodeWhenAst(whenAst) : rule.when]); } -function isSameKeybindingRule(left: KeybindingRule, right: KeybindingRule): boolean { +interface KeybindingRuleText { + readonly key: string; + readonly command: string; + readonly when?: string | undefined; +} + +export function isSameKeybindingRule(left: KeybindingRuleText, right: KeybindingRuleText): boolean { return keybindingRuleIdentity(left) === keybindingRuleIdentity(right); } +/** Text form of a loaded rule. Unlike the config schema it has no length limit, so any loaded rule renders. */ +export function keybindingRuleText(rule: ResolvedKeybindingRule): { + readonly key: string; + readonly command: KeybindingCommand; + readonly when?: string; +} { + const key = encodeShortcut(rule.shortcut) ?? rule.shortcut.key; + return rule.whenAst === undefined + ? { key, command: rule.command } + : { key, command: rule.command, when: encodeWhenAst(rule.whenAst) }; +} + const LATE_DEFAULT_KEYBINDINGS: ReadonlyArray<{ readonly id: string; readonly alongside: KeybindingRule; @@ -160,19 +179,28 @@ function encodeShortcut(shortcut: KeybindingShortcut): string | null { return [...modifiers, key].join("+"); } +// Parenthesizes only where the parser needs it to rebuild the same tree, so a rule read back fits +// the length limit its stored form did: `&&` binds tighter than `||`, and both group left to right. function encodeWhenAst(node: KeybindingWhenNode): string { switch (node.type) { case "identifier": return node.name; case "not": - return `!(${encodeWhenAst(node.node)})`; + return `!${encodeWhenOperand(node.node, ["identifier", "not"])}`; case "and": - return `(${encodeWhenAst(node.left)} && ${encodeWhenAst(node.right)})`; + return `${encodeWhenOperand(node.left, ["identifier", "not", "and"])} && ${encodeWhenOperand(node.right, ["identifier", "not"])}`; case "or": - return `(${encodeWhenAst(node.left)} || ${encodeWhenAst(node.right)})`; + return `${encodeWhenAst(node.left)} || ${encodeWhenOperand(node.right, ["identifier", "not", "and"])}`; } } +function encodeWhenOperand( + node: KeybindingWhenNode, + bare: ReadonlyArray, +): string { + return bare.includes(node.type) ? encodeWhenAst(node) : `(${encodeWhenAst(node)})`; +} + const RawKeybindingsEntries = fromLenientJson(Schema.Array(Schema.Unknown)); const RawKeybindingsEntriesPrettyJson = fromJsonStringPretty(Schema.Array(Schema.Unknown)); const decodeKeybindingRuleExit = Schema.decodeUnknownExit(KeybindingRule); diff --git a/apps/server/src/mcp/toolkits/environment/handlers.test.ts b/apps/server/src/mcp/toolkits/environment/handlers.test.ts index b4d39bd41c17f..906bee5ac5e77 100644 --- a/apps/server/src/mcp/toolkits/environment/handlers.test.ts +++ b/apps/server/src/mcp/toolkits/environment/handlers.test.ts @@ -1,11 +1,13 @@ import { expect, it } from "@effect/vitest"; import { - DEFAULT_SERVER_SETTINGS, EnvironmentId, + ProjectId, ProviderInstanceId, ThreadId, type OrchestrationV2ThreadShell, + type ServerSettings, } from "@t3tools/contracts"; +import { compileResolvedKeybindingsConfig, DEFAULT_KEYBINDINGS } from "@t3tools/shared/keybindings"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; @@ -14,6 +16,7 @@ import * as Ref from "effect/Ref"; import * as Stream from "effect/Stream"; import * as Environment from "../../../environment/ServerEnvironment.ts"; +import * as Keybindings from "../../../keybindings.ts"; import * as ThreadCommandExecutor from "../../../orchestration-v2/ThreadCommandExecutor.ts"; import * as ThreadManagement from "../../../orchestration-v2/ThreadManagementService.ts"; import * as Settings from "../../../serverSettings.ts"; @@ -26,46 +29,87 @@ import { EnvironmentToolkit } from "./tools.ts"; const environmentId = EnvironmentId.make("environment:preferences"); const threadId = ThreadId.make("thread:preferences"); -it.effect("refuses a preferences update when the caller's turn ends while it waits", () => - Effect.gen(function* () { - const caller = yield* Ref.make(liveThreadShell(threadId)); - const updates = yield* Ref.make(0); - const checked = yield* Deferred.make(); - const layerDependencies = Layer.mergeAll( - ThreadCommandExecutor.layer, - Layer.succeed(McpInvocationContext.McpInvocationContext, { - environmentId, - requestNamespace: "provider:preferences", - thread: { - threadId, - providerSessionId: "provider:preferences", - providerInstanceId: ProviderInstanceId.make("codex"), - }, - client: undefined, - capabilities: new Set(["orchestration" as const]), - issuedAt: 0, - }), - Layer.mock(ThreadManagement.ThreadManagementService)({ - getThreadShell: () => - Ref.get(caller).pipe(Effect.tap(() => Deferred.succeed(checked, undefined))), - }), - Layer.mock(Environment.ServerEnvironment)({ - getDescriptor: Effect.succeed({ +const projectId = ProjectId.make("project:preferences"); +// Valid at the 256-character limit; a fully parenthesized re-encoding would exceed it. +const longWhen = Array.from({ length: 15 }, () => "terminalFocus").join(" && "); +const longRule = { key: "mod+alt+k", command: "terminal.toggle" as const, when: longWhen }; + +const makeLayer = Effect.fn(function* ( + options: { + readonly onGetThreadShell?: Effect.Effect; + readonly settings?: Parameters[0]; + } = {}, +) { + const { onGetThreadShell = Effect.void, settings = {} } = options; + const caller = yield* Ref.make(liveThreadShell(threadId)); + const writes = yield* Ref.make(0); + const write = (value: A) => Ref.update(writes, (count) => count + 1).pipe(Effect.as(value)); + const snapshot = { + keybindings: compileResolvedKeybindingsConfig([...DEFAULT_KEYBINDINGS, longRule]), + issues: [], + }; + const layer = McpToolAccess.HandlersLayer.layer(EnvironmentHandlers.layer).pipe( + Layer.provideMerge( + Layer.mergeAll( + ThreadCommandExecutor.layer, + Layer.succeed(McpInvocationContext.McpInvocationContext, { environmentId, - label: "Test", - platform: { os: "linux", arch: "x64" }, - serverVersion: "0.0.0", - capabilities: { repositoryIdentity: false }, + requestNamespace: "provider:preferences", + thread: { + threadId, + providerSessionId: "provider:preferences", + providerInstanceId: ProviderInstanceId.make("codex"), + }, + client: undefined, + capabilities: new Set(["orchestration" as const]), + issuedAt: 0, }), - }), - Layer.mock(Settings.ServerSettingsService)({ - getSettings: Effect.succeed(DEFAULT_SERVER_SETTINGS), - updateSettings: () => - Ref.update(updates, (count) => count + 1).pipe(Effect.as(DEFAULT_SERVER_SETTINGS)), - }), - ); + Layer.mock(ThreadManagement.ThreadManagementService)({ + getThreadShell: () => Ref.get(caller).pipe(Effect.tap(() => onGetThreadShell)), + }), + Layer.mock(Environment.ServerEnvironment)({ + getDescriptor: Effect.succeed({ + environmentId, + label: "Test", + platform: { os: "linux", arch: "x64" }, + serverVersion: "0.0.0", + capabilities: { repositoryIdentity: false }, + }), + }), + Settings.ServerSettingsService.layerTest(settings), + Layer.mock(Keybindings.Keybindings)({ + getSnapshot: Effect.succeed(snapshot), + upsertKeybindingRule: () => write(snapshot), + removeKeybindingRule: () => write(snapshot), + }), + ), + ), + ); + return { caller, writes, layer }; +}); + +const call = (...[name, params]: Parameters["handle"]>) => + EnvironmentToolkit.pipe( + Effect.flatMap((toolkit) => + toolkit.handle(name, params).pipe(Stream.unwrap, Stream.runCollect), + ), + Effect.map((results) => results.at(-1)?.result), + ); + +const unchangedSettings = (expected: ServerSettings) => + Settings.ServerSettingsService.pipe( + Effect.flatMap((settings) => settings.getSettings), + Effect.map((current) => expect(current).toEqual(expected)), + ); + +it.effect("refuses a settings update when the caller's turn ends while it waits", () => + Effect.gen(function* () { + const checked = yield* Deferred.make(); + const { caller, layer } = yield* makeLayer({ + onGetThreadShell: Deferred.succeed(checked, undefined), + }); yield* Effect.gen(function* () { - const toolkit = yield* EnvironmentToolkit; + const before = yield* (yield* Settings.ServerSettingsService).getSettings; const executor = yield* ThreadCommandExecutor.ThreadCommandExecutor; const held = yield* Deferred.make(); const release = yield* Deferred.make(); @@ -76,22 +120,101 @@ it.effect("refuses a preferences update when the caller's turn ends while it wai ) .pipe(Effect.forkChild); yield* Deferred.await(held); - const update = yield* toolkit - .handle("t3_environment_preferences_update", { newWorktreesStartFromOrigin: true }) - .pipe(Stream.unwrap, Stream.runCollect, Effect.forkChild); + const update = yield* call("t3_environment_settings_update", { + patch: { newWorktreesStartFromOrigin: true }, + }).pipe(Effect.forkChild); yield* Deferred.await(checked); yield* Ref.update(caller, (shell) => ({ ...shell, activeRunId: null })); yield* Deferred.succeed(release, undefined); yield* Fiber.join(holder); - const result = yield* Fiber.join(update); - expect(result.at(-1)?.result).toMatchObject({ code: "parent_not_active" }); - expect(yield* Ref.get(updates)).toBe(0); - }).pipe( - Effect.provide( - McpToolAccess.HandlersLayer.layer(EnvironmentHandlers.layer).pipe( - Layer.provideMerge(layerDependencies), - ), - ), - ); + expect(yield* Fiber.join(update)).toMatchObject({ code: "parent_not_active" }); + yield* unchangedSettings(before); + }).pipe(Effect.provide(layer)); + }), +); + +it.effect("refuses settings and shortcuts agents may not or cannot write", () => + Effect.gen(function* () { + const { writes, layer } = yield* makeLayer(); + const cases = [ + [ + call("t3_environment_settings_update", { patch: { enableAgentDeviceAccess: true } }), + "capability_denied", + ], + [ + call("t3_environment_settings_update", { + patch: { projectSettingsOverrides: { [projectId]: { enableAgentDeviceAccess: true } } }, + }), + "capability_denied", + ], + [call("t3_environment_settings_update", { patch: { notASetting: true } }), "invalid_request"], + [ + call("t3_environment_settings_update", { patch: { linkedEnvironmentsEnabled: "yes" } }), + "invalid_request", + ], + [call("t3_environment_settings_update", { patch: {} }), "invalid_request"], + [call("t3_environment_settings_read", { keys: ["notASetting"] }), "invalid_request"], + [call("t3_keybinding_upsert", { key: "mod+k", command: "not.a.command" }), "invalid_request"], + [ + call("t3_keybinding_upsert", { key: "mod+k+j", command: "terminal.toggle" }), + "invalid_request", + ], + [ + call("t3_keybinding_remove", { key: "mod+k", command: "terminal.toggle" }), + "invalid_request", + ], + ] as const; + yield* Effect.gen(function* () { + const before = yield* (yield* Settings.ServerSettingsService).getSettings; + for (const [result, code] of cases) expect(yield* result).toMatchObject({ code }); + expect(yield* Ref.get(writes)).toBe(0); + yield* unchangedSettings(before); + }).pipe(Effect.provide(layer)); + }), +); + +it.effect("lets agents give up browser and device access but not take back a denial", () => + Effect.gen(function* () { + const { layer } = yield* makeLayer({ + settings: { + enableAgentBrowserAccess: true, + projectSettingsOverrides: { [projectId]: { enableAgentBrowserAccess: false } }, + }, + }); + yield* Effect.gen(function* () { + const settings = yield* Settings.ServerSettingsService; + const before = yield* settings.getSettings; + for (const entry of [null, {}]) + expect( + yield* call("t3_environment_settings_update", { + patch: { projectSettingsOverrides: { [projectId]: entry } }, + }), + ).toMatchObject({ code: "capability_denied" }); + yield* unchangedSettings(before); + yield* call("t3_environment_settings_update", { patch: { enableAgentBrowserAccess: false } }); + expect((yield* settings.getSettings).enableAgentBrowserAccess).toBe(false); + }).pipe(Effect.provide(layer)); + }), +); + +it.effect("lists every loaded shortcut in a form that writes back", () => + Effect.gen(function* () { + const { writes, layer } = yield* makeLayer(); + yield* Effect.gen(function* () { + const read = yield* call("t3_keybindings_read", {}); + const listed = (read as { keybindings: ReadonlyArray }).keybindings; + expect(listed.find((rule) => rule.key === longRule.key)).toEqual(longRule); + expect( + yield* call("t3_keybinding_upsert", { ...longRule, key: "mod+alt+j", replace: longRule }), + ).toHaveProperty("keybindings"); + expect( + yield* call("t3_keybinding_remove", { + key: "MOD+SHIFT+B", + command: "threadPanel.toggle", + when: "!terminalFocus", + }), + ).toHaveProperty("keybindings"); + expect(yield* Ref.get(writes)).toBe(2); + }).pipe(Effect.provide(layer)); }), ); diff --git a/apps/server/src/mcp/toolkits/environment/handlers.ts b/apps/server/src/mcp/toolkits/environment/handlers.ts index fb1716885d6e8..f23af7aaba158 100644 --- a/apps/server/src/mcp/toolkits/environment/handlers.ts +++ b/apps/server/src/mcp/toolkits/environment/handlers.ts @@ -1,6 +1,18 @@ -import { OrchestratorMcpFailure, type ServerSettings } from "@t3tools/contracts"; +import { + KeybindingRule, + OrchestratorMcpFailure, + ProjectId, + ServerSettings, + ServerSettingsPatch, + STATIC_KEYBINDING_COMMANDS, + type ResolvedKeybindingsConfig, +} from "@t3tools/contracts"; +import { compileResolvedKeybindingRule } from "@t3tools/shared/keybindings"; +import { resolveProjectSettings } from "@t3tools/shared/projectSettings"; import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; import * as Environment from "../../../environment/ServerEnvironment.ts"; +import * as Keybindings from "../../../keybindings.ts"; import * as ThreadCommandExecutor from "../../../orchestration-v2/ThreadCommandExecutor.ts"; import * as Settings from "../../../serverSettings.ts"; import * as McpInvocationContext from "../../McpInvocationContext.ts"; @@ -29,6 +41,64 @@ export function preferences(settings: ServerSettings) { }, }; } + +const SETTINGS_KEYS = new Set(Object.keys(ServerSettings.fields)); +const PATCH_KEYS = new Set(Object.keys(ServerSettingsPatch.fields)); + +const invalid = (message: string) => + new OrchestratorMcpFailure({ code: "invalid_request", message }); +const decodePatch = Schema.decodeUnknownEffect(ServerSettingsPatch); +const encodeSettings = Schema.encodeEffect(ServerSettings); +const decodeKeybinding = Schema.decodeUnknownEffect(KeybindingRule); + +const settingsView = (settings: ServerSettings, keys: ReadonlyArray | undefined) => + encodeSettings(Settings.redactServerSettingsForClient(settings, { secretReferences: true })).pipe( + Effect.mapError(unavailable), + Effect.map((encoded) => + keys === undefined + ? encoded + : Object.fromEntries(Object.entries(encoded).filter(([key]) => keys.includes(key))), + ), + ); + +/** Whether `next` lets agents use the browser or a device anywhere `current` did not. */ +function grantsAgentAccess(current: ServerSettings, next: ServerSettings): boolean { + const access = (settings: ServerSettings, projectId: ProjectId | null) => { + const resolved = resolveProjectSettings(settings, projectId).settings; + return [resolved.enableAgentBrowserAccess, resolved.enableAgentDeviceAccess]; + }; + const projectIds = new Set([ + ...Object.keys(current.projectSettingsOverrides), + ...Object.keys(next.projectSettingsOverrides), + ]); + return [null, ...[...projectIds].map((id) => ProjectId.make(id))].some((projectId) => { + const before = access(current, projectId); + return access(next, projectId).some((granted, index) => granted && !before[index]); + }); +} + +const keybindingsView = (keybindings: ResolvedKeybindingsConfig) => + keybindings.map(Keybindings.keybindingRuleText); + +/** Rejects a rule the service would store as a broken entry, as the Settings page path does. */ +const validRule = (input: unknown) => + decodeKeybinding(input).pipe( + Effect.mapError((error) => invalid(`Invalid shortcut: ${error.message}`)), + Effect.filterOrFail( + (rule) => compileResolvedKeybindingRule(rule) !== null, + () => invalid("Invalid shortcut: the key or `when` does not parse."), + ), + ); + +/** The listed rule a replace or remove target names, however the agent spelled it. */ +const listedRule = ( + keybindings: ResolvedKeybindingsConfig, + target: { readonly key: string; readonly command: string; readonly when?: string | undefined }, +) => + Effect.fromNullishOr( + keybindingsView(keybindings).find((rule) => Keybindings.isSameKeybindingRule(rule, target)), + ).pipe(Effect.mapError(() => invalid("No such shortcut. `t3_keybindings_read` lists them."))); + const access = Effect.gen(function* () { const context = yield* readCaller(); const environment = yield* Environment.ServerEnvironment; @@ -38,8 +108,28 @@ const access = Effect.gen(function* () { code: "capability_denied", message: "This credential belongs to another environment.", }); - return { ...context, descriptor, settings: yield* Settings.ServerSettingsService }; + return { + ...context, + descriptor, + settings: yield* Settings.ServerSettingsService, + keybindings: yield* Keybindings.Keybindings, + }; +}); + +/** Runs a write under the caller thread's lock, rechecking access once the lock is held. */ +const writeLocked = Effect.fn("EnvironmentTools.writeLocked")(function* ( + check: Effect.Effect, + write: Effect.Effect, +) { + const scope = yield* McpInvocationContext.McpInvocationContext; + const executor = yield* ThreadCommandExecutor.ThreadCommandExecutor; + // The turn may have ended, or the thread's modes changed, while this waited for the lock. + const update = check.pipe(Effect.andThen(write)); + return yield* scope.thread === undefined + ? update + : executor.withLock(scope.thread.threadId, update); }); + export const layer = McpToolAccess.toLayer(EnvironmentToolkit, { t3_environment_read: McpToolAccess.reads(() => Effect.gen(function* () { @@ -54,21 +144,103 @@ export const layer = McpToolAccess.toLayer(EnvironmentToolkit, { }; }), ), - t3_environment_preferences_update: McpToolAccess.writesEnvironment((patch, check) => + t3_environment_settings_read: McpToolAccess.reads(({ keys }) => + Effect.gen(function* () { + const unknown = (keys ?? []).filter((key) => !SETTINGS_KEYS.has(key)); + if (unknown.length > 0) return yield* invalid(`Unknown settings: ${unknown.join(", ")}.`); + const { settings } = yield* access; + const current = yield* settings.getSettings.pipe(Effect.mapError(unavailable)); + return { settings: yield* settingsView(current, keys) }; + }), + ), + t3_environment_settings_update: McpToolAccess.writesEnvironment(({ patch }, check) => + Effect.gen(function* () { + const keys = Object.keys(patch); + if (keys.length === 0) return yield* invalid("`patch` is empty."); + const unknown = keys.filter((key) => !PATCH_KEYS.has(key)); + if (unknown.length > 0) + return yield* invalid(`Unknown or read-only settings: ${unknown.join(", ")}.`); + // Device hosts need the local-host filtering only the RPC path applies. + if (keys.includes("deviceHosts")) + return yield* new OrchestratorMcpFailure({ + code: "capability_denied", + message: "Only the user can change deviceHosts, in Settings.", + }); + const decoded = yield* decodePatch(patch).pipe( + Effect.mapError((error) => invalid(`Invalid settings: ${error.message}`)), + ); + return yield* writeLocked( + check, + Effect.gen(function* () { + const { settings } = yield* access; + const next = yield* settings + .updateSettings(decoded, (current, patched) => + grantsAgentAccess(current, patched) + ? Effect.fail( + new OrchestratorMcpFailure({ + code: "capability_denied", + message: + "Only the user can grant agents browser or device access, in Settings.", + }), + ) + : Effect.void, + ) + .pipe(Effect.catchTags({ ServerSettingsError: () => Effect.fail(unavailable()) })); + return { settings: yield* settingsView(next, keys) }; + }), + ); + }), + ), + t3_keybindings_read: McpToolAccess.reads(() => + Effect.gen(function* () { + const { keybindings } = yield* access; + const snapshot = yield* keybindings.getSnapshot.pipe(Effect.mapError(unavailable)); + return { + keybindings: keybindingsView(snapshot.keybindings), + commands: [...STATIC_KEYBINDING_COMMANDS], + issues: snapshot.issues.map((issue) => issue.message), + }; + }), + ), + t3_keybinding_upsert: McpToolAccess.writesEnvironment(({ replace, ...input }, check) => Effect.gen(function* () { - const scope = yield* McpInvocationContext.McpInvocationContext; - const executor = yield* ThreadCommandExecutor.ThreadCommandExecutor; - const update = Effect.gen(function* () { - // The turn may have ended, or the thread's modes changed, while this waited for the lock. - yield* check; - const { settings } = yield* access; - return preferences( - yield* settings.updateSettings(patch).pipe(Effect.mapError(unavailable)), - ); - }); - return yield* scope.thread === undefined - ? update - : executor.withLock(scope.thread.threadId, update); + const rule = yield* validRule(input); + return yield* writeLocked( + check, + Effect.gen(function* () { + const { keybindings } = yield* access; + const current = yield* keybindings.getSnapshot.pipe(Effect.mapError(unavailable)); + const target = + replace === undefined ? undefined : yield* listedRule(current.keybindings, replace); + const next = yield* keybindings + .upsertKeybindingRule(target ? { ...rule, replace: target } : rule) + .pipe(Effect.mapError(unavailable)); + const commands = new Set([rule.command, target?.command]); + return { + keybindings: keybindingsView( + next.keybindings.filter((binding) => commands.has(binding.command)), + ), + }; + }), + ); }), ), + t3_keybinding_remove: McpToolAccess.writesEnvironment((input, check) => + writeLocked( + check, + Effect.gen(function* () { + const { keybindings } = yield* access; + const current = yield* keybindings.getSnapshot.pipe(Effect.mapError(unavailable)); + const target = yield* listedRule(current.keybindings, input); + const next = yield* keybindings + .removeKeybindingRule(target) + .pipe(Effect.mapError(unavailable)); + return { + keybindings: keybindingsView( + next.keybindings.filter((binding) => binding.command === target.command), + ), + }; + }), + ), + ), }); diff --git a/apps/server/src/mcp/toolkits/environment/tools.ts b/apps/server/src/mcp/toolkits/environment/tools.ts index 9e10380295de2..0b45d07b5fba8 100644 --- a/apps/server/src/mcp/toolkits/environment/tools.ts +++ b/apps/server/src/mcp/toolkits/environment/tools.ts @@ -1,15 +1,14 @@ import { - BackgroundActivityProfile, BackgroundActivityProfileSelection, ExecutionEnvironmentDescriptor, OrchestratorMcpEnvironmentTarget, OrchestratorMcpFailure, ServerSettings, - ServerSettingsPatch, } from "@t3tools/contracts"; import * as Schema from "effect/Schema"; import { Tool, Toolkit } from "effect/ai"; import * as ServerEnvironment from "../../../environment/ServerEnvironment.ts"; +import * as Keybindings from "../../../keybindings.ts"; import * as ThreadCommandExecutor from "../../../orchestration-v2/ThreadCommandExecutor.ts"; import * as ThreadManagementService from "../../../orchestration-v2/ThreadManagementService.ts"; import * as Settings from "../../../serverSettings.ts"; @@ -35,9 +34,25 @@ const shared = { ThreadManagementService.ThreadManagementService, ServerEnvironment.ServerEnvironment, Settings.ServerSettingsService, + Keybindings.Keybindings, ThreadCommandExecutor.ThreadCommandExecutor, ], }; +// Settings and keybindings travel as plain JSON; their full schemas would bloat every tool list. +const SettingsObject = Schema.Record(Schema.String, Schema.Unknown); +const KeybindingFields = { + key: Schema.String.annotate({ + description: 'e.g. "mod+shift+k"; mod is cmd on macOS, ctrl elsewhere.', + }), + command: Schema.String.annotate({ description: "From `t3_keybindings_read`." }), + when: Schema.optionalKey(Schema.String.annotate({ description: 'e.g. "!terminalFocus".' })), +}; +const KeybindingRuleView = Schema.Struct({ + key: Schema.String, + command: Schema.String, + when: Schema.optionalKey(Schema.String), +}); + const EnvironmentReadTool = Tool.make("t3_environment_read", { ...shared, description: @@ -53,18 +68,66 @@ const EnvironmentReadTool = Tool.make("t3_environment_read", { }) .annotate(Tool.Readonly, true) .annotate(Tool.Destructive, false); -const EnvironmentPreferencesTool = Tool.make("t3_environment_preferences_update", { +const SettingsReadTool = Tool.make("t3_environment_settings_read", { + ...shared, + description: + "Read this server's settings, as on the Settings page. Secrets come back redacted. Pass `keys` to read only some.", + parameters: Schema.Struct({ + environmentId: OrchestratorMcpEnvironmentTarget, + keys: Schema.optionalKey(Schema.Array(Schema.String)), + }), + success: Schema.Struct({ settings: SettingsObject }), +}) + .annotate(Tool.Readonly, true) + .annotate(Tool.Destructive, false); +const SettingsUpdateTool = Tool.make("t3_environment_settings_update", { + ...shared, + description: + "Change this server's settings. `patch` uses the keys and shapes of `t3_environment_settings_read`; omitted keys are unchanged. Live full-access or default caller thread only. Agent browser and device access stay the user's to grant.", + parameters: Schema.Struct({ + environmentId: OrchestratorMcpEnvironmentTarget, + patch: SettingsObject, + }), + success: Schema.Struct({ settings: SettingsObject }), +}).annotate(Tool.Destructive, true); +const KeybindingsReadTool = Tool.make("t3_keybindings_read", { + ...shared, + description: "List this server's keyboard shortcuts and every command a shortcut can run.", + parameters: Schema.Struct({ environmentId: OrchestratorMcpEnvironmentTarget }), + success: Schema.Struct({ + keybindings: Schema.Array(KeybindingRuleView), + commands: Schema.Array(Schema.String), + issues: Schema.Array(Schema.String), + }), +}) + .annotate(Tool.Readonly, true) + .annotate(Tool.Destructive, false); +const KeybindingUpsertTool = Tool.make("t3_keybinding_upsert", { + ...shared, + description: + "Add a keyboard shortcut, or change one by passing the current binding as `replace`. Live full-access or default caller thread only.", + parameters: Schema.Struct({ + environmentId: OrchestratorMcpEnvironmentTarget, + ...KeybindingFields, + replace: Schema.optionalKey(Schema.Struct(KeybindingFields)), + }), + success: Schema.Struct({ keybindings: Schema.Array(KeybindingRuleView) }), +}).annotate(Tool.Destructive, true); +const KeybindingRemoveTool = Tool.make("t3_keybinding_remove", { ...shared, description: - "Update environment-wide preferences. Live full-access or default caller thread only. Omitted fields are unchanged; `customInstructions: ''` clears it.", + "Remove a keyboard shortcut, matched exactly as `t3_keybindings_read` lists it. Live full-access or default caller thread only.", parameters: Schema.Struct({ environmentId: OrchestratorMcpEnvironmentTarget, - defaultThreadEnvMode: ServerSettingsPatch.fields.defaultThreadEnvMode, - newWorktreesStartFromOrigin: ServerSettingsPatch.fields.newWorktreesStartFromOrigin, - enableProviderUpdateChecks: ServerSettingsPatch.fields.enableProviderUpdateChecks, - backgroundActivity: Schema.optionalKey(Schema.Struct({ profile: BackgroundActivityProfile })), - sourceControlWritingStyle: ServerSettingsPatch.fields.sourceControlWritingStyle, + ...KeybindingFields, }), - success: Schema.Struct(PreferenceFields), + success: Schema.Struct({ keybindings: Schema.Array(KeybindingRuleView) }), }).annotate(Tool.Destructive, true); -export const EnvironmentToolkit = Toolkit.make(EnvironmentReadTool, EnvironmentPreferencesTool); +export const EnvironmentToolkit = Toolkit.make( + EnvironmentReadTool, + SettingsReadTool, + SettingsUpdateTool, + KeybindingsReadTool, + KeybindingUpsertTool, + KeybindingRemoveTool, +); diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index 7b63b7efc0b65..9868b8f065332 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -2001,6 +2001,8 @@ export const CLAUDE_READ_ONLY_T3_MCP_ALLOWED_TOOLS: ReadonlyArray = [ "mcp__t3-code__t3_thread_search", "mcp__t3-code__t3_preview_list", "mcp__t3-code__t3_environment_read", + "mcp__t3-code__t3_environment_settings_read", + "mcp__t3-code__t3_keybindings_read", "mcp__t3-code__t3_environment_links", "mcp__t3-code__html_preview", "mcp__t3-code__html_render", diff --git a/apps/server/src/provider/AgentContextBudget.test.ts b/apps/server/src/provider/AgentContextBudget.test.ts index 8cdd52d202f12..24a0d9d06ad0a 100644 --- a/apps/server/src/provider/AgentContextBudget.test.ts +++ b/apps/server/src/provider/AgentContextBudget.test.ts @@ -13,6 +13,7 @@ import { ServerConfig } from "../config.ts"; import { DeviceService } from "../device/DeviceService.ts"; import { ServerEnvironment } from "../environment/ServerEnvironment.ts"; import { GitWorkflowService } from "../git/GitWorkflowService.ts"; +import { Keybindings } from "../keybindings.ts"; import * as McpHttpServer from "../mcp/McpHttpServer.ts"; import { PreviewAutomationBroker } from "../mcp/PreviewAutomationBroker.ts"; import { @@ -53,6 +54,7 @@ const toolHandlerServices = Layer.mergeAll( Layer.mock(DocumentText)({}), Layer.mock(GitVcsDriver)({}), Layer.mock(GitWorkflowService)({}), + Layer.mock(Keybindings)({}), Layer.mock(ManagedProjectFolders)({ namedProjectsRoot: "" }), Layer.mock(McpProviderSessions)({}), Layer.mock(OrchestratorV2)({}), diff --git a/apps/server/src/provider/agentContextBudget.json b/apps/server/src/provider/agentContextBudget.json index 4439c50940722..e2cbb1f643716 100644 --- a/apps/server/src/provider/agentContextBudget.json +++ b/apps/server/src/provider/agentContextBudget.json @@ -1,5 +1,5 @@ { "claudeSystemAppendBytes": 5597, "codexAdditionalContextBytes": 7327, - "mcpToolListJsonBytes": 48217 + "mcpToolListJsonBytes": 49649 } diff --git a/apps/server/src/serverSettings.test.ts b/apps/server/src/serverSettings.test.ts index 347b43dd6f44c..d0bf620c66a10 100644 --- a/apps/server/src/serverSettings.test.ts +++ b/apps/server/src/serverSettings.test.ts @@ -486,6 +486,24 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("server settings" ); assert.equal(afterProviderSave.responseStreamingMode, "paragraph"); assert.equal(afterProviderSave.providerInstances[instanceId]?.displayName, "Kilo"); + + // A write's check judges the edit it would overwrite, and its failure leaves the file alone. + yield* writeFileStringAtomically({ + filePath: config.settingsPath, + contents: `{ "responseStreamingMode": "turn" }`, + }); + const refused = yield* serverSettings + .updateSettings({ responseStreamingMode: "paragraph" }, (current, next) => + current.responseStreamingMode === "turn" && next.responseStreamingMode === "paragraph" + ? Effect.fail("refused" as const) + : Effect.void, + ) + .pipe(Effect.flip); + assert.equal(refused, "refused"); + const afterRefusal = yield* decodeServerSettingsJson( + yield* fs.readFileString(config.settingsPath), + ); + assert.equal(afterRefusal.responseStreamingMode, "turn"); }).pipe(Effect.provide(layerServerSettings())), ); diff --git a/apps/server/src/serverSettings.ts b/apps/server/src/serverSettings.ts index 251becba12f6c..aa749e123e41d 100644 --- a/apps/server/src/serverSettings.ts +++ b/apps/server/src/serverSettings.ts @@ -262,9 +262,11 @@ export class ServerSettingsService extends Context.Service< readonly getSettings: Effect.Effect; - readonly updateSettings: ( + /** `check` runs in the write lock on the settings the patch applies to; failing it aborts the write. */ + readonly updateSettings: ( patch: ServerSettingsPatch, - ) => Effect.Effect; + check?: (current: ServerSettings, next: ServerSettings) => Effect.Effect, + ) => Effect.Effect>; readonly updateProviderInstance: ( mutation: ProviderInstanceMutation, @@ -307,9 +309,9 @@ const makeTest = Effect.fn("serverSettings.makeTest")(function* ( const writeSemaphore = yield* Semaphore.make(1); const getSettings = Ref.get(currentSettingsRef).pipe(Effect.map(resolveTextGenerationProvider)); - const updateTestSettings = ( - update: (current: ServerSettings) => Effect.Effect, - ): Effect.Effect => + const updateTestSettings = ( + update: (current: ServerSettings) => Effect.Effect, + ): Effect.Effect => writeSemaphore.withPermits(1)( Ref.get(currentSettingsRef).pipe( Effect.flatMap(update), @@ -324,10 +326,11 @@ const makeTest = Effect.fn("serverSettings.makeTest")(function* ( start: Effect.void, ready: Effect.void, getSettings, - updateSettings: (patch) => - updateTestSettings((currentSettings) => - Effect.succeed(applyServerSettingsPatch(currentSettings, patch)), - ), + updateSettings: (patch, check) => + updateTestSettings((currentSettings) => { + const next = applyServerSettingsPatch(currentSettings, patch); + return (check?.(currentSettings, next) ?? Effect.void).pipe(Effect.as(next)); + }), updateProviderInstance: (mutation, patch = {}) => updateTestSettings((currentSettings) => Effect.gen(function* () { @@ -1183,10 +1186,10 @@ const make = Effect.gen(function* () { ); }; - const updateAndPersistSettings = ( + const updateAndPersistSettings = ( patch: ServerSettingsPatch, - update: (current: ServerSettings) => Effect.Effect, - ): Effect.Effect => + update: (current: ServerSettings) => Effect.Effect, + ): Effect.Effect => writeSemaphore.withPermits(1)( Effect.gen(function* () { const { settings: current, parseFailure } = yield* reloadSettings; @@ -1367,12 +1370,14 @@ const make = Effect.gen(function* () { start, ready: Deferred.await(startedDeferred), getSettings: getMaterializedSettings, - updateSettings: (patch) => - updateAndPersistSettings(patch, (current) => - ensureSecretProviderWritesAllowed(patch, settingsPath).pipe( - Effect.as(applyServerSettingsPatch(current, patch)), - ), - ), + updateSettings: (patch, check) => + updateAndPersistSettings(patch, (current) => { + const next = applyServerSettingsPatch(current, patch); + return ensureSecretProviderWritesAllowed(patch, settingsPath).pipe( + Effect.andThen(check?.(current, next) ?? Effect.void), + Effect.as(next), + ); + }), updateProviderInstance: (mutation, patch = {}) => updateAndPersistSettings(patch, (current) => Effect.gen(function* () { diff --git a/evals/mcp-tool-use/cases/settings.ndjson b/evals/mcp-tool-use/cases/settings.ndjson new file mode 100644 index 0000000000000..258289e30dec7 --- /dev/null +++ b/evals/mcp-tool-use/cases/settings.ndjson @@ -0,0 +1 @@ +{"id": "labs-setting-uses-settings-update", "area": "settings", "kind": "bad", "pattern": "edit settings.json by hand", "experience": "Asked to turn on the Linked environments Labs switch on a headless box, an agent had no tool for it and told the user to write the server's settings.json by hand.", "rule": "t3_environment_settings_update: Change this server's settings.", "privacy": "commit-safe", "setup": {"role": "top", "mocks": {"t3_environment_settings_read": {"settings": {"linkedEnvironmentsEnabled": false, "guestSharingEnabled": false, "promptSuggestionsEnabled": false}}, "t3_environment_settings_update": {"settings": {"linkedEnvironmentsEnabled": true}}}}, "prompt": "Turn on the linked environments beta on this machine. There's no T3 Code window open on it.", "expect": {"calls": [{"tool": "t3_environment_settings_update", "args": {"patch.linkedEnvironmentsEnabled": true}}], "shellMustNot": ["settings\\.json"]}, "maxSteps": 6} diff --git a/packages/client-runtime/src/t3ToolSummary.ts b/packages/client-runtime/src/t3ToolSummary.ts index 1d57c1f0c91b7..09142690a6111 100644 --- a/packages/client-runtime/src/t3ToolSummary.ts +++ b/packages/client-runtime/src/t3ToolSummary.ts @@ -350,10 +350,10 @@ export function summarizeT3ToolCalls( ); break; case "environment-read": - label = phrase("Checked", "check", `environment preferences ${times}`); + label = phrase("Checked", "check", `environment settings ${times}`); break; case "environment-update": - label = phrase("Updated", "update", `environment preferences ${times}`); + label = phrase("Updated", "update", `environment settings ${times}`); break; case "environment-links": label = phrase("Listed", "list", `linked environments ${times}`); diff --git a/packages/shared/src/t3McpToolPresentation.ts b/packages/shared/src/t3McpToolPresentation.ts index 7a6c2fab91187..9742639f9a801 100644 --- a/packages/shared/src/t3McpToolPresentation.ts +++ b/packages/shared/src/t3McpToolPresentation.ts @@ -350,8 +350,24 @@ const T3_MCP_TOOLS: Readonly> = { ["Forget", "Forgetting", "Forgot", "a linked environment"], "environment-unlink", ), - t3_environment_preferences_update: tool( - ["Update", "Updating", "Updated", "environment preferences"], + t3_environment_settings_read: tool( + ["Read", "Reading", "Read", "environment settings"], + "environment-read", + ), + t3_environment_settings_update: tool( + ["Update", "Updating", "Updated", "environment settings"], + "environment-update", + ), + t3_keybindings_read: tool( + ["List", "Listing", "Listed", "keyboard shortcuts"], + "environment-read", + ), + t3_keybinding_upsert: tool( + ["Set", "Setting", "Set", "a keyboard shortcut"], + "environment-update", + ), + t3_keybinding_remove: tool( + ["Remove", "Removing", "Removed", "a keyboard shortcut"], "environment-update", ), t3_thread_launch: tool(["Launch", "Launching", "Launched", "a project thread"], "thread-create"), From e0b2dc8ede38cab98432ff6d5bec4fcb3333d36a Mon Sep 17 00:00:00 2001 From: Batch Processor <46352227+batchema@users.noreply.github.com> Date: Fri, 13 Nov 2026 10:58:04 -0500 Subject: [PATCH 08/20] feat: agents can run app commands in the user's window (#7) --- apps/server/src/appControl/AppControl.test.ts | 61 ++++++ apps/server/src/appControl/AppControl.ts | 176 ++++++++++++++++++ apps/server/src/auth/RpcAuthorization.ts | 2 + .../mcp/toolkits/environment/handlers.test.ts | 32 +++- .../src/mcp/toolkits/environment/handlers.ts | 39 ++++ .../src/mcp/toolkits/environment/tools.ts | 13 ++ .../src/observability/RpcInstrumentation.ts | 2 + .../src/provider/AgentContextBudget.test.ts | 2 + .../src/provider/agentContextBudget.json | 2 +- apps/server/src/server.ts | 8 +- apps/server/src/ws.test.ts | 2 + apps/server/src/ws.ts | 28 ++- apps/web/src/appInit.tsx | 2 + apps/web/src/components/AppSidebarLayout.tsx | 12 +- apps/web/src/components/RightPanelTabs.tsx | 21 ++- apps/web/src/components/Sidebar.tsx | 56 +++--- .../src/components/chat/useChatShortcuts.ts | 14 ++ .../pullRequest/PullRequestDetailPanel.tsx | 18 +- apps/web/src/components/usage/UsagePage.tsx | 25 ++- apps/web/src/lib/appControl.ts | 77 ++++++++ .../src/shortcuts/dispatcher.browser.test.ts | 41 ++-- apps/web/src/shortcuts/dispatcher.ts | 35 ++++ evals/mcp-tool-use/cases/settings.ndjson | 1 + packages/client-runtime/src/rpc/client.ts | 1 + packages/client-runtime/src/t3ToolSummary.ts | 3 + packages/contracts/src/appControl.ts | 83 +++++++++ packages/contracts/src/index.ts | 1 + packages/contracts/src/rpc.ts | 21 +++ packages/shared/src/t3McpToolPresentation.ts | 2 + 29 files changed, 714 insertions(+), 66 deletions(-) create mode 100644 apps/server/src/appControl/AppControl.test.ts create mode 100644 apps/server/src/appControl/AppControl.ts create mode 100644 apps/web/src/lib/appControl.ts create mode 100644 packages/contracts/src/appControl.ts diff --git a/apps/server/src/appControl/AppControl.test.ts b/apps/server/src/appControl/AppControl.test.ts new file mode 100644 index 0000000000000..311676b3ffcba --- /dev/null +++ b/apps/server/src/appControl/AppControl.test.ts @@ -0,0 +1,61 @@ +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; +import { expect, it } from "@effect/vitest"; +import { AuthSessionId } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; +import * as Option from "effect/Option"; +import * as Stream from "effect/Stream"; +import * as TestClock from "effect/testing/TestClock"; + +import * as AppControl from "./AppControl.ts"; + +const makeAppControl = AppControl.make.pipe(Effect.provide(NodeCrypto.layer)); +const desktop = { sessionId: AuthSessionId.make("desktop"), windowId: "socket-a:0" }; +const browser = { sessionId: AuthSessionId.make("browser"), windowId: "socket-b:0" }; +// Another tab of the same browser: same session and RPC client id, its own socket. +const browserTab = { ...browser, windowId: "socket-c:0" }; + +it.effect("runs a command in the window used most recently and returns its answer", () => + Effect.gen(function* () { + const appControl = yield* makeAppControl; + const desktopRequests = yield* appControl.connect(desktop, false); + const browserRequests = yield* appControl.connect(browser, true); + // A tab connecting in the background doesn't take over from the one in use. + yield* appControl.connect(browserTab, false).pipe(Effect.asVoid); + const toBrowser = yield* appControl.run("sidebar.toggle").pipe(Effect.forkChild); + const browserRequest = Option.getOrThrow(yield* Stream.runHead(browserRequests)); + yield* appControl.respond(browser.sessionId, { + requestId: browserRequest.requestId, + result: "ran", + }); + expect(yield* Fiber.join(toBrowser)).toBe("ran"); + yield* appControl.reportFocus(desktop, true); + const run = yield* appControl.run("terminal.toggle").pipe(Effect.forkChild); + const request = Option.getOrThrow(yield* Stream.runHead(desktopRequests)); + expect(request.command).toBe("terminal.toggle"); + // Another session cannot answer for this window. + yield* appControl.respond(browser.sessionId, { requestId: request.requestId, result: "ran" }); + yield* appControl.respond(desktop.sessionId, { + requestId: request.requestId, + result: "not-handled", + }); + expect(yield* Fiber.join(run)).toBe("not-handled"); + }).pipe(Effect.scoped), +); + +it.effect("fails when no window is open or the window does not answer", () => + Effect.gen(function* () { + const appControl = yield* makeAppControl; + yield* Effect.scoped(appControl.connect(desktop, true).pipe(Effect.asVoid)); + expect(yield* appControl.run("terminal.toggle").pipe(Effect.flip)).toBeInstanceOf( + AppControl.AppControlNoWindowError, + ); + const requests = yield* appControl.connect(desktop, true); + const run = yield* appControl.run("terminal.toggle").pipe(Effect.forkChild); + yield* Stream.runHead(requests); + yield* TestClock.adjust("5 seconds"); + expect(yield* Fiber.join(run).pipe(Effect.flip)).toBeInstanceOf( + AppControl.AppControlTimeoutError, + ); + }).pipe(Effect.scoped), +); diff --git a/apps/server/src/appControl/AppControl.ts b/apps/server/src/appControl/AppControl.ts new file mode 100644 index 0000000000000..16206a237f779 --- /dev/null +++ b/apps/server/src/appControl/AppControl.ts @@ -0,0 +1,176 @@ +import type { + AppCommand, + AppControlRequest, + AppControlResponseInput, + AppControlResult, + AuthSessionId, +} from "@t3tools/contracts"; +import * as Context from "effect/Context"; +import * as SecureRandom from "effect/crypto/SecureRandom"; +import * as Deferred from "effect/Deferred"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Queue from "effect/Queue"; +import * as Ref from "effect/Ref"; +import * as Schema from "effect/Schema"; +import type * as Scope from "effect/Scope"; +import * as Stream from "effect/Stream"; + +/** One window's connection to this server. */ +export interface AppControlClient { + readonly sessionId: AuthSessionId; + /** Unique per socket and RPC client, since tabs share a session. */ + readonly windowId: string; +} + +export class AppControlNoWindowError extends Schema.TaggedError()( + "AppControlNoWindowError", + {}, +) {} + +export class AppControlTimeoutError extends Schema.TaggedError()( + "AppControlTimeoutError", + {}, +) {} + +const RESPONSE_TIMEOUT = "5 seconds"; + +export class AppControl extends Context.Service< + AppControl, + { + /** Registers a window; the commands sent to it arrive until the scope closes. */ + readonly connect: ( + client: AppControlClient, + focused: boolean, + ) => Effect.Effect, never, Scope.Scope>; + readonly reportFocus: (client: AppControlClient, focused: boolean) => Effect.Effect; + readonly respond: ( + sessionId: AuthSessionId, + response: AppControlResponseInput, + ) => Effect.Effect; + /** Runs a command in the window used most recently, returning what the window answered. */ + readonly run: ( + command: AppCommand, + ) => Effect.Effect; + } +>()("t3/appControl/AppControl") {} + +interface Window { + readonly sessionId: AuthSessionId; + readonly queue: Queue.Queue; + readonly focusOrder: number; +} + +interface Pending { + readonly sessionId: AuthSessionId; + readonly deferred: Deferred.Deferred; +} + +interface State { + readonly windows: ReadonlyMap; + readonly pending: ReadonlyMap; + readonly focusSequence: number; +} + +const windowKey = (client: AppControlClient) => `${client.sessionId}:${client.windowId}`; + +export const make = Effect.gen(function* () { + const random = yield* SecureRandom.SecureRandom; + const state = yield* Ref.make({ + windows: new Map(), + pending: new Map(), + focusSequence: 0, + }); + + /** Marks a window as the one used most recently. */ + const focusWindow = (current: State, key: string, window: Omit): State => { + const focusSequence = current.focusSequence + 1; + const windows = new Map(current.windows).set(key, { ...window, focusOrder: focusSequence }); + return { ...current, windows, focusSequence }; + }; + + const connect: AppControl["Service"]["connect"] = (client, focused) => + Effect.acquireRelease( + Effect.gen(function* () { + const queue = yield* Queue.unbounded(); + const window = { sessionId: client.sessionId, queue }; + // A window connecting in the background ranks below every window used before. + yield* Ref.update(state, (current) => + focused + ? focusWindow(current, windowKey(client), window) + : { + ...current, + windows: new Map(current.windows).set(windowKey(client), { + ...window, + focusOrder: 0, + }), + }, + ); + return queue; + }), + (queue) => + Ref.update(state, (current) => { + if (current.windows.get(windowKey(client))?.queue !== queue) return current; + const windows = new Map(current.windows); + windows.delete(windowKey(client)); + return { ...current, windows }; + }), + ).pipe(Effect.map((queue) => Stream.fromQueue(queue))); + + const reportFocus: AppControl["Service"]["reportFocus"] = (client, focused) => + Ref.update(state, (current) => { + const window = current.windows.get(windowKey(client)); + return focused && window !== undefined + ? focusWindow(current, windowKey(client), window) + : current; + }); + + const respond: AppControl["Service"]["respond"] = Effect.fn("AppControl.respond")( + function* (sessionId, response) { + const pending = yield* Ref.get(state).pipe( + Effect.map((current) => current.pending.get(response.requestId)), + ); + if (pending?.sessionId !== sessionId) return; + yield* Deferred.succeed(pending.deferred, response.result); + }, + ); + + const run: AppControl["Service"]["run"] = Effect.fn("AppControl.run")(function* (command) { + const requestId = yield* random.uuidV4(); + const deferred = yield* Deferred.make(); + const target = yield* Ref.modify(state, (current) => { + const window = Array.from(current.windows.values()).reduce( + (latest, next) => + latest === undefined || next.focusOrder > latest.focusOrder ? next : latest, + undefined, + ); + if (window === undefined) return [undefined, current] as const; + const pending = new Map(current.pending).set(requestId, { + sessionId: window.sessionId, + deferred, + }); + return [window, { ...current, pending }] as const; + }); + if (target === undefined) return yield* new AppControlNoWindowError(); + const removePending = Ref.update(state, (current) => { + const pending = new Map(current.pending); + pending.delete(requestId); + return { ...current, pending }; + }); + return yield* Queue.offer(target.queue, { requestId, command }).pipe( + Effect.andThen(Deferred.await(deferred).pipe(Effect.timeoutOption(RESPONSE_TIMEOUT))), + Effect.flatMap( + Option.match({ + onNone: () => Effect.fail(new AppControlTimeoutError()), + onSome: Effect.succeed, + }), + ), + Effect.ensuring(removePending), + ); + }); + + return AppControl.of({ connect, reportFocus, respond, run }); +}); + +export const layer = Layer.effect(AppControl, make); diff --git a/apps/server/src/auth/RpcAuthorization.ts b/apps/server/src/auth/RpcAuthorization.ts index 180f053f111f4..54291e3beb69b 100644 --- a/apps/server/src/auth/RpcAuthorization.ts +++ b/apps/server/src/auth/RpcAuthorization.ts @@ -200,6 +200,8 @@ export const RPC_REQUIRED_SCOPES = { [WS_METHODS.previewReportStatus]: AuthPreviewOperateScope, [WS_METHODS.previewStopLocalServer]: AuthTerminalOperateScope, [WS_METHODS.subscribePreviewEvents]: AuthOrchestrationReadScope, + [WS_METHODS.subscribeAppControl]: AuthOrchestrationReadScope, + [WS_METHODS.appControlRespond]: AuthOrchestrationReadScope, [WS_METHODS.subscribeDiscoveredLocalServers]: AuthOrchestrationReadScope, [WS_METHODS.deviceConfigure]: AuthSettingsWriteScope, [WS_METHODS.deviceTestHost]: AuthSettingsWriteScope, diff --git a/apps/server/src/mcp/toolkits/environment/handlers.test.ts b/apps/server/src/mcp/toolkits/environment/handlers.test.ts index 906bee5ac5e77..5299979e3d583 100644 --- a/apps/server/src/mcp/toolkits/environment/handlers.test.ts +++ b/apps/server/src/mcp/toolkits/environment/handlers.test.ts @@ -4,6 +4,7 @@ import { ProjectId, ProviderInstanceId, ThreadId, + type AppControlResult, type OrchestrationV2ThreadShell, type ServerSettings, } from "@t3tools/contracts"; @@ -15,6 +16,7 @@ import * as Layer from "effect/Layer"; import * as Ref from "effect/Ref"; import * as Stream from "effect/Stream"; +import * as AppControl from "../../../appControl/AppControl.ts"; import * as Environment from "../../../environment/ServerEnvironment.ts"; import * as Keybindings from "../../../keybindings.ts"; import * as ThreadCommandExecutor from "../../../orchestration-v2/ThreadCommandExecutor.ts"; @@ -38,9 +40,14 @@ const makeLayer = Effect.fn(function* ( options: { readonly onGetThreadShell?: Effect.Effect; readonly settings?: Parameters[0]; + readonly appCommand?: Effect.Effect; } = {}, ) { - const { onGetThreadShell = Effect.void, settings = {} } = options; + const { + onGetThreadShell = Effect.void, + settings = {}, + appCommand = Effect.succeed("ran"), + } = options; const caller = yield* Ref.make(liveThreadShell(threadId)); const writes = yield* Ref.make(0); const write = (value: A) => Ref.update(writes, (count) => count + 1).pipe(Effect.as(value)); @@ -82,6 +89,9 @@ const makeLayer = Effect.fn(function* ( upsertKeybindingRule: () => write(snapshot), removeKeybindingRule: () => write(snapshot), }), + Layer.mock(AppControl.AppControl)({ + run: () => appCommand.pipe(Effect.tap(() => write(undefined))), + }), ), ), ); @@ -163,6 +173,9 @@ it.effect("refuses settings and shortcuts agents may not or cannot write", () => call("t3_keybinding_remove", { key: "mod+k", command: "terminal.toggle" }), "invalid_request", ], + [call("t3_app_command", { command: "not.a.command" }), "invalid_request"], + [call("t3_app_command", { command: "composer.sendAlternate" }), "invalid_request"], + [call("t3_app_command", { command: "thread.undo" }), "invalid_request"], ] as const; yield* Effect.gen(function* () { const before = yield* (yield* Settings.ServerSettingsService).getSettings; @@ -218,3 +231,20 @@ it.effect("lists every loaded shortcut in a form that writes back", () => }).pipe(Effect.provide(layer)); }), ); + +it.effect("says when the user's window cannot run an app command", () => + Effect.gen(function* () { + const cases = [ + [Effect.succeed("ran"), { ran: true }], + [Effect.succeed("not-handled"), { code: "invalid_request" }], + [Effect.succeed("other-environment"), { code: "invalid_request" }], + [Effect.fail(new AppControl.AppControlNoWindowError()), { code: "orchestration_error" }], + ] as const; + for (const [appCommand, expected] of cases) { + const { layer } = yield* makeLayer({ appCommand }); + expect( + yield* call("t3_app_command", { command: "terminal.toggle" }).pipe(Effect.provide(layer)), + ).toMatchObject(expected); + } + }), +); diff --git a/apps/server/src/mcp/toolkits/environment/handlers.ts b/apps/server/src/mcp/toolkits/environment/handlers.ts index f23af7aaba158..82ec34b77c1fa 100644 --- a/apps/server/src/mcp/toolkits/environment/handlers.ts +++ b/apps/server/src/mcp/toolkits/environment/handlers.ts @@ -1,4 +1,5 @@ import { + AppCommand, KeybindingRule, OrchestratorMcpFailure, ProjectId, @@ -11,6 +12,7 @@ import { compileResolvedKeybindingRule } from "@t3tools/shared/keybindings"; import { resolveProjectSettings } from "@t3tools/shared/projectSettings"; import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; +import * as AppControl from "../../../appControl/AppControl.ts"; import * as Environment from "../../../environment/ServerEnvironment.ts"; import * as Keybindings from "../../../keybindings.ts"; import * as ThreadCommandExecutor from "../../../orchestration-v2/ThreadCommandExecutor.ts"; @@ -50,6 +52,7 @@ const invalid = (message: string) => const decodePatch = Schema.decodeUnknownEffect(ServerSettingsPatch); const encodeSettings = Schema.encodeEffect(ServerSettings); const decodeKeybinding = Schema.decodeUnknownEffect(KeybindingRule); +const decodeAppCommand = Schema.decodeUnknownEffect(AppCommand); const settingsView = (settings: ServerSettings, keys: ReadonlyArray | undefined) => encodeSettings(Settings.redactServerSettingsForClient(settings, { secretReferences: true })).pipe( @@ -113,6 +116,7 @@ const access = Effect.gen(function* () { descriptor, settings: yield* Settings.ServerSettingsService, keybindings: yield* Keybindings.Keybindings, + appControl: yield* AppControl.AppControl, }; }); @@ -243,4 +247,39 @@ export const layer = McpToolAccess.toLayer(EnvironmentToolkit, { }), ), ), + t3_app_command: McpToolAccess.writesEnvironment(({ command }) => + Effect.gen(function* () { + const appCommand = yield* decodeAppCommand(command).pipe( + Effect.mapError(() => + invalid( + "Unknown command, or one only the user may run. `t3_keybindings_read` lists them.", + ), + ), + ); + const { appControl } = yield* access; + const failed = (message: string) => + Effect.fail(new OrchestratorMcpFailure({ code: "orchestration_error", message })); + const result = yield* appControl.run(appCommand).pipe( + Effect.catchTags({ + AppControlNoWindowError: () => + failed( + "No T3 Code window is open on this environment. Mobile apps don't take commands.", + ), + AppControlTimeoutError: () => + failed( + "The user's window didn't answer. It may still run the command when it wakes, so check before retrying.", + ), + }), + ); + if (result === "other-environment") + return yield* invalid( + `\`${command}\` runs only while the user's window shows a thread or draft from this environment.`, + ); + if (result === "not-handled") + return yield* invalid( + `Nothing in the user's window handles \`${command}\` right now, such as a thread command outside a thread.`, + ); + return { ran: true }; + }), + ), }); diff --git a/apps/server/src/mcp/toolkits/environment/tools.ts b/apps/server/src/mcp/toolkits/environment/tools.ts index 0b45d07b5fba8..541fbbd1ac507 100644 --- a/apps/server/src/mcp/toolkits/environment/tools.ts +++ b/apps/server/src/mcp/toolkits/environment/tools.ts @@ -7,6 +7,7 @@ import { } from "@t3tools/contracts"; import * as Schema from "effect/Schema"; import { Tool, Toolkit } from "effect/ai"; +import * as AppControl from "../../../appControl/AppControl.ts"; import * as ServerEnvironment from "../../../environment/ServerEnvironment.ts"; import * as Keybindings from "../../../keybindings.ts"; import * as ThreadCommandExecutor from "../../../orchestration-v2/ThreadCommandExecutor.ts"; @@ -35,6 +36,7 @@ const shared = { ServerEnvironment.ServerEnvironment, Settings.ServerSettingsService, Keybindings.Keybindings, + AppControl.AppControl, ThreadCommandExecutor.ThreadCommandExecutor, ], }; @@ -123,6 +125,16 @@ const KeybindingRemoveTool = Tool.make("t3_keybinding_remove", { }), success: Schema.Struct({ keybindings: Schema.Array(KeybindingRuleView) }), }).annotate(Tool.Destructive, true); +const AppCommandTool = Tool.make("t3_app_command", { + ...shared, + description: + "Run a command from `t3_keybindings_read` in the user's T3 Code window, the one they used last, as if they pressed its shortcut. Sending or dictating in their composer stays theirs. Live full-access or default caller thread only.", + parameters: Schema.Struct({ + environmentId: OrchestratorMcpEnvironmentTarget, + command: Schema.String.annotate({ description: 'e.g. "terminal.toggle".' }), + }), + success: Schema.Struct({ ran: Schema.Boolean }), +}).annotate(Tool.Destructive, true); export const EnvironmentToolkit = Toolkit.make( EnvironmentReadTool, SettingsReadTool, @@ -130,4 +142,5 @@ export const EnvironmentToolkit = Toolkit.make( KeybindingsReadTool, KeybindingUpsertTool, KeybindingRemoveTool, + AppCommandTool, ); diff --git a/apps/server/src/observability/RpcInstrumentation.ts b/apps/server/src/observability/RpcInstrumentation.ts index f9a861cca23fb..262c3f236dc6b 100644 --- a/apps/server/src/observability/RpcInstrumentation.ts +++ b/apps/server/src/observability/RpcInstrumentation.ts @@ -213,6 +213,8 @@ const RPC_AGGREGATES = { [WS_METHODS.previewReportProfiles]: "preview", [WS_METHODS.previewReportStatus]: "preview", [WS_METHODS.subscribePreviewEvents]: "preview", + [WS_METHODS.subscribeAppControl]: "app-control", + [WS_METHODS.appControlRespond]: "app-control", [WS_METHODS.subscribeDiscoveredLocalServers]: "preview", [WS_METHODS.previewStopLocalServer]: "preview", [WS_METHODS.deviceConfigure]: "device", diff --git a/apps/server/src/provider/AgentContextBudget.test.ts b/apps/server/src/provider/AgentContextBudget.test.ts index 24a0d9d06ad0a..893658536a203 100644 --- a/apps/server/src/provider/AgentContextBudget.test.ts +++ b/apps/server/src/provider/AgentContextBudget.test.ts @@ -13,6 +13,7 @@ import { ServerConfig } from "../config.ts"; import { DeviceService } from "../device/DeviceService.ts"; import { ServerEnvironment } from "../environment/ServerEnvironment.ts"; import { GitWorkflowService } from "../git/GitWorkflowService.ts"; +import { AppControl } from "../appControl/AppControl.ts"; import { Keybindings } from "../keybindings.ts"; import * as McpHttpServer from "../mcp/McpHttpServer.ts"; import { PreviewAutomationBroker } from "../mcp/PreviewAutomationBroker.ts"; @@ -55,6 +56,7 @@ const toolHandlerServices = Layer.mergeAll( Layer.mock(GitVcsDriver)({}), Layer.mock(GitWorkflowService)({}), Layer.mock(Keybindings)({}), + Layer.mock(AppControl)({}), Layer.mock(ManagedProjectFolders)({ namedProjectsRoot: "" }), Layer.mock(McpProviderSessions)({}), Layer.mock(OrchestratorV2)({}), diff --git a/apps/server/src/provider/agentContextBudget.json b/apps/server/src/provider/agentContextBudget.json index e2cbb1f643716..01973bac6d369 100644 --- a/apps/server/src/provider/agentContextBudget.json +++ b/apps/server/src/provider/agentContextBudget.json @@ -1,5 +1,5 @@ { "claudeSystemAppendBytes": 5597, "codexAdditionalContextBytes": 7327, - "mcpToolListJsonBytes": 49649 + "mcpToolListJsonBytes": 50094 } diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 47190f60dcf51..95e4809d22374 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -26,6 +26,7 @@ import * as Stream from "effect/Stream"; import { FetchHttpClient, HttpRouter, HttpServer } from "effect/http"; import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder"; +import * as AppControl from "./appControl/AppControl.ts"; import * as BackgroundPolicy from "./background/BackgroundPolicy.ts"; import * as HostPowerMonitor from "./background/HostPowerMonitor.ts"; import * as ServerConfig from "./config.ts"; @@ -696,7 +697,12 @@ const layerRuntimeCoreDependenciesBase = Layer.mergeAll( Layer.provideMerge(Layer.mergeAll(layerTerminal, layerPreview, layerDevice)), Layer.provideMerge(layerPersistence), Layer.provideMerge( - Layer.mergeAll(Keybindings.layer, EnvironmentTheme.layer, UsageLimitSources.layer), + Layer.mergeAll( + Keybindings.layer, + EnvironmentTheme.layer, + UsageLimitSources.layer, + AppControl.layer, + ), ), Layer.provideMerge(ProviderRegistry.layer), Layer.provideMerge(ProviderInstanceRegistryHydration.layer), diff --git a/apps/server/src/ws.test.ts b/apps/server/src/ws.test.ts index 6374204471964..828901f445d29 100644 --- a/apps/server/src/ws.test.ts +++ b/apps/server/src/ws.test.ts @@ -54,6 +54,7 @@ import * as AgentSessionScanner from "./project/AgentSessionScanner.ts"; import * as AnalyticsService from "./telemetry/AnalyticsService.ts"; import * as AntigravityInstallation from "./provider/AntigravityInstallation.ts"; import * as ProviderInstallation from "./provider/providerInstallation.ts"; +import * as AppControl from "./appControl/AppControl.ts"; import * as BackgroundPolicy from "./background/BackgroundPolicy.ts"; import * as CheckpointDiffQuery from "./checkpointing/CheckpointDiffQuery.ts"; import * as NativeChildWorkQuery from "./orchestration-v2/NativeChildWorkQuery.ts"; @@ -787,6 +788,7 @@ const layerUnusedConfigRpcServices = Layer.mergeAll( Layer.mock(AnalyticsService.AnalyticsService)({}), Layer.mock(AntigravityInstallation.AntigravityInstallation)({ managedDirectory: "/unused" }), Layer.mock(BackgroundPolicy.BackgroundPolicy)({}), + Layer.mock(AppControl.AppControl)({}), Layer.mock(CheckpointDiffQuery.CheckpointDiffQuery)({}), Layer.mock(NativeChildWorkQuery.NativeChildWorkQuery)({}), Layer.mock(CommandOutputHub.CommandOutputHub)({}), diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 8a8c4e1be719c..17a61fb861980 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -229,6 +229,7 @@ import * as DirectEndpoints from "./environment/DirectEndpoints.ts"; import * as RemoteOpenTargets from "./environment/RemoteOpenTargets.ts"; import * as DefectReporter from "./observability/DefectReporter.ts"; import * as EventLoopMonitor from "./observability/EventLoopMonitor.ts"; +import * as AppControl from "./appControl/AppControl.ts"; import * as BackgroundPolicy from "./background/BackgroundPolicy.ts"; import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts"; import { requiredScopeForDeviceList, rpcAuthorizationError } from "./auth/RpcAuthorization.ts"; @@ -1457,10 +1458,10 @@ export const layerWsRpc = ( yield* Effect.context>>(); const orchestrationEngine = yield* Orchestrator.OrchestratorV2; const random = yield* SecureRandom.SecureRandom; - // RPC client ids are only unique within one socket; terminals share viewers across sockets. - const terminalViewerPrefix = yield* random.uuidV4(); - const terminalViewerId = (metadata: { readonly client: { readonly id: number } }) => - `${terminalViewerPrefix}:${metadata.client.id}`; + // RPC client ids are only unique within one socket; terminals and app windows span sockets. + const socketPrefix = yield* random.uuidV4(); + const socketClientId = (metadata: { readonly client: { readonly id: number } }) => + `${socketPrefix}:${metadata.client.id}`; const serverCommandId = (tag: string) => random.uuidV4().pipe( Effect.orDie, @@ -1497,6 +1498,7 @@ export const layerWsRpc = ( const vcsStatusBroadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster; const terminalManager = yield* TerminalManager.TerminalManager; const previewManager = yield* PreviewManager.PreviewManager; + const appControl = yield* AppControl.AppControl; const portDiscovery = yield* PortScanner.PortDiscovery; const providerRegistry = yield* ProviderRegistry.ProviderRegistry; const providerInstances = yield* ProviderInstanceRegistry.ProviderInstanceRegistry; @@ -2757,6 +2759,12 @@ export const layerWsRpc = ( input, ), ), + Effect.andThen( + appControl.reportFocus( + { sessionId: currentSessionId, windowId: socketClientId(metadata) }, + input.focused && input.visible, + ), + ), ), [WS_METHODS.cloudGetRelayClientStatus]: (_input) => relayClient.resolve, [WS_METHODS.cloudInstallRelayClient]: (_input) => @@ -3222,10 +3230,10 @@ export const layerWsRpc = ( [WS_METHODS.reviewGetDiffFileContents]: (input) => review.getDiffFileContents(input), [WS_METHODS.terminalOpen]: (input) => terminalManager.open(input), [WS_METHODS.terminalAttach]: (input, metadata) => - terminalManager.attachOutputStream(input, terminalViewerId(metadata)), + terminalManager.attachOutputStream(input, socketClientId(metadata)), [WS_METHODS.terminalWrite]: (input) => terminalManager.write(input), [WS_METHODS.terminalResize]: (input, metadata) => - terminalManager.resize(input, terminalViewerId(metadata)), + terminalManager.resize(input, socketClientId(metadata)), [WS_METHODS.terminalClear]: (input) => terminalManager.clear(input), [WS_METHODS.terminalClose]: (input) => terminalManager.close(input), [WS_METHODS.terminalObserve]: (input) => @@ -3251,6 +3259,14 @@ export const layerWsRpc = ( [WS_METHODS.previewReportProfiles]: (input) => reportProfiles(input), [WS_METHODS.previewReportStatus]: (input) => previewManager.reportStatus(input), [WS_METHODS.subscribePreviewEvents]: (_input) => previewManager.events, + [WS_METHODS.subscribeAppControl]: (input, metadata) => + Stream.unwrap( + appControl.connect( + { sessionId: currentSessionId, windowId: socketClientId(metadata) }, + input.focused, + ), + ), + [WS_METHODS.appControlRespond]: (input) => appControl.respond(currentSessionId, input), [WS_METHODS.deviceConfigure]: (input) => deviceService.configure(input), [WS_METHODS.deviceTestHost]: (input) => deviceService.testHost(input), [WS_METHODS.deviceEasAccount]: (input) => deviceService.easAccount(input), diff --git a/apps/web/src/appInit.tsx b/apps/web/src/appInit.tsx index 3be9175c4f2e4..5a45c030f96f7 100644 --- a/apps/web/src/appInit.tsx +++ b/apps/web/src/appInit.tsx @@ -51,6 +51,7 @@ import { appAtomRegistry } from "./rpc/atomRegistry"; import { primaryServerConfigAtom } from "./state/server"; import { environmentShell } from "./state/shell"; import { installChatRouteCommands } from "./shortcuts/chatRouteCommands"; +import { startAppControl } from "./lib/appControl"; import { startWorkspaceFocus } from "./lib/workspaceFocus"; import { installCommandPaletteCommands } from "./shortcuts/commandPaletteCommands"; import { registerOpenFavoriteEditorCommand } from "./components/chat/OpenInPickerShortcut"; @@ -191,6 +192,7 @@ export function startAppServices(): AppRouter { startPreviewTitleRecording(); startBrowserProfileReporting(); installChatRouteCommands(router); + startAppControl(router); installCommandPaletteCommands(router); registerOpenFavoriteEditorCommand(); startThreadOverlayRetention(router); diff --git a/apps/web/src/components/AppSidebarLayout.tsx b/apps/web/src/components/AppSidebarLayout.tsx index f9cb8c5170cf9..7537465e21242 100644 --- a/apps/web/src/components/AppSidebarLayout.tsx +++ b/apps/web/src/components/AppSidebarLayout.tsx @@ -62,7 +62,11 @@ import { } from "./ui/sidebar"; import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip"; import { appAtomRegistry } from "../rpc/atomRegistry"; -import { registerCommands, registerMenuAction } from "../shortcuts/dispatcher"; +import { + registerCommandRunner, + registerCommands, + registerMenuAction, +} from "../shortcuts/dispatcher"; import { resolveThreadRouteRef } from "../threadRoutes"; const MACOS_TRAFFIC_LIGHTS_LEFT_INSET = "var(--desktop-window-controls-inset, 90px)"; @@ -360,9 +364,15 @@ function SidebarControl({ showSidebar }: { readonly showSidebar: boolean }) { const unsubscribe = window.desktopBridge?.onMenuAction((action) => { if (action === "sidebar.toggle") toggleSidebar(); }); + const unregisterRunner = registerCommandRunner((command) => { + if (command !== "sidebar.toggle") return false; + toggleSidebar(); + return true; + }); return () => { window.removeEventListener("keydown", onKeyDown, true); unsubscribe?.(); + unregisterRunner(); }; }, [keybindings, showSidebar, toggleSidebar, usagePageOpen]); diff --git a/apps/web/src/components/RightPanelTabs.tsx b/apps/web/src/components/RightPanelTabs.tsx index 596bdee96ad1f..0a11fb838a28d 100644 --- a/apps/web/src/components/RightPanelTabs.tsx +++ b/apps/web/src/components/RightPanelTabs.tsx @@ -104,6 +104,7 @@ import { resolvePullRequestState } from "./pullRequest/pullRequestPresentation"; import { PullRequestGlyph } from "~/components/pullRequest/pullRequestIcons"; import { observeResize } from "~/lib/observeResize"; import { surfaceShortcutKey } from "~/lib/surfaceShortcutKey"; +import { registerCommandRunner } from "../shortcuts/dispatcher"; export interface RightPanelTabsProps { mode: PreviewPanelMode; @@ -1039,6 +1040,10 @@ export function RightPanelTabs(props: RightPanelTabsProps) { if (props.open === false && addSurfaceMenuOpen) setAddSurfaceMenuOpen(false); + const openAddSurfaceMenu = useEffectEvent(() => { + addSurfaceTriggerRef.current?.focus(); + setAddSurfaceMenuOpen(true); + }); const onNewSurfaceKeyDown = useEffectEvent((event: KeyboardEvent) => { if (event.defaultPrevented || event.isComposing) return; if ( @@ -1050,16 +1055,22 @@ export function RightPanelTabs(props: RightPanelTabsProps) { if (!addSurfaceMenuOpen && document.querySelector(LAUNCHER_SHORTCUT_BLOCKING_LAYERS)) return; event.preventDefault(); event.stopPropagation(); - if (!event.repeat) { - addSurfaceTriggerRef.current?.focus(); - setAddSurfaceMenuOpen(true); - } + if (!event.repeat) openAddSurfaceMenu(); }); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes a document keydown listener for the new surface shortcut while the panel is open useEffect(() => { if (props.open === false) return; document.addEventListener("keydown", onNewSurfaceKeyDown, true); - return () => document.removeEventListener("keydown", onNewSurfaceKeyDown, true); + const unregisterRunner = registerCommandRunner((command) => { + if (command !== "rightPanel.new" || document.querySelector(LAUNCHER_SHORTCUT_BLOCKING_LAYERS)) + return false; + openAddSurfaceMenu(); + return true; + }); + return () => { + document.removeEventListener("keydown", onNewSurfaceKeyDown, true); + unregisterRunner(); + }; }, [props.open]); const updateTabScrollState = (viewport: HTMLDivElement) => { diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 2b1a8403935c6..e5fd9cb52f811 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -100,6 +100,7 @@ import { useShortcutModifierState } from "../shortcutModifierState"; import { isTerminalFocused } from "../lib/terminalFocus"; import { isPreviewFocused } from "../lib/previewFocus"; import { isModelPickerOpen } from "../modelPickerVisibility"; +import { registerCommandRunner } from "../shortcuts/dispatcher"; import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore"; import { selectActiveRightPanel, useRightPanelStore } from "../rightPanelStore"; import { isMacPlatform } from "~/lib/utils"; @@ -2889,6 +2890,27 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve ); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes to window keydown for thread navigation shortcuts using the current thread list useEffect(() => { + const navigateToThreadKey = (targetThreadKey: string | null) => { + if (!targetThreadKey) return false; + const targetThread = threadByKey.get(targetThreadKey); + if (!targetThread) return false; + navigateToThread(scopeThreadRef(targetThread.environmentId, targetThread.id)); + return true; + }; + const runThreadCommand = (command: string | null) => { + const traversalDirection = threadTraversalDirectionFromCommand(command); + if (traversalDirection !== null) { + return navigateToThreadKey( + resolveAdjacentThreadId({ + threadIds: orderedThreadKeys, + currentThreadId: routeRowThreadKey, + direction: traversalDirection, + }), + ); + } + const jumpIndex = threadJumpIndexFromCommand(command ?? ""); + return jumpIndex !== null && navigateToThreadKey(orderedThreadKeys[jumpIndex] ?? null); + }; const onWindowKeyDown = (event: KeyboardEvent) => { if (event.defaultPrevented || event.repeat || isCommandPaletteOpen() || isModelPickerOpen()) { return; @@ -2905,32 +2927,18 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve isDesktop: isElectron, }, }); - const navigateToThreadKey = (targetThreadKey: string | null) => { - if (!targetThreadKey) return false; - const targetThread = threadByKey.get(targetThreadKey); - if (!targetThread) return false; - event.preventDefault(); - event.stopPropagation(); - navigateToThread(scopeThreadRef(targetThread.environmentId, targetThread.id)); - return true; - }; - const traversalDirection = threadTraversalDirectionFromCommand(command); - if (traversalDirection !== null) { - navigateToThreadKey( - resolveAdjacentThreadId({ - threadIds: orderedThreadKeys, - currentThreadId: routeRowThreadKey, - direction: traversalDirection, - }), - ); - return; - } - const jumpIndex = threadJumpIndexFromCommand(command ?? ""); - if (jumpIndex === null) return; - navigateToThreadKey(orderedThreadKeys[jumpIndex] ?? null); + if (!runThreadCommand(command)) return; + event.preventDefault(); + event.stopPropagation(); }; window.addEventListener("keydown", onWindowKeyDown); - return () => window.removeEventListener("keydown", onWindowKeyDown); + const unregisterRunner = registerCommandRunner( + (command) => !isCommandPaletteOpen() && runThreadCommand(command), + ); + return () => { + window.removeEventListener("keydown", onWindowKeyDown); + unregisterRunner(); + }; }, [ keybindings, navigateToThread, diff --git a/apps/web/src/components/chat/useChatShortcuts.ts b/apps/web/src/components/chat/useChatShortcuts.ts index 637546f65d2bc..8da25600becb3 100644 --- a/apps/web/src/components/chat/useChatShortcuts.ts +++ b/apps/web/src/components/chat/useChatShortcuts.ts @@ -1,6 +1,7 @@ import type { KeybindingCommand, ResolvedKeybindingsConfig } from "@t3tools/contracts"; import { useEffect, useEffectEvent } from "react"; import { isCommandPaletteOpen } from "../../commandPaletteBus"; +import { registerCommandRunner } from "../../shortcuts/dispatcher"; import { resolveChatShortcutCommand, type ShortcutMatchContext } from "../../keybindings"; import { isTerminalCloseConfirmPending } from "../../lib/terminalCloseConfirm"; import { @@ -92,6 +93,17 @@ export function useChatShortcuts(input: ChatShortcutsInput) { event.preventDefault(); event.stopPropagation(); }); + const runWithoutKey = useEffectEvent((command: KeybindingCommand) => { + if (!input.enabled || isCommandPaletteOpen()) return false; + const run = + input.commands[command] ?? + composerShortcutCommands(input.composerRef, input.branchToolbarRef)[command] ?? + input.fallback(command); + const event = new KeyboardEvent("keydown", { cancelable: true }); + return ( + run !== undefined && run({ event, terminalFocusOwner: getTerminalFocusOwner() }) !== false + ); + }); const dismissFind = useEffectEvent((event: KeyboardEvent) => { if ( event.key !== "Escape" || @@ -132,9 +144,11 @@ export function useChatShortcuts(input: ChatShortcutsInput) { const onKeyDown = (event: KeyboardEvent) => dismissFind(event); window.addEventListener("keydown", onKeyDownCapture, true); window.addEventListener("keydown", onKeyDown); + const unregisterRunner = registerCommandRunner((command) => runWithoutKey(command)); return () => { window.removeEventListener("keydown", onKeyDownCapture, true); window.removeEventListener("keydown", onKeyDown); + unregisterRunner(); }; }, [composerElement, embedded]); } diff --git a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx index 9d0f6193f7e3f..866b22a7017d9 100644 --- a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx +++ b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx @@ -158,6 +158,7 @@ import { import { PullRequestGuideTab } from "./PullRequestGuideTab"; import { guideRunKey, useGuideRunStore } from "./guide/guideRunStore"; import { useReviewGuideWriter } from "./guide/useReviewGuideWriter"; +import { registerCommandRunner } from "~/shortcuts/dispatcher"; const actionFailureLabels = (term: string): Record => ({ merge: `Could not merge this ${term}`, @@ -483,6 +484,15 @@ export function PullRequestDetailPanel({ description: error.message, }), }); + const copyNumber = useEffectEvent(() => + copyReference(`#${reference.number}`, `${terminology.shortLabel} number`), + ); + const runCopyNumber = useEffectEvent((command: string) => { + if (command !== "pullRequest.copyNumber" || !shortcutsEnabled || isCommandPaletteOpen()) + return false; + copyNumber(); + return true; + }); const copyFromShortcut = useEffectEvent((event: KeyboardEvent) => { if (!shortcutsEnabled || event.defaultPrevented || isCommandPaletteOpen()) return; const command = resolveShortcutCommand(event, keybindings, { @@ -491,13 +501,17 @@ export function PullRequestDetailPanel({ if (command !== "pullRequest.copyNumber") return; event.preventDefault(); event.stopPropagation(); - if (!event.repeat) copyReference(`#${reference.number}`, `${terminology.shortLabel} number`); + if (!event.repeat) copyNumber(); }); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- window keydown capture listener for the copy-number shortcut useEffect(() => { const onKeyDown = (event: KeyboardEvent) => copyFromShortcut(event); window.addEventListener("keydown", onKeyDown, true); - return () => window.removeEventListener("keydown", onKeyDown, true); + const unregisterRunner = registerCommandRunner((command) => runCopyNumber(command)); + return () => { + window.removeEventListener("keydown", onKeyDown, true); + unregisterRunner(); + }; }, []); const autoMergeKey = `${pullRequestKey}:${detail?.autoMergeMethod ?? ""}`; const [seenAutoMergeKey, setSeenAutoMergeKey] = useState(null); diff --git a/apps/web/src/components/usage/UsagePage.tsx b/apps/web/src/components/usage/UsagePage.tsx index 8bc8a93a43d69..9be9b8c0db9b9 100644 --- a/apps/web/src/components/usage/UsagePage.tsx +++ b/apps/web/src/components/usage/UsagePage.tsx @@ -106,6 +106,7 @@ import { saveUsagePagePreferences, type UsagePagePreferences, } from "./usagePagePreferences"; +import { registerCommandRunner } from "../../shortcuts/dispatcher"; function isUsageMetric(value: string | null | undefined): value is UsageMetric { return METRIC_OPTIONS.some((option) => option.value === value); @@ -266,6 +267,14 @@ export function UsagePage() { setLimitsNow(Date.now()); if (!AsyncResult.isSuccess(result)) throw Cause.squash(result.cause); }); + const runUsageCommand = useEffectEvent((command: string | null) => { + const metricOption = METRIC_OPTIONS.find((option) => option.command === command); + const periodOption = WINDOW_OPTIONS.find((option) => option.command === command); + if (!metricOption && !periodOption) return false; + if (metricOption) selectMetric(metricOption.value); + if (periodOption && !showingLimits) selectWindow(periodOption.days); + return true; + }); const onUsageKeyDown = useEffectEvent((event: KeyboardEvent) => { if ( event.defaultPrevented || @@ -276,21 +285,21 @@ export function UsagePage() { ) return; - const command = resolveUsageShortcut(event, keybindings); - const metricOption = METRIC_OPTIONS.find((option) => option.command === command); - const periodOption = WINDOW_OPTIONS.find((option) => option.command === command); - if (!metricOption && !periodOption) return; - + if (!runUsageCommand(resolveUsageShortcut(event, keybindings))) return; event.preventDefault(); event.stopPropagation(); - if (metricOption) selectMetric(metricOption.value); - if (periodOption && !showingLimits) selectWindow(periodOption.days); }); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- window capture keydown listener for usage metric and period shortcuts useEffect(() => { globalThis.window.addEventListener("keydown", onUsageKeyDown, true); - return () => globalThis.window.removeEventListener("keydown", onUsageKeyDown, true); + const unregisterRunner = registerCommandRunner( + (command) => !isCommandPaletteOpen() && runUsageCommand(command), + ); + return () => { + globalThis.window.removeEventListener("keydown", onUsageKeyDown, true); + unregisterRunner(); + }; }, []); const refreshWindow = () => { diff --git a/apps/web/src/lib/appControl.ts b/apps/web/src/lib/appControl.ts new file mode 100644 index 0000000000000..ae0bed35e719f --- /dev/null +++ b/apps/web/src/lib/appControl.ts @@ -0,0 +1,77 @@ +import { EnvironmentRegistry } from "@t3tools/client-runtime/connection"; +import { request, subscribeDynamic } from "@t3tools/client-runtime/rpc"; +import { + type AppCommand, + type AppControlResult, + VIEW_ONLY_APP_COMMANDS, + WS_METHODS, +} from "@t3tools/contracts"; +import type { AnyRouter } from "@tanstack/react-router"; +import * as Effect from "effect/Effect"; +import * as Stream from "effect/Stream"; +import * as SubscriptionRef from "effect/SubscriptionRef"; + +import { useComposerDraftStore } from "../composerDraftStore"; +import { connectionAtomRuntime } from "../connection/runtime"; +import { appAtomRegistry } from "../rpc/atomRegistry"; +import { runCommand } from "../shortcuts/dispatcher"; +import { resolveThreadRouteTarget } from "../threadRoutes"; + +/** Runs the commands agents send this window, from every environment it is connected to. */ +export function startAppControl(router: AnyRouter): () => void { + // Outside view-only commands, a command runs only on its own environment's thread or draft, + // so an agent can't act through this window on an environment it has no access to. + const shownEnvironmentIds = () => { + const params: Record = router.state.matches.at(-1)?.params ?? {}; + const target = resolveThreadRouteTarget(params); + const draft = + target?.kind === "draft" + ? useComposerDraftStore.getState().getDraftSession(target.draftId) + : null; + return [params.environmentId, draft?.environmentId, draft?.loadBalancedEnvironmentId]; + }; + const run = (environmentId: string, command: AppCommand): AppControlResult => { + if (!VIEW_ONLY_APP_COMMANDS.has(command)) { + const shown = shownEnvironmentIds().filter((id) => id != null); + if (shown.length === 0 || shown.some((id) => id !== environmentId)) + return "other-environment"; + } + return runCommand(command) ? "ran" : "not-handled"; + }; + const focused = Effect.sync(() => ({ + focused: document.hasFocus() && document.visibilityState === "visible", + })); + const atom = connectionAtomRuntime.atom( + Effect.gen(function* () { + const registry = yield* EnvironmentRegistry.EnvironmentRegistry; + yield* Stream.concat( + Stream.fromEffect(SubscriptionRef.get(registry.entries)), + SubscriptionRef.changes(registry.entries), + ).pipe( + Stream.map((entries) => [...entries.keys()]), + Stream.changesWith((previous, current) => previous.join() === current.join()), + Stream.switchMap((environmentIds) => + Stream.mergeAll( + environmentIds.map((environmentId) => + registry.followStream( + environmentId, + subscribeDynamic(WS_METHODS.subscribeAppControl, () => focused).pipe( + Stream.mapEffect(({ requestId, command }) => + request(WS_METHODS.appControlRespond, { + requestId, + result: run(environmentId, command), + }).pipe(Effect.ignoreCause), + ), + Stream.ignoreCause, + ), + ), + ), + { concurrency: "unbounded" }, + ), + ), + Stream.runDrain, + ); + }), + ); + return appAtomRegistry.mount(atom); +} diff --git a/apps/web/src/shortcuts/dispatcher.browser.test.ts b/apps/web/src/shortcuts/dispatcher.browser.test.ts index b9bf6c4e4b7d3..1e4c1dacbd29a 100644 --- a/apps/web/src/shortcuts/dispatcher.browser.test.ts +++ b/apps/web/src/shortcuts/dispatcher.browser.test.ts @@ -1,7 +1,7 @@ import type { KeybindingCommand, ResolvedKeybindingsConfig } from "@t3tools/contracts"; import { describe, expect, it, vi } from "vite-plus/test"; -import { dispatchMenuAction, registerCommands, registerMenuAction } from "./dispatcher"; +import { dispatchMenuAction, registerCommands, registerMenuAction, runCommand } from "./dispatcher"; function bindings(entries: ReadonlyArray<[string, KeybindingCommand]>): ResolvedKeybindingsConfig { return entries.map(([key, command]) => ({ @@ -46,22 +46,29 @@ describe("command dispatcher", () => { expect(global).not.toHaveBeenCalled(); }); - it("falls through scopes that return false, skip the command, or fail their guard", () => { - const global = vi.fn(); - const declined = vi.fn(() => false); - const guarded = vi.fn(); - using stack = new DisposableStack(); - stack.defer(registerCommands({ "chat.new": global }, { keybindings })); - stack.defer(registerCommands({ "chat.new": declined }, { keybindings })); - stack.defer(registerCommands({ "chat.newLocal": vi.fn() }, { keybindings })); - stack.defer(registerCommands({ "chat.new": guarded }, { keybindings, when: () => false })); - - press("k"); - - expect(guarded).not.toHaveBeenCalled(); - expect(declined).toHaveBeenCalledOnce(); - expect(global).toHaveBeenCalledOnce(); - }); + it.each([ + ["key press", () => press("k")], + ["agent", () => expect(runCommand("chat.new")).toBe(true)], + ])( + "falls through scopes that return false, skip the command, or fail their guard (%s)", + (_, run) => { + const global = vi.fn(); + const declined = vi.fn(() => false); + const guarded = vi.fn(); + using stack = new DisposableStack(); + stack.defer(registerCommands({ "chat.new": global }, { keybindings })); + stack.defer(registerCommands({ "chat.new": declined }, { keybindings })); + stack.defer(registerCommands({ "chat.newLocal": vi.fn() }, { keybindings })); + stack.defer(registerCommands({ "chat.new": guarded }, { keybindings, when: () => false })); + + run(); + + expect(guarded).not.toHaveBeenCalled(); + expect(declined).toHaveBeenCalledOnce(); + expect(global).toHaveBeenCalledOnce(); + expect(runCommand("chat.find")).toBe(false); + }, + ); it("stops once a handler prevents default, and unregisters on cleanup", () => { const lower = vi.fn(); diff --git a/apps/web/src/shortcuts/dispatcher.ts b/apps/web/src/shortcuts/dispatcher.ts index 5ce799cf482d5..1a7f066ac1593 100644 --- a/apps/web/src/shortcuts/dispatcher.ts +++ b/apps/web/src/shortcuts/dispatcher.ts @@ -110,6 +110,41 @@ function pushScope(list: CommandScope[], scope: CommandScope): () => void { }; } +type CommandRunner = (command: KeybindingCommand) => boolean; +const commandRunners: CommandRunner[] = []; + +/** + * For views that match their own shortcuts (the chat, the sidebar), so `runCommand` reaches + * them too. A runner returns whether it ran the command. + */ +export function registerCommandRunner(runner: CommandRunner): () => void { + commandRunners.push(runner); + return () => { + const index = commandRunners.lastIndexOf(runner); + if (index !== -1) commandRunners.splice(index, 1); + }; +} + +/** + * Runs a command as its shortcut would, without a key press. Returns false when nothing + * on screen handles it right now, such as a thread command outside a thread. + */ +export function runCommand(command: KeybindingCommand): boolean { + for (let index = commandRunners.length - 1; index >= 0; index -= 1) { + if (commandRunners[index]?.(command)) return true; + } + const event = new KeyboardEvent("keydown", { cancelable: true }); + for (const scopes of [captureScopes, globalScopes]) { + for (let index = scopes.length - 1; index >= 0; index -= 1) { + const scope = scopes[index]; + const handler = scope?.commands[command]; + if (handler === undefined || scope?.options.when?.(event) === false) continue; + if (handler(event) !== false) return true; + } + } + return false; +} + /** App-global commands, registered once at module level or bootstrap. */ export function registerCommands( commands: CommandHandlers, diff --git a/evals/mcp-tool-use/cases/settings.ndjson b/evals/mcp-tool-use/cases/settings.ndjson index 258289e30dec7..991ea4754d3d1 100644 --- a/evals/mcp-tool-use/cases/settings.ndjson +++ b/evals/mcp-tool-use/cases/settings.ndjson @@ -1 +1,2 @@ {"id": "labs-setting-uses-settings-update", "area": "settings", "kind": "bad", "pattern": "edit settings.json by hand", "experience": "Asked to turn on the Linked environments Labs switch on a headless box, an agent had no tool for it and told the user to write the server's settings.json by hand.", "rule": "t3_environment_settings_update: Change this server's settings.", "privacy": "commit-safe", "setup": {"role": "top", "mocks": {"t3_environment_settings_read": {"settings": {"linkedEnvironmentsEnabled": false, "guestSharingEnabled": false, "promptSuggestionsEnabled": false}}, "t3_environment_settings_update": {"settings": {"linkedEnvironmentsEnabled": true}}}}, "prompt": "Turn on the linked environments beta on this machine. There's no T3 Code window open on it.", "expect": {"calls": [{"tool": "t3_environment_settings_update", "args": {"patch.linkedEnvironmentsEnabled": true}}], "shellMustNot": ["settings\\.json"]}, "maxSteps": 6} +{"id": "open-panel-uses-app-command", "area": "settings", "kind": "bad", "pattern": "tell the user to press the shortcut", "experience": "Asked to open the terminal in the user's T3 Code window, an agent had no way to act on the window and told the user which shortcut to press.", "rule": "t3_app_command: Run a command from `t3_keybindings_read` in the user's T3 Code window.", "privacy": "commit-safe", "setup": {"role": "top", "mocks": {"t3_keybindings_read": {"keybindings": [{"key": "mod+j", "command": "terminal.toggle"}], "commands": ["terminal.toggle", "sidebar.toggle", "chat.new"], "issues": []}, "t3_app_command": {"ran": true}}}, "prompt": "Open the terminal in my T3 Code window.", "expect": {"calls": [{"tool": "t3_app_command", "args": {"command": "terminal.toggle"}}]}, "maxSteps": 6} diff --git a/packages/client-runtime/src/rpc/client.ts b/packages/client-runtime/src/rpc/client.ts index 0d8c9e1351d0d..446afe90c616b 100644 --- a/packages/client-runtime/src/rpc/client.ts +++ b/packages/client-runtime/src/rpc/client.ts @@ -64,6 +64,7 @@ export type EnvironmentSubscriptionRpcTag = | typeof WS_METHODS.serverGetDatabaseStorage | typeof WS_METHODS.subscribeTerminalMetadata | typeof WS_METHODS.subscribePreviewEvents + | typeof WS_METHODS.subscribeAppControl | typeof WS_METHODS.subscribeDiscoveredLocalServers | typeof WS_METHODS.subscribeDeviceState | typeof WS_METHODS.subscribeResourceTelemetry diff --git a/packages/client-runtime/src/t3ToolSummary.ts b/packages/client-runtime/src/t3ToolSummary.ts index 09142690a6111..f5daf28dbef1b 100644 --- a/packages/client-runtime/src/t3ToolSummary.ts +++ b/packages/client-runtime/src/t3ToolSummary.ts @@ -355,6 +355,9 @@ export function summarizeT3ToolCalls( case "environment-update": label = phrase("Updated", "update", `environment settings ${times}`); break; + case "app-command": + label = phrase("Ran", "run", `app commands ${times}`); + break; case "environment-links": label = phrase("Listed", "list", `linked environments ${times}`); break; diff --git a/packages/contracts/src/appControl.ts b/packages/contracts/src/appControl.ts new file mode 100644 index 0000000000000..0af347d37a40e --- /dev/null +++ b/packages/contracts/src/appControl.ts @@ -0,0 +1,83 @@ +import { Schema } from "effect"; + +import { TrimmedNonEmptyString } from "./baseSchemas.ts"; +import { STATIC_KEYBINDING_COMMANDS } from "./keybindings.ts"; + +/** + * Only the user may trigger these: they send what the user wrote, listen to them, or pick + * work that may belong to another environment (undo and reopen history, new threads, hosts). + * Agents start threads with `t3_thread_launch` instead. + */ +const USER_ONLY_COMMANDS = new Set([ + "composer.sendAlternate", + "composer.sendBackground", + "composer.sendAndNewThread", + "composer.dictation", + "composer.cycleHost", + "thread.steerQueuedMessage", + "thread.undo", + "view.reopenClosed", + "chat.new", + "chat.newLocal", + "chat.newWithoutProject", +]); + +/** + * These change only the window's own view, so they run on any screen. The rest act on the + * thread or draft on screen, so they run only while it belongs to the agent's environment. + */ +export const VIEW_ONLY_APP_COMMANDS: ReadonlySet = new Set([ + "sidebar.toggle", + "navigation.back", + "navigation.forward", + "workspace.focusNext", + "workspace.focusPrevious", + "commandPalette.toggle", + "theme.select", + "appearance.cycle", + "themeEditor.toggle", + "thread.previous", + "thread.next", + "usage.open", + "usage.cost", + "usage.tokens", + "usage.limits", + "usage.period.day", + "usage.period.week", + "usage.period.month", + "usage.period.quarter", +]); + +/** Shortcut commands an agent may run in the user's window. */ +const APP_COMMANDS = STATIC_KEYBINDING_COMMANDS.filter( + (command) => !USER_ONLY_COMMANDS.has(command), +); +export const AppCommand = Schema.Literals(APP_COMMANDS); +export type AppCommand = typeof AppCommand.Type; + +export const AppControlRequest = Schema.Struct({ + requestId: TrimmedNonEmptyString, + command: AppCommand, +}); +export type AppControlRequest = typeof AppControlRequest.Type; + +export const AppControlSubscribeInput = Schema.Struct({ + /** Whether the window is in use as it subscribes, so a background reconnect is not. */ + focused: Schema.Boolean, +}); +export type AppControlSubscribeInput = typeof AppControlSubscribeInput.Type; + +export const AppControlResult = Schema.Literals([ + "ran", + /** Nothing on screen handles the command right now. */ + "not-handled", + /** The window isn't showing a thread or draft from the agent's environment. */ + "other-environment", +]); +export type AppControlResult = typeof AppControlResult.Type; + +export const AppControlResponseInput = Schema.Struct({ + requestId: TrimmedNonEmptyString, + result: AppControlResult, +}); +export type AppControlResponseInput = typeof AppControlResponseInput.Type; diff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.ts index 8dd47df33a21f..ac29a0a7986d7 100644 --- a/packages/contracts/src/index.ts +++ b/packages/contracts/src/index.ts @@ -2,6 +2,7 @@ export * from "./baseSchemas.ts"; export * from "./assistantCitations.ts"; export * from "./composerContext.ts"; export * from "./composerContextClipboard.ts"; +export * from "./appControl.ts"; export * from "./background.ts"; export * from "./acpRegistry.ts"; export * from "./auth.ts"; diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts index 0f6af19188e18..38e0649fe254c 100644 --- a/packages/contracts/src/rpc.ts +++ b/packages/contracts/src/rpc.ts @@ -82,6 +82,11 @@ import { AuthAccessStreamEvent, EnvironmentAuthorizationError, } from "./auth.ts"; +import { + AppControlRequest, + AppControlResponseInput, + AppControlSubscribeInput, +} from "./appControl.ts"; import { ClientActivityReportInput } from "./background.ts"; import { FilesystemGetMetadataInput, @@ -618,6 +623,8 @@ export const WS_METHODS = { worktreeSetupCancel: "worktreeSetup.cancel", subscribeTerminalMetadata: "subscribeTerminalMetadata", subscribePreviewEvents: "subscribePreviewEvents", + subscribeAppControl: "subscribeAppControl", + appControlRespond: "appControl.respond", subscribeDiscoveredLocalServers: "subscribeDiscoveredLocalServers", subscribeDeviceState: "subscribeDeviceState", subscribeServerConfig: "subscribeServerConfig", @@ -1690,6 +1697,18 @@ const WsSubscribePreviewEventsRpc = Rpc.make(WS_METHODS.subscribePreviewEvents, stream: true, }); +const WsSubscribeAppControlRpc = Rpc.make(WS_METHODS.subscribeAppControl, { + payload: AppControlSubscribeInput, + success: AppControlRequest, + error: EnvironmentAuthorizationError, + stream: true, +}); + +const WsAppControlRespondRpc = Rpc.make(WS_METHODS.appControlRespond, { + payload: AppControlResponseInput, + error: EnvironmentAuthorizationError, +}); + const WsPreviewStopLocalServerRpc = Rpc.make(WS_METHODS.previewStopLocalServer, { payload: PreviewStopLocalServerInput, error: Schema.Union([PreviewStopLocalServerError, EnvironmentAuthorizationError]), @@ -2243,6 +2262,8 @@ export const WsRpcGroup = RpcGroup.make( WsPreviewReportProfilesRpc, WsPreviewReportStatusRpc, WsSubscribePreviewEventsRpc, + WsSubscribeAppControlRpc, + WsAppControlRespondRpc, WsPreviewStopLocalServerRpc, WsSubscribeDiscoveredLocalServersRpc, WsDeviceConfigureRpc, diff --git a/packages/shared/src/t3McpToolPresentation.ts b/packages/shared/src/t3McpToolPresentation.ts index 9742639f9a801..d6e27fd1de9b2 100644 --- a/packages/shared/src/t3McpToolPresentation.ts +++ b/packages/shared/src/t3McpToolPresentation.ts @@ -55,6 +55,7 @@ export type T3McpToolSummaryAction = | "environment-link" | "environment-unlink" | "environment-update" + | "app-command" | "attachment-prepare" | "attachment-discard" | "attachment-send" @@ -370,6 +371,7 @@ const T3_MCP_TOOLS: Readonly> = { ["Remove", "Removing", "Removed", "a keyboard shortcut"], "environment-update", ), + t3_app_command: tool(["Run", "Running", "Ran", "an app command"], "app-command"), t3_thread_launch: tool(["Launch", "Launching", "Launched", "a project thread"], "thread-create"), t3_project_list: tool(["List", "Listing", "Listed", "projects"], "project-list"), t3_project_read: tool(["Read", "Reading", "Read", "a project"], "project-read"), From 685633e9af4d9f5b6613066bb148f27be17a501f Mon Sep 17 00:00:00 2001 From: Batch Processor <46352227+batchema@users.noreply.github.com> Date: Fri, 13 Nov 2026 12:00:10 -0500 Subject: [PATCH 09/20] feat: agents can navigate the app and run palette thread actions (#8) --- apps/server/src/appControl/AppControl.test.ts | 17 ++-- apps/server/src/appControl/AppControl.ts | 10 +-- .../mcp/toolkits/environment/handlers.test.ts | 22 ++++- .../src/mcp/toolkits/environment/handlers.ts | 78 ++++++++++++----- .../src/mcp/toolkits/environment/tools.ts | 12 +++ .../src/provider/agentContextBudget.json | 2 +- apps/web/src/components/ChatView.tsx | 39 ++++++++- apps/web/src/components/CommandPalette.tsx | 66 ++++++-------- .../src/components/settings/settingsSearch.ts | 32 ++----- apps/web/src/hooks/useRestartAgentSession.ts | 50 +++++++++++ apps/web/src/lib/appControl.ts | 57 ++++++++++-- .../src/lib/navigateSettled.browser.test.tsx | 87 +++++++++++++++++++ apps/web/src/lib/navigateSettled.ts | 15 ++++ evals/mcp-tool-use/cases/settings.ndjson | 1 + packages/client-runtime/src/t3ToolSummary.ts | 3 + packages/contracts/src/appControl.ts | 48 +++++++++- packages/contracts/src/keybindings.ts | 4 + packages/shared/src/t3McpToolPresentation.ts | 2 + 18 files changed, 432 insertions(+), 113 deletions(-) create mode 100644 apps/web/src/hooks/useRestartAgentSession.ts create mode 100644 apps/web/src/lib/navigateSettled.browser.test.tsx create mode 100644 apps/web/src/lib/navigateSettled.ts diff --git a/apps/server/src/appControl/AppControl.test.ts b/apps/server/src/appControl/AppControl.test.ts index 311676b3ffcba..dd8f863040a7a 100644 --- a/apps/server/src/appControl/AppControl.test.ts +++ b/apps/server/src/appControl/AppControl.test.ts @@ -1,6 +1,6 @@ import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import { expect, it } from "@effect/vitest"; -import { AuthSessionId } from "@t3tools/contracts"; +import { type AppCommand, AuthSessionId } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; import * as Option from "effect/Option"; @@ -9,6 +9,7 @@ import * as TestClock from "effect/testing/TestClock"; import * as AppControl from "./AppControl.ts"; +const commandAction = (command: AppCommand) => ({ _tag: "command", command }) as const; const makeAppControl = AppControl.make.pipe(Effect.provide(NodeCrypto.layer)); const desktop = { sessionId: AuthSessionId.make("desktop"), windowId: "socket-a:0" }; const browser = { sessionId: AuthSessionId.make("browser"), windowId: "socket-b:0" }; @@ -22,7 +23,7 @@ it.effect("runs a command in the window used most recently and returns its answe const browserRequests = yield* appControl.connect(browser, true); // A tab connecting in the background doesn't take over from the one in use. yield* appControl.connect(browserTab, false).pipe(Effect.asVoid); - const toBrowser = yield* appControl.run("sidebar.toggle").pipe(Effect.forkChild); + const toBrowser = yield* appControl.run(commandAction("sidebar.toggle")).pipe(Effect.forkChild); const browserRequest = Option.getOrThrow(yield* Stream.runHead(browserRequests)); yield* appControl.respond(browser.sessionId, { requestId: browserRequest.requestId, @@ -30,9 +31,9 @@ it.effect("runs a command in the window used most recently and returns its answe }); expect(yield* Fiber.join(toBrowser)).toBe("ran"); yield* appControl.reportFocus(desktop, true); - const run = yield* appControl.run("terminal.toggle").pipe(Effect.forkChild); + const run = yield* appControl.run(commandAction("terminal.toggle")).pipe(Effect.forkChild); const request = Option.getOrThrow(yield* Stream.runHead(desktopRequests)); - expect(request.command).toBe("terminal.toggle"); + expect(request.action).toEqual(commandAction("terminal.toggle")); // Another session cannot answer for this window. yield* appControl.respond(browser.sessionId, { requestId: request.requestId, result: "ran" }); yield* appControl.respond(desktop.sessionId, { @@ -47,11 +48,11 @@ it.effect("fails when no window is open or the window does not answer", () => Effect.gen(function* () { const appControl = yield* makeAppControl; yield* Effect.scoped(appControl.connect(desktop, true).pipe(Effect.asVoid)); - expect(yield* appControl.run("terminal.toggle").pipe(Effect.flip)).toBeInstanceOf( - AppControl.AppControlNoWindowError, - ); + expect( + yield* appControl.run(commandAction("terminal.toggle")).pipe(Effect.flip), + ).toBeInstanceOf(AppControl.AppControlNoWindowError); const requests = yield* appControl.connect(desktop, true); - const run = yield* appControl.run("terminal.toggle").pipe(Effect.forkChild); + const run = yield* appControl.run(commandAction("terminal.toggle")).pipe(Effect.forkChild); yield* Stream.runHead(requests); yield* TestClock.adjust("5 seconds"); expect(yield* Fiber.join(run).pipe(Effect.flip)).toBeInstanceOf( diff --git a/apps/server/src/appControl/AppControl.ts b/apps/server/src/appControl/AppControl.ts index 16206a237f779..86bdb41125a37 100644 --- a/apps/server/src/appControl/AppControl.ts +++ b/apps/server/src/appControl/AppControl.ts @@ -1,5 +1,5 @@ import type { - AppCommand, + AppAction, AppControlRequest, AppControlResponseInput, AppControlResult, @@ -49,9 +49,9 @@ export class AppControl extends Context.Service< sessionId: AuthSessionId, response: AppControlResponseInput, ) => Effect.Effect; - /** Runs a command in the window used most recently, returning what the window answered. */ + /** Runs an action in the window used most recently, returning what the window answered. */ readonly run: ( - command: AppCommand, + action: AppAction, ) => Effect.Effect; } >()("t3/appControl/AppControl") {} @@ -136,7 +136,7 @@ export const make = Effect.gen(function* () { }, ); - const run: AppControl["Service"]["run"] = Effect.fn("AppControl.run")(function* (command) { + const run: AppControl["Service"]["run"] = Effect.fn("AppControl.run")(function* (action) { const requestId = yield* random.uuidV4(); const deferred = yield* Deferred.make(); const target = yield* Ref.modify(state, (current) => { @@ -158,7 +158,7 @@ export const make = Effect.gen(function* () { pending.delete(requestId); return { ...current, pending }; }); - return yield* Queue.offer(target.queue, { requestId, command }).pipe( + return yield* Queue.offer(target.queue, { requestId, action }).pipe( Effect.andThen(Deferred.await(deferred).pipe(Effect.timeoutOption(RESPONSE_TIMEOUT))), Effect.flatMap( Option.match({ diff --git a/apps/server/src/mcp/toolkits/environment/handlers.test.ts b/apps/server/src/mcp/toolkits/environment/handlers.test.ts index 5299979e3d583..f1b05b46c9efc 100644 --- a/apps/server/src/mcp/toolkits/environment/handlers.test.ts +++ b/apps/server/src/mcp/toolkits/environment/handlers.test.ts @@ -72,7 +72,10 @@ const makeLayer = Effect.fn(function* ( issuedAt: 0, }), Layer.mock(ThreadManagement.ThreadManagementService)({ - getThreadShell: () => Ref.get(caller).pipe(Effect.tap(() => onGetThreadShell)), + getThreadShell: (id) => + id === threadId + ? Ref.get(caller).pipe(Effect.tap(() => onGetThreadShell)) + : Effect.succeed(null), }), Layer.mock(Environment.ServerEnvironment)({ getDescriptor: Effect.succeed({ @@ -248,3 +251,20 @@ it.effect("says when the user's window cannot run an app command", () => } }), ); + +it.effect("shows a thread from this environment in the user's window, and no other", () => + Effect.gen(function* () { + const { layer, writes } = yield* makeLayer(); + yield* Effect.gen(function* () { + expect(yield* call("t3_app_navigate", { to: { page: "thread", threadId } })).toEqual({ + ran: true, + }); + expect( + yield* call("t3_app_navigate", { + to: { page: "thread", threadId: ThreadId.make("thread:elsewhere") }, + }), + ).toMatchObject({ code: "thread_not_found" }); + expect(yield* Ref.get(writes)).toBe(1); + }).pipe(Effect.provide(layer)); + }), +); diff --git a/apps/server/src/mcp/toolkits/environment/handlers.ts b/apps/server/src/mcp/toolkits/environment/handlers.ts index 82ec34b77c1fa..af6a6bff52718 100644 --- a/apps/server/src/mcp/toolkits/environment/handlers.ts +++ b/apps/server/src/mcp/toolkits/environment/handlers.ts @@ -1,4 +1,5 @@ import { + type AppAction, AppCommand, KeybindingRule, OrchestratorMcpFailure, @@ -19,7 +20,8 @@ import * as ThreadCommandExecutor from "../../../orchestration-v2/ThreadCommandE import * as Settings from "../../../serverSettings.ts"; import * as McpInvocationContext from "../../McpInvocationContext.ts"; import * as McpToolAccess from "../../McpToolAccess.ts"; -import { readCaller, unavailable } from "../../threadAccess.ts"; +import * as ThreadManagement from "../../../orchestration-v2/ThreadManagementService.ts"; +import { readCaller, threadNotFound, unavailable } from "../../threadAccess.ts"; import { EnvironmentToolkit } from "./tools.ts"; export function preferences(settings: ServerSettings) { @@ -120,6 +122,28 @@ const access = Effect.gen(function* () { }; }); +/** Runs an action in the user's window, failing with `refusals` when the window declines it. */ +const runInWindow = Effect.fn("EnvironmentTools.runInWindow")(function* ( + appControl: AppControl.AppControl["Service"], + action: AppAction, + refusals: Record<"other-environment" | "not-handled", string>, +) { + const failed = (message: string) => + Effect.fail(new OrchestratorMcpFailure({ code: "orchestration_error", message })); + const result = yield* appControl.run(action).pipe( + Effect.catchTags({ + AppControlNoWindowError: () => + failed("No T3 Code window is open on this environment. Mobile apps don't take commands."), + AppControlTimeoutError: () => + failed( + "The user's window didn't answer. It may still act when it wakes, so check before retrying.", + ), + }), + ); + if (result !== "ran") return yield* invalid(refusals[result]); + return { ran: true }; +}); + /** Runs a write under the caller thread's lock, rechecking access once the lock is held. */ const writeLocked = Effect.fn("EnvironmentTools.writeLocked")(function* ( check: Effect.Effect, @@ -257,29 +281,37 @@ export const layer = McpToolAccess.toLayer(EnvironmentToolkit, { ), ); const { appControl } = yield* access; - const failed = (message: string) => - Effect.fail(new OrchestratorMcpFailure({ code: "orchestration_error", message })); - const result = yield* appControl.run(appCommand).pipe( - Effect.catchTags({ - AppControlNoWindowError: () => - failed( - "No T3 Code window is open on this environment. Mobile apps don't take commands.", - ), - AppControlTimeoutError: () => - failed( - "The user's window didn't answer. It may still run the command when it wakes, so check before retrying.", - ), - }), + return yield* runInWindow( + appControl, + { _tag: "command", command: appCommand }, + { + "other-environment": `\`${command}\` runs only while the user's window shows a thread or draft from this environment.`, + "not-handled": `Nothing in the user's window handles \`${command}\` right now, such as a thread command outside a thread.`, + }, + ); + }), + ), + t3_app_navigate: McpToolAccess.writesEnvironment(({ to }) => + Effect.gen(function* () { + const { appControl } = yield* access; + if (to.page === "thread") { + const threads = yield* ThreadManagement.ThreadManagementService; + const shell = yield* threads.getThreadShell(to.threadId).pipe(Effect.mapError(unavailable)); + if (shell === null || shell.deletedAt !== null) + return yield* threadNotFound( + threads, + to.threadId, + `Thread ${to.threadId} was not found.`, + ); + } + return yield* runInWindow( + appControl, + { _tag: "navigate", to }, + { + "other-environment": "The user's window can't show that page.", + "not-handled": "The user's window can't show that page.", + }, ); - if (result === "other-environment") - return yield* invalid( - `\`${command}\` runs only while the user's window shows a thread or draft from this environment.`, - ); - if (result === "not-handled") - return yield* invalid( - `Nothing in the user's window handles \`${command}\` right now, such as a thread command outside a thread.`, - ); - return { ran: true }; }), ), }); diff --git a/apps/server/src/mcp/toolkits/environment/tools.ts b/apps/server/src/mcp/toolkits/environment/tools.ts index 541fbbd1ac507..a75cf8172b653 100644 --- a/apps/server/src/mcp/toolkits/environment/tools.ts +++ b/apps/server/src/mcp/toolkits/environment/tools.ts @@ -1,4 +1,5 @@ import { + AppDestination, BackgroundActivityProfileSelection, ExecutionEnvironmentDescriptor, OrchestratorMcpEnvironmentTarget, @@ -135,6 +136,16 @@ const AppCommandTool = Tool.make("t3_app_command", { }), success: Schema.Struct({ ran: Schema.Boolean }), }).annotate(Tool.Destructive, true); +const AppNavigateTool = Tool.make("t3_app_navigate", { + ...shared, + description: + "Show a page in the user's T3 Code window, the one they used last: a thread from this environment, a settings section, usage, or pull requests. Live full-access or default caller thread only.", + parameters: Schema.Struct({ + environmentId: OrchestratorMcpEnvironmentTarget, + to: AppDestination, + }), + success: Schema.Struct({ ran: Schema.Boolean }), +}); export const EnvironmentToolkit = Toolkit.make( EnvironmentReadTool, SettingsReadTool, @@ -143,4 +154,5 @@ export const EnvironmentToolkit = Toolkit.make( KeybindingUpsertTool, KeybindingRemoveTool, AppCommandTool, + AppNavigateTool, ); diff --git a/apps/server/src/provider/agentContextBudget.json b/apps/server/src/provider/agentContextBudget.json index 01973bac6d369..c2c319936edf4 100644 --- a/apps/server/src/provider/agentContextBudget.json +++ b/apps/server/src/provider/agentContextBudget.json @@ -1,5 +1,5 @@ { "claudeSystemAppendBytes": 5597, "codexAdditionalContextBytes": 7327, - "mcpToolListJsonBytes": 50094 + "mcpToolListJsonBytes": 51085 } diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 337d1b2c74f39..54742cb3287c6 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -48,7 +48,7 @@ import { freshSessionBannerItem } from "./chat/ComposerFreshSession"; import { armFreshSession, disarmFreshSession, useFreshSessionArmed } from "./chat/freshSessionArms"; import { useUsageLimitsPanel } from "./chat/useUsageLimitsPanel"; import { useWorktreeSetup } from "./chat/useWorktreeSetup"; -import { useChatShortcuts } from "./chat/useChatShortcuts"; +import { type ChatShortcutCommands, useChatShortcuts } from "./chat/useChatShortcuts"; import { ChatBannerLane } from "./chat/ChatBannerLane"; import * as Schema from "effect/Schema"; import { @@ -177,7 +177,14 @@ import { usePreviewMiniPlayerStore, } from "../previewMiniPlayerStore"; import { threadPullRequestPanelTarget } from "./pullRequest/pullRequestDetail.logic"; -import { LinkPullRequestDialogHost } from "./pullRequest/LinkPullRequestDialog"; +import { + LinkPullRequestDialogHost, + openLinkPullRequestDialog, +} from "./pullRequest/LinkPullRequestDialog"; +import { canShareWithGuestAtom } from "./chat/guestShareAvailability"; +import { openGuestShareDialog } from "./chat/guestShareDialogState"; +import { threadPullRequestLinkMode } from "@t3tools/client-runtime/thread-pull-request-compatibility"; +import { useRestartAgentSession } from "../hooks/useRestartAgentSession"; import { GuestPendingMessages } from "./chat/GuestShareControls"; import { useDeviceState } from "~/state/device"; import { BranchToolbar, type BranchToolbarHandle } from "./BranchToolbar"; @@ -2699,6 +2706,33 @@ export default function ChatView(props: ChatViewProps) { } }); + const restartAgentSession = useRestartAgentSession(); + const canShareWithGuest = useAtomValue(canShareWithGuestAtom(environmentId)); + // The palette offers these too, through the same shortcuts. + const serverThreadShortcuts: ChatShortcutCommands = { + "thread.restartSession": ({ event }) => { + if (serverThread === null) return false; + if (!event.repeat) void restartAgentSession(serverThread, activeProjectCwd); + }, + "thread.showPullRequests": () => { + if (!pullRequestsSurfaceAvailable || activeThreadRef === null) return false; + useRightPanelStore.getState().open(activeThreadRef, "pull-requests"); + }, + "thread.linkPullRequest": () => { + if ( + !isServerThread || + activeThreadRef === null || + threadPullRequestLinkMode(serverConfig?.environment.capabilities) === "unsupported" + ) + return false; + openLinkPullRequestDialog(activeThreadRef); + }, + "thread.shareWithGuest": () => { + if (!isServerThread || activeThreadRef === null || !canShareWithGuest) return false; + openGuestShareDialog(activeThreadRef); + }, + }; + useChatShortcuts({ enabled: activeThreadId !== null && !backgroundThread, embedded, @@ -2717,6 +2751,7 @@ export default function ChatView(props: ChatViewProps) { ...terminalShortcuts, ...rightPanelShortcuts, ...threadLifecycleShortcuts, + ...serverThreadShortcuts, "thread.copyReference": ({ event }) => { if (!event.repeat) copyActiveThreadReference(); }, diff --git a/apps/web/src/components/CommandPalette.tsx b/apps/web/src/components/CommandPalette.tsx index 126fac928909b..9f753a32ad478 100644 --- a/apps/web/src/components/CommandPalette.tsx +++ b/apps/web/src/components/CommandPalette.tsx @@ -48,6 +48,7 @@ import { AuthFilesystemReadScope, type DesktopWslState, type EnvironmentId, + type KeybindingCommand, type FilesystemBrowseResult, SourceControlProviderKind, PRIMARY_LOCAL_ENVIRONMENT_ID, @@ -118,10 +119,10 @@ import { filesystemEnvironment, useFilesystemReadAccess } from "../state/filesys import { projectEnvironment } from "../state/projects"; import { useEnvironmentQuery } from "../state/query"; import { serverEnvironment } from "../state/server"; -import { threadEnvironment } from "../state/threads"; import { readEnvironmentScope, useEnvironmentScope } from "~/state/session"; import { sourceControlEnvironment } from "../state/sourceControl"; import { useAtomCommand } from "../state/use-atom-command"; +import { useRestartAgentSession } from "../hooks/useRestartAgentSession"; import { useOrchestrationCommand } from "../state/use-orchestration-command"; import { useAtomQueryRunner } from "../state/use-atom-query-runner"; import { useScratchProject } from "../hooks/useScratchProject"; @@ -301,6 +302,16 @@ function openIntentView(intent: CommandPaletteOpenIntent | null): CommandPalette const NEW_THREAD_NO_PROJECT_VALUE = "new-thread-in:no-project"; +const PALETTE_ITEM_COMMANDS = new Set([ + "chat.new", + "chat.newLocal", + "chat.newWithoutProject", + "thread.restartSession", + "thread.showPullRequests", + "thread.linkPullRequest", + "thread.shareWithGuest", +]); + export function CommandPalette({ children }: { children: ReactNode }) { useCommandPaletteMount(); const state = useCommandPaletteStore(); @@ -462,12 +473,7 @@ function OpenCommandPaletteDialog(props: { const startProjectClone = useAtomCommand(sourceControlEnvironment.startProjectClone, { reportFailure: false, }); - const stopThreadSession = useAtomCommand(threadEnvironment.stopSession, { - reportFailure: false, - }); - const refreshProviders = useAtomCommand(serverEnvironment.refreshProviders, { - reportFailure: false, - }); + const restartAgentSession = useRestartAgentSession(); const { environments } = useEnvironments(); const desktopLocalBootstraps = useDesktopLocalBootstraps(); const primaryEnvironmentId = usePrimaryEnvironmentId(); @@ -1422,6 +1428,7 @@ function OpenCommandPaletteDialog(props: { searchTerms: ["link", "pull request", "pr", "attach", "stack"], title: "Link pull request to thread", icon: , + shortcutCommand: "thread.linkPullRequest", run: async () => { openLinkPullRequestDialog(threadRef); }, @@ -1433,6 +1440,7 @@ function OpenCommandPaletteDialog(props: { title: "Show linked pull requests", disabled: visibleThreadPullRequests(activeThread.pullRequests).length === 0, icon: , + shortcutCommand: "thread.showPullRequests", run: async () => { useRightPanelStore.getState().open(threadRef, "pull-requests"); }, @@ -1447,6 +1455,7 @@ function OpenCommandPaletteDialog(props: { searchTerms: ["share", "guest", "invite", "link", "teammate"], title: "Share with guest", icon: , + shortcutCommand: "thread.shareWithGuest", run: async () => { openGuestShareDialog(threadRef); }, @@ -1461,32 +1470,12 @@ function OpenCommandPaletteDialog(props: { searchTerms: ["restart", "reset", "reload", "agent", "session", "skills", "plugins", "mcp"], title: "Restart agent session", icon: , - run: async () => { - const { environmentId } = thread; - if (thread.runtime !== null) { - const stopped = await stopThreadSession({ - environmentId, - input: { threadId: thread.id }, - }); - if (stopped._tag === "Failure") throw squashAtomCommandFailure(stopped); - } - toastManager.add({ - type: "success", - title: "Agent session will restart", - description: "Your next message starts a fresh session.", - }); - const project = projectByKey.get(`${environmentId}:${thread.projectId}`); - if (!project) return; - const refreshed = await refreshProviders({ - environmentId, - input: { - instanceId: thread.runtime?.providerInstanceId ?? thread.modelSelection.instanceId, - cwd: thread.worktreePath ?? project.workspaceRoot, - fresh: true, - }, - }); - if (refreshed._tag === "Failure") throw squashAtomCommandFailure(refreshed); - }, + shortcutCommand: "thread.restartSession", + run: () => + restartAgentSession( + thread, + projectByKey.get(`${thread.environmentId}:${thread.projectId}`)?.workspaceRoot ?? null, + ), }); } @@ -2537,16 +2526,15 @@ function OpenCommandPaletteDialog(props: { return; } } - // Global new-thread handlers ignore shortcuts while the palette is open. + // Global new-thread and thread handlers ignore shortcuts while the palette is open. const isJump = threadJumpIndexFromCommand(command ?? "") !== null; - const isNewThread = + const isItemCommand = !event.nativeEvent.isComposing && event.keyCode !== 229 && - (command === "chat.new" || - command === "chat.newLocal" || - command === "chat.newWithoutProject"); + command !== null && + PALETTE_ITEM_COMMANDS.has(command); const matchingItem = - isJump || isNewThread + isJump || isItemCommand ? displayedGroups .flatMap((group) => group.items) .find((item) => item.shortcutCommand === command) diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts index f0bbffbeddb06..f6f5b512c6386 100644 --- a/apps/web/src/components/settings/settingsSearch.ts +++ b/apps/web/src/components/settings/settingsSearch.ts @@ -1,7 +1,11 @@ import { HOSTED_APP_CHANNEL } from "~/branding"; import { isElectron, isSecretsFeatureEnabled } from "~/env"; import { isMacPlatform, isWindowsPlatform, normalizeSearchText } from "~/lib/utils"; -import { STATIC_KEYBINDING_COMMANDS, type KeybindingCommand } from "@t3tools/contracts"; +import { + type AppSettingsSection, + STATIC_KEYBINDING_COMMANDS, + type KeybindingCommand, +} from "@t3tools/contracts"; import type { EnvironmentId } from "@t3tools/contracts"; import type { EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection"; import { @@ -15,30 +19,8 @@ import { writeLocalStorageValue } from "../../hooks/useLocalStorage"; import { commandLabel } from "./KeybindingsSettings.logic"; import type { ResolvedSettingsScope } from "./settingsScope"; -export type SettingsPath = - | "/settings/projects" - | "/settings/general" - | "/settings/diagnostics" - | "/settings/voice" - | "/settings/appearance" - | "/settings/chat" - | "/settings/diffs" - | "/settings/keybindings" - | "/settings/snap-shot" - | "/settings/providers" - | "/settings/threads" - | "/settings/browser" - | "/settings/devices" - | "/settings/scheduled-tasks" - | "/settings/source-control" - | "/settings/worktrees" - | "/settings/connections" - | "/settings/access" - | "/settings/secrets" - | "/settings/maintenance" - | "/settings/labs" - | "/settings/about" - | "/settings/archived"; +/** Agents open these sections too, so the list lives in contracts. */ +export type SettingsPath = `/settings/${AppSettingsSection}`; export type SettingsSearchScope = | "environment" diff --git a/apps/web/src/hooks/useRestartAgentSession.ts b/apps/web/src/hooks/useRestartAgentSession.ts new file mode 100644 index 0000000000000..98a4c52aa768e --- /dev/null +++ b/apps/web/src/hooks/useRestartAgentSession.ts @@ -0,0 +1,50 @@ +import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; + +import { toastManager } from "../components/ui/toast"; +import { serverEnvironment } from "../state/server"; +import { threadEnvironment } from "../state/threads"; +import { useAtomCommand } from "../state/use-atom-command"; +import type { Thread } from "../types"; + +/** Stops the thread's agent session so the next message starts fresh, with providers reloaded. */ +export function useRestartAgentSession() { + const stopThreadSession = useAtomCommand(threadEnvironment.stopSession, { + reportFailure: false, + }); + const refreshProviders = useAtomCommand(serverEnvironment.refreshProviders, { + reportFailure: false, + }); + const restart = async ( + thread: Pick, + workspaceRoot: string | null, + ) => { + const { environmentId } = thread; + if (thread.runtime !== null) { + const stopped = await stopThreadSession({ environmentId, input: { threadId: thread.id } }); + if (stopped._tag === "Failure") throw squashAtomCommandFailure(stopped); + } + toastManager.add({ + type: "success", + title: "Agent session will restart", + description: "Your next message starts a fresh session.", + }); + if (workspaceRoot === null) return; + const refreshed = await refreshProviders({ + environmentId, + input: { + instanceId: thread.runtime?.providerInstanceId ?? thread.modelSelection.instanceId, + cwd: thread.worktreePath ?? workspaceRoot, + fresh: true, + }, + }); + if (refreshed._tag === "Failure") throw squashAtomCommandFailure(refreshed); + }; + return (...args: Parameters) => + restart(...args).catch((error: unknown) => { + toastManager.add({ + type: "error", + title: "Unable to restart agent session", + description: error instanceof Error ? error.message : "An unexpected error occurred.", + }); + }); +} diff --git a/apps/web/src/lib/appControl.ts b/apps/web/src/lib/appControl.ts index ae0bed35e719f..5befbd12c554b 100644 --- a/apps/web/src/lib/appControl.ts +++ b/apps/web/src/lib/appControl.ts @@ -1,22 +1,33 @@ import { EnvironmentRegistry } from "@t3tools/client-runtime/connection"; +import { scopeThreadRef } from "@t3tools/client-runtime/environment"; import { request, subscribeDynamic } from "@t3tools/client-runtime/rpc"; import { + type AppAction, type AppCommand, type AppControlResult, + type AppDestination, + EnvironmentId, VIEW_ONLY_APP_COMMANDS, WS_METHODS, } from "@t3tools/contracts"; -import type { AnyRouter } from "@tanstack/react-router"; +import type { AnyRouter, NavigateOptions } from "@tanstack/react-router"; import * as Effect from "effect/Effect"; import * as Stream from "effect/Stream"; import * as SubscriptionRef from "effect/SubscriptionRef"; import { useComposerDraftStore } from "../composerDraftStore"; +import { readPullRequestListPreferences } from "../components/pullRequest/pullRequestListPreferences"; +import type { SettingsPath } from "../components/settings/settingsSearch"; import { connectionAtomRuntime } from "../connection/runtime"; import { appAtomRegistry } from "../rpc/atomRegistry"; import { runCommand } from "../shortcuts/dispatcher"; +import { waitForThreadShell } from "../state/entities"; +import { navigateSettled } from "./navigateSettled"; import { resolveThreadRouteTarget } from "../threadRoutes"; +// The server stops waiting for an answer after this long. +const RESPONSE_DEADLINE = "5 seconds"; + /** Runs the commands agents send this window, from every environment it is connected to. */ export function startAppControl(router: AnyRouter): () => void { // Outside view-only commands, a command runs only on its own environment's thread or draft, @@ -38,6 +49,36 @@ export function startAppControl(router: AnyRouter): () => void { } return runCommand(command) ? "ran" : "not-handled"; }; + const destination = (environmentId: string, to: AppDestination): NavigateOptions => { + switch (to.page) { + case "thread": + return { + to: "/$environmentId/$threadId", + params: { environmentId, threadId: to.threadId }, + } as const; + case "settings": { + // Straight to a section: `/settings` redirects, which would look like a blocked move. + const path: SettingsPath = `/settings/${to.section ?? "general"}`; + return { to: path }; + } + case "usage": + return { to: "/usage" } as const; + case "pull-requests": + return { to: "/pull-requests", search: readPullRequestListPreferences() } as const; + } + }; + const act = async (environmentId: string, action: AppAction): Promise => { + if (action._tag === "command") return run(environmentId, action.command); + const { to } = action; + if (!(await navigateSettled(router, destination(environmentId, to)))) return "not-handled"; + // An older thread mounts its chat only once its row loads, after the route has settled. + if ( + to.page === "thread" && + !(await waitForThreadShell(scopeThreadRef(EnvironmentId.make(environmentId), to.threadId))) + ) + return "not-handled"; + return "ran"; + }; const focused = Effect.sync(() => ({ focused: document.hasFocus() && document.visibilityState === "visible", })); @@ -56,11 +97,15 @@ export function startAppControl(router: AnyRouter): () => void { registry.followStream( environmentId, subscribeDynamic(WS_METHODS.subscribeAppControl, () => focused).pipe( - Stream.mapEffect(({ requestId, command }) => - request(WS_METHODS.appControlRespond, { - requestId, - result: run(environmentId, command), - }).pipe(Effect.ignoreCause), + Stream.mapEffect(({ requestId, action }) => + // Requests run in order, so one that never settles must not hold the rest. + Effect.promise(() => act(environmentId, action)).pipe( + Effect.timeout(RESPONSE_DEADLINE), + Effect.flatMap((result) => + request(WS_METHODS.appControlRespond, { requestId, result }), + ), + Effect.ignoreCause, + ), ), Stream.ignoreCause, ), diff --git a/apps/web/src/lib/navigateSettled.browser.test.tsx b/apps/web/src/lib/navigateSettled.browser.test.tsx new file mode 100644 index 0000000000000..791bd30916fd2 --- /dev/null +++ b/apps/web/src/lib/navigateSettled.browser.test.tsx @@ -0,0 +1,87 @@ +import { + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, + Outlet, + redirect, + RouterProvider, +} from "@tanstack/react-router"; +import { describe, expect, it, vi } from "vite-plus/test"; + +import { render } from "../../test/render"; +import { navigateSettled } from "./navigateSettled"; + +function makeRouter(input: { nextLoader: () => Promise; redirect: boolean }) { + const root = createRootRoute({ component: Outlet }); + const home = createRoute({ getParentRoute: () => root, path: "/", component: () =>

home

}); + const next = createRoute({ + getParentRoute: () => root, + path: "/usage", + beforeLoad: () => { + if (input.redirect) throw redirect({ to: "/settings/general" }); + }, + loader: input.nextLoader, + component: () =>

usage

, + }); + const settings = createRoute({ + getParentRoute: () => root, + path: "/settings/general", + component: () =>

settings

, + }); + const thread = createRoute({ + getParentRoute: () => root, + path: "/$environmentId/$threadId", + component: () =>

thread

, + }); + return createRouter({ + routeTree: root.addChildren([home, next, settings, thread]), + history: createMemoryHistory({ initialEntries: ["/"] }), + }); +} + +describe("navigateSettled", () => { + it("resolves once the destination is on screen, not when navigation starts", async () => { + let openGate = () => {}; + const gate = new Promise((resolve) => { + openGate = resolve; + }); + const router = makeRouter({ nextLoader: () => gate, redirect: false }); + // The test needs its own route tree, with a loader that holds navigation pending. + // Its paths reuse app routes so the registered route types accept them. + await using screen = await render(, { router: false }); + await expect.element(screen.getByText("home")).toBeInTheDocument(); + + let settled = false; + const navigated = navigateSettled(router, { to: "/usage" }).finally(() => { + settled = true; + }); + await vi.waitFor(() => expect(router.state.status).toBe("pending")); + expect(settled).toBe(false); + + openGate(); + expect(await navigated).toBe(true); + expect(screen.container.textContent).toBe("usage"); + }); + + it("resolves false when the window ends up somewhere else", async () => { + const router = makeRouter({ nextLoader: async () => {}, redirect: true }); + // The test needs its own route tree, with a route that redirects elsewhere. + await using screen = await render(, { router: false }); + await expect.element(screen.getByText("home")).toBeInTheDocument(); + + expect(await navigateSettled(router, { to: "/usage" })).toBe(false); + await expect.element(screen.getByText("settings")).toBeInTheDocument(); + }); + + it("arrives at a thread whose id needs encoding in the URL", async () => { + const router = makeRouter({ nextLoader: async () => {}, redirect: false }); + // The test needs its own route tree; this one mirrors the app's thread route. + await using screen = await render(, { router: false }); + await expect.element(screen.getByText("home")).toBeInTheDocument(); + + const params = { environmentId: "environment", threadId: "mcp:thread" }; + expect(await navigateSettled(router, { to: "/$environmentId/$threadId", params })).toBe(true); + expect(screen.container.textContent).toBe("thread"); + }); +}); diff --git a/apps/web/src/lib/navigateSettled.ts b/apps/web/src/lib/navigateSettled.ts new file mode 100644 index 0000000000000..b02997f5dfea1 --- /dev/null +++ b/apps/web/src/lib/navigateSettled.ts @@ -0,0 +1,15 @@ +import type { AnyRouter, NavigateOptions } from "@tanstack/react-router"; + +/** + * Navigates and resolves once the destination is on screen, so a command sent next reaches it. + * Resolves false when the window ends up elsewhere, such as after a redirect. A blocked navigation + * never settles (TanStack leaves it pending), so callers bound the wait. + */ +export async function navigateSettled( + router: AnyRouter, + options: NavigateOptions, +): Promise { + const target = router.buildLocation(options).pathname; + if (router.state.location.pathname !== target) await router.navigate(options); + return router.state.location.pathname === target; +} diff --git a/evals/mcp-tool-use/cases/settings.ndjson b/evals/mcp-tool-use/cases/settings.ndjson index 991ea4754d3d1..ab730a715531f 100644 --- a/evals/mcp-tool-use/cases/settings.ndjson +++ b/evals/mcp-tool-use/cases/settings.ndjson @@ -1,2 +1,3 @@ {"id": "labs-setting-uses-settings-update", "area": "settings", "kind": "bad", "pattern": "edit settings.json by hand", "experience": "Asked to turn on the Linked environments Labs switch on a headless box, an agent had no tool for it and told the user to write the server's settings.json by hand.", "rule": "t3_environment_settings_update: Change this server's settings.", "privacy": "commit-safe", "setup": {"role": "top", "mocks": {"t3_environment_settings_read": {"settings": {"linkedEnvironmentsEnabled": false, "guestSharingEnabled": false, "promptSuggestionsEnabled": false}}, "t3_environment_settings_update": {"settings": {"linkedEnvironmentsEnabled": true}}}}, "prompt": "Turn on the linked environments beta on this machine. There's no T3 Code window open on it.", "expect": {"calls": [{"tool": "t3_environment_settings_update", "args": {"patch.linkedEnvironmentsEnabled": true}}], "shellMustNot": ["settings\\.json"]}, "maxSteps": 6} {"id": "open-panel-uses-app-command", "area": "settings", "kind": "bad", "pattern": "tell the user to press the shortcut", "experience": "Asked to open the terminal in the user's T3 Code window, an agent had no way to act on the window and told the user which shortcut to press.", "rule": "t3_app_command: Run a command from `t3_keybindings_read` in the user's T3 Code window.", "privacy": "commit-safe", "setup": {"role": "top", "mocks": {"t3_keybindings_read": {"keybindings": [{"key": "mod+j", "command": "terminal.toggle"}], "commands": ["terminal.toggle", "sidebar.toggle", "chat.new"], "issues": []}, "t3_app_command": {"ran": true}}}, "prompt": "Open the terminal in my T3 Code window.", "expect": {"calls": [{"tool": "t3_app_command", "args": {"command": "terminal.toggle"}}]}, "maxSteps": 6} +{"id": "open-settings-section-uses-app-navigate", "area": "settings", "kind": "bad", "pattern": "tell the user where to click", "experience": "Asked to show the keybindings settings in the user's T3 Code window, an agent had no way to move the window and described where to click.", "rule": "t3_app_navigate: Show a page in the user's T3 Code window, the one they used last: a thread from this environment, a settings section, usage, or pull requests.", "privacy": "commit-safe", "setup": {"role": "top", "mocks": {"t3_app_navigate": {"ran": true}}}, "prompt": "Take my T3 Code window to the keybindings settings.", "expect": {"calls": [{"tool": "t3_app_navigate", "args": {"to": {"page": "settings", "section": "keybindings"}}}]}, "maxSteps": 6} diff --git a/packages/client-runtime/src/t3ToolSummary.ts b/packages/client-runtime/src/t3ToolSummary.ts index f5daf28dbef1b..d2f9a279bc0e5 100644 --- a/packages/client-runtime/src/t3ToolSummary.ts +++ b/packages/client-runtime/src/t3ToolSummary.ts @@ -358,6 +358,9 @@ export function summarizeT3ToolCalls( case "app-command": label = phrase("Ran", "run", `app commands ${times}`); break; + case "app-navigate": + label = phrase("Opened", "open", `pages in the app ${times}`); + break; case "environment-links": label = phrase("Listed", "list", `linked environments ${times}`); break; diff --git a/packages/contracts/src/appControl.ts b/packages/contracts/src/appControl.ts index 0af347d37a40e..4430a5f36e9b8 100644 --- a/packages/contracts/src/appControl.ts +++ b/packages/contracts/src/appControl.ts @@ -1,6 +1,6 @@ import { Schema } from "effect"; -import { TrimmedNonEmptyString } from "./baseSchemas.ts"; +import { ThreadId, TrimmedNonEmptyString } from "./baseSchemas.ts"; import { STATIC_KEYBINDING_COMMANDS } from "./keybindings.ts"; /** @@ -55,9 +55,51 @@ const APP_COMMANDS = STATIC_KEYBINDING_COMMANDS.filter( export const AppCommand = Schema.Literals(APP_COMMANDS); export type AppCommand = typeof AppCommand.Type; +const APP_SETTINGS_SECTIONS = [ + "general", + "appearance", + "chat", + "diffs", + "keybindings", + "voice", + "snap-shot", + "providers", + "threads", + "projects", + "browser", + "devices", + "scheduled-tasks", + "source-control", + "worktrees", + "connections", + "access", + "secrets", + "maintenance", + "diagnostics", + "labs", + "about", + "archived", +] as const; +export const AppSettingsSection = Schema.Literals(APP_SETTINGS_SECTIONS); +export type AppSettingsSection = typeof AppSettingsSection.Type; + +/** A page of the user's window. A thread is always one from the agent's environment. */ +export const AppDestination = Schema.Union([ + Schema.Struct({ page: Schema.Literal("thread"), threadId: ThreadId }), + Schema.Struct({ page: Schema.Literal("settings"), section: Schema.optional(AppSettingsSection) }), + Schema.Struct({ page: Schema.Literals(["usage", "pull-requests"]) }), +]); +export type AppDestination = typeof AppDestination.Type; + +export const AppAction = Schema.Union([ + Schema.TaggedStruct("command", { command: AppCommand }), + Schema.TaggedStruct("navigate", { to: AppDestination }), +]); +export type AppAction = typeof AppAction.Type; + export const AppControlRequest = Schema.Struct({ requestId: TrimmedNonEmptyString, - command: AppCommand, + action: AppAction, }); export type AppControlRequest = typeof AppControlRequest.Type; @@ -69,7 +111,7 @@ export type AppControlSubscribeInput = typeof AppControlSubscribeInput.Type; export const AppControlResult = Schema.Literals([ "ran", - /** Nothing on screen handles the command right now. */ + /** Nothing on screen handles the command right now, or the window has no such page. */ "not-handled", /** The window isn't showing a thread or draft from the agent's environment. */ "other-environment", diff --git a/packages/contracts/src/keybindings.ts b/packages/contracts/src/keybindings.ts index 0e41fcfd4c294..434c7c7b9f954 100644 --- a/packages/contracts/src/keybindings.ts +++ b/packages/contracts/src/keybindings.ts @@ -45,6 +45,10 @@ const THREAD_KEYBINDING_COMMANDS = [ "thread.pin", "thread.regenerateTitle", "thread.undo", + "thread.restartSession", + "thread.showPullRequests", + "thread.linkPullRequest", + "thread.shareWithGuest", ...THREAD_JUMP_KEYBINDING_COMMANDS, ] as const; diff --git a/packages/shared/src/t3McpToolPresentation.ts b/packages/shared/src/t3McpToolPresentation.ts index d6e27fd1de9b2..b75e89d402bb8 100644 --- a/packages/shared/src/t3McpToolPresentation.ts +++ b/packages/shared/src/t3McpToolPresentation.ts @@ -56,6 +56,7 @@ export type T3McpToolSummaryAction = | "environment-unlink" | "environment-update" | "app-command" + | "app-navigate" | "attachment-prepare" | "attachment-discard" | "attachment-send" @@ -372,6 +373,7 @@ const T3_MCP_TOOLS: Readonly> = { "environment-update", ), t3_app_command: tool(["Run", "Running", "Ran", "an app command"], "app-command"), + t3_app_navigate: tool(["Open", "Opening", "Opened", "a page in the app"], "app-navigate"), t3_thread_launch: tool(["Launch", "Launching", "Launched", "a project thread"], "thread-create"), t3_project_list: tool(["List", "Listing", "Listed", "projects"], "project-list"), t3_project_read: tool(["Read", "Reading", "Read", "a project"], "project-read"), From f08f9fedad961a92c9079403caeae6d0d1d36850 Mon Sep 17 00:00:00 2001 From: Batch Processor <46352227+batchema@users.noreply.github.com> Date: Sat, 14 Nov 2026 14:25:00 -0500 Subject: [PATCH 10/20] feat: sanucode command runs the fork beside T3 Code (#9) Running the fork took a long command, Node had to come from nvm, and a new machine had no way to set it up. scripts/sanucode wraps it: - `sanucode` serves the web app, `sanucode app` opens the desktop app, both with their own data in ~/.sanucode - `sanucode import` replaces that data with a fresh copy of the installed T3 Code's threads and preferences, keeping a backup - `sanucode install` links `sanucode` and `sn` into ~/.local/bin It runs vp on the Node version pinned in package.json, so a system Node from nvm does not leak in. Co-authored-by: batchema --- AGENTS.md | 1 + scripts/sanucode | 79 ++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 80 insertions(+) create mode 100755 scripts/sanucode diff --git a/AGENTS.md b/AGENTS.md index 02c2cc5e03146..6ab65c99f8f13 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -218,3 +218,4 @@ This checkout is `batchema/t3code`, a personal fork. Its to-do list is the fork' - When asked to add a to-do, open an issue: `gh issue create --repo batchema/t3code`. Never file it upstream. - `gh issue list --repo batchema/t3code` shows open work. - A PR that finishes an issue says `Closes #N`; one that finishes part of it says `Part of #N`. +- The fork runs as Sanu Code beside an installed T3 Code, with its own data in `~/.sanucode`. `scripts/sanucode install` adds the `sanucode` and `sn` commands; `sn help` lists what they do. diff --git a/scripts/sanucode b/scripts/sanucode new file mode 100755 index 0000000000000..9077d6bd8944c --- /dev/null +++ b/scripts/sanucode @@ -0,0 +1,79 @@ +#!/bin/sh +# Sanu Code: runs this fork from source beside an installed T3 Code, with its own data in ~/.sanucode. +# sanucode serve the web app (extra flags pass through, e.g. --share --built) +# sanucode app open the desktop app (shares data with the web app; run one at a time) +# sanucode import replace Sanu Code's threads and preferences with a fresh copy of T3 Code's +# sanucode install link `sanucode` and `sn` in ~/.local/bin to this checkout +set -eu + +repo=$(cd "$(dirname "$(realpath "$0")")/.." && pwd) +home="$HOME/.sanucode" + +case "${1:-}" in + help | -h | --help) + sed -n '2,6s/^# //p' "$repo/scripts/sanucode" + exit 0 + ;; + install) + bin="$HOME/.local/bin" + mkdir -p "$bin" + ln -sfn "$repo/scripts/sanucode" "$bin/sanucode" + ln -sfn sanucode "$bin/sn" + echo "Linked sanucode and sn in $bin to $repo." + case ":$PATH:" in + *":$bin:"*) ;; + *) echo "Add $bin to your PATH to use them." ;; + esac + exit 0 + ;; +esac + +if ! command -v vp >/dev/null 2>&1; then + echo "sanucode: vp is not installed. See \"Install vp\" in $repo/README.md." >&2 + exit 1 +fi + +# An explicit version keeps the pinned Node even when vp defers to a system Node such as nvm's. +node_version=$(sed -n 's/^ *"node": "\([0-9.]*\)".*/\1/p' "$repo/package.json" | head -n 1) +cd "$repo" + +case "${1:-}" in + app) + shift + set -- dev:desktop --home-dir "$home" "$@" + ;; + import) + t3_data="$HOME/.t3/userdata" + data="$home/userdata" + backup="$home/backup" + prefs="settings.json keybindings.json keybindings-migrations client-settings.json" + + # SQLite removes the -wal file on a clean shutdown, so its presence means Sanu Code is open. + if [ -e "$data/statev2.sqlite-wal" ]; then + echo "sanucode: Sanu Code is running. Quit it, then import again." >&2 + exit 1 + fi + + mkdir -p "$data" "$backup" + for file in statev2.sqlite $prefs; do + if [ -f "$data/$file" ]; then cp "$data/$file" "$backup/"; fi + done + + vp env exec --node "$node_version" vp run migrate-dev-db \ + --base-dir "$home" --projects 1000 --threads-per-project 1000 + + for file in $prefs; do + if [ -f "$t3_data/$file" ]; then cp "$t3_data/$file" "$data/"; fi + done + + echo + echo "Imported T3 Code. Threads still running there were skipped." + echo "Previous Sanu Code data is in $backup." + exit 0 + ;; + *) + set -- dev --home-dir "$home" --host 0.0.0.0 --no-auto-bootstrap-project-from-cwd "$@" + ;; +esac + +exec vp env exec --node "$node_version" vp run "$@" From c41736b07990653383a1431a2bae20bde6c28aee Mon Sep 17 00:00:00 2001 From: Batch Processor <46352227+batchema@users.noreply.github.com> Date: Sat, 14 Nov 2026 14:43:14 -0500 Subject: [PATCH 11/20] docs: guide for moving to Sanu Code and connecting devices (#10) The sanucode command had no written path for switching over from an installed T3 Code or reconnecting a phone and other machines, which the import cannot carry over. docs/operations/sanu-code.md covers setup, the one-time import, pairing a phone from the desktop app, pairing machines with `t3 pair`, and day to day use. AGENTS.md points to it. Co-authored-by: batchema --- AGENTS.md | 2 +- docs/operations/sanu-code.md | 76 ++++++++++++++++++++++++++++++++++++ 2 files changed, 77 insertions(+), 1 deletion(-) create mode 100644 docs/operations/sanu-code.md diff --git a/AGENTS.md b/AGENTS.md index 6ab65c99f8f13..6480e7b4f45e5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -218,4 +218,4 @@ This checkout is `batchema/t3code`, a personal fork. Its to-do list is the fork' - When asked to add a to-do, open an issue: `gh issue create --repo batchema/t3code`. Never file it upstream. - `gh issue list --repo batchema/t3code` shows open work. - A PR that finishes an issue says `Closes #N`; one that finishes part of it says `Part of #N`. -- The fork runs as Sanu Code beside an installed T3 Code, with its own data in `~/.sanucode`. `scripts/sanucode install` adds the `sanucode` and `sn` commands; `sn help` lists what they do. +- The fork runs as Sanu Code beside an installed T3 Code, with its own data in `~/.sanucode`. `scripts/sanucode install` adds the `sanucode` and `sn` commands; `sn help` lists what they do. [Sanu Code](docs/operations/sanu-code.md) covers moving over from T3 Code and connecting devices. diff --git a/docs/operations/sanu-code.md b/docs/operations/sanu-code.md new file mode 100644 index 0000000000000..94789b4b91769 --- /dev/null +++ b/docs/operations/sanu-code.md @@ -0,0 +1,76 @@ +# Sanu Code + +Sanu Code is this fork run from source beside an installed T3 Code. It keeps its own data in +`~/.sanucode`, so the installed app, its database, and its connections stay untouched. + +## Set up + +Install `vp` ([Install vp](../../README.md#install-vp)), clone the fork, and run in the checkout: + +```sh +vp i +./scripts/sanucode install +``` + +This links `sanucode` and its alias `sn` in `~/.local/bin` to that checkout, so `git pull` also +updates the command. `sn help` lists every command. Sanu Code runs on the Node version pinned in +`package.json`, even when a Node version manager such as nvm selects another one. + +| Command | Opens | +| -------- | ---------------------------------------------------------------------------------------- | +| `sn app` | The desktop app | +| `sn` | The web app at `http://localhost:5733`. Open the `pairingUrl` it prints once per browser | + +Both use the same data and ports, so run one at a time. Sanu Code runs only while that command +does; keep its terminal open while you need it, including from your phone. + +## Move over from T3 Code + +`sn import` replaces Sanu Code's data with a copy of the installed T3 Code's projects, threads, +settings, keybindings, and display preferences. It saves the previous Sanu Code data in +`~/.sanucode/backup` and refuses to run while Sanu Code is open. + +1. Let running threads in T3 Code finish. +2. Quit and reopen T3 Code once. It closes inactive agent sessions on start, and the import skips + any thread whose session is still open. +3. Quit Sanu Code, then run `sn import`. It prints the threads each project received. Skipped + threads stay readable in T3 Code. + +Treat the import as a one-time move: running it again later replaces everything you did in Sanu +Code. It does not bring sign-ins, paired phones and machines, scheduled tasks, or secrets. +Reconnect devices as described below. + +## Connect your phone + +Sanu Code has no T3 Connect, because official builds carry the relay configuration and a build +from source does not. Phones and other machines reach it over your local network or Tailscale. + +1. Start `sn app`, open **Settings → Sharing & access**, and turn on **Network access**. The app + restarts. +2. Create a pairing link with an address your phone can reach, such as your computer's Tailscale + address. +3. In the mobile app, open **Settings → Environments → Add environment** and scan the QR code. + +Pair from `sn app`, which lists your computer's network addresses. The paired phone also reaches +`sn`, whose server listens on every interface at the same port. Plain HTTP works over Tailscale. +For HTTPS, enable HTTPS certificates for your tailnet, then use `sn --share --built`. + +## Connect other machines + +For each machine running T3 Code that you want to control from Sanu Code: + +1. Let it accept network connections: run `t3 up --lan` on a command-line host, or turn on + **Network access** in its desktop app. +2. Run `t3 pair` on that machine. +3. In Sanu Code, open **Settings → Environments → Add environment** and paste the link. If its + address is not reachable from your computer, replace the host with the machine's Tailscale + name or address and keep the port. + +This adds a new sign-in on that machine, and T3 Code's existing connection keeps working. Features +unique to this fork only work on machines that run Sanu Code. + +## Day to day + +- Update with `git pull` in the checkout, then restart Sanu Code. +- Keep T3 Code installed as a fallback, but never run agents in the same worktree from both apps. +- Once you stop using T3 Code, remove its environment from your phone and other clients. From 2c4158acedbd343f79f82cd4801b59cfdc9a5de2 Mon Sep 17 00:00:00 2001 From: Batch Processor <46352227+batchema@users.noreply.github.com> Date: Sat, 14 Nov 2026 21:21:03 +0100 Subject: [PATCH 12/20] fix(server): settings MCP tool no longer writes theme defaults Upstream's theme service validates themes and stamps when they were set, so clients may only change them through it. The settings tool decoded the full server patch and let agents store a theme that does not exist. It now uses the client patch and points at t3_theme_set. Co-Authored-By: Claude Opus 5.5 --- .../src/mcp/toolkits/environment/handlers.test.ts | 4 ++++ .../server/src/mcp/toolkits/environment/handlers.ts | 13 ++++++++++--- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/apps/server/src/mcp/toolkits/environment/handlers.test.ts b/apps/server/src/mcp/toolkits/environment/handlers.test.ts index f1b05b46c9efc..eb472ddcf6c38 100644 --- a/apps/server/src/mcp/toolkits/environment/handlers.test.ts +++ b/apps/server/src/mcp/toolkits/environment/handlers.test.ts @@ -161,6 +161,10 @@ it.effect("refuses settings and shortcuts agents may not or cannot write", () => "capability_denied", ], [call("t3_environment_settings_update", { patch: { notASetting: true } }), "invalid_request"], + [ + call("t3_environment_settings_update", { patch: { defaultTheme: "no-such-theme" } }), + "invalid_request", + ], [ call("t3_environment_settings_update", { patch: { linkedEnvironmentsEnabled: "yes" } }), "invalid_request", diff --git a/apps/server/src/mcp/toolkits/environment/handlers.ts b/apps/server/src/mcp/toolkits/environment/handlers.ts index af6a6bff52718..67b1054929d60 100644 --- a/apps/server/src/mcp/toolkits/environment/handlers.ts +++ b/apps/server/src/mcp/toolkits/environment/handlers.ts @@ -4,6 +4,7 @@ import { KeybindingRule, OrchestratorMcpFailure, ProjectId, + ClientServerSettingsPatch, ServerSettings, ServerSettingsPatch, STATIC_KEYBINDING_COMMANDS, @@ -47,11 +48,14 @@ export function preferences(settings: ServerSettings) { } const SETTINGS_KEYS = new Set(Object.keys(ServerSettings.fields)); -const PATCH_KEYS = new Set(Object.keys(ServerSettingsPatch.fields)); +const PATCH_KEYS = new Set(Object.keys(ClientServerSettingsPatch.fields)); +const THEME_KEYS = new Set( + Object.keys(ServerSettingsPatch.fields).filter((key) => !PATCH_KEYS.has(key)), +); const invalid = (message: string) => new OrchestratorMcpFailure({ code: "invalid_request", message }); -const decodePatch = Schema.decodeUnknownEffect(ServerSettingsPatch); +const decodePatch = Schema.decodeUnknownEffect(ClientServerSettingsPatch); const encodeSettings = Schema.encodeEffect(ServerSettings); const decodeKeybinding = Schema.decodeUnknownEffect(KeybindingRule); const decodeAppCommand = Schema.decodeUnknownEffect(AppCommand); @@ -187,7 +191,10 @@ export const layer = McpToolAccess.toLayer(EnvironmentToolkit, { if (keys.length === 0) return yield* invalid("`patch` is empty."); const unknown = keys.filter((key) => !PATCH_KEYS.has(key)); if (unknown.length > 0) - return yield* invalid(`Unknown or read-only settings: ${unknown.join(", ")}.`); + return yield* invalid( + `Unknown or read-only settings: ${unknown.join(", ")}.` + + (unknown.some((key) => THEME_KEYS.has(key)) ? " Use `t3_theme_set` for themes." : ""), + ); // Device hosts need the local-host filtering only the RPC path applies. if (keys.includes("deviceHosts")) return yield* new OrchestratorMcpFailure({ From 8f8852f6f6dd97d893ff531939c5b46f88b4ff6b Mon Sep 17 00:00:00 2001 From: Batch Processor <46352227+batchema@users.noreply.github.com> Date: Sat, 14 Nov 2026 22:14:47 +0100 Subject: [PATCH 13/20] feat: move a started thread to another project A started thread could not change projects. Move to project (thread menu, command palette, mobile row menu, and t3_thread_organize action `move`) now moves an idle thread into another project's root folder: - The thread keeps its id and history. A folder change ends its provider sessions, so the next turn resumes the conversation in the new folder, or seeds a fresh session from the thread when the provider can't resume. - Scheduled tasks bound to the thread move with it. - A confirm dialog, and the MCP result's `notice`, say what changes. - A moved thread gets a checkpoint scope per project, so earlier diffs keep reading the repository they were captured in. Threads that never move keep today's scope id. A diff whose folder is gone now says so. Part of #6 --- .../features/threads/moveThreadToProject.ts | 62 +++++++ .../features/threads/thread-list-v2-items.tsx | 32 +++- .../checkpointing/CheckpointDiffQuery.test.ts | 73 +++++++- .../src/checkpointing/CheckpointDiffQuery.ts | 32 +++- apps/server/src/checkpointing/Errors.ts | 34 +++- .../src/environment/ServerEnvironment.ts | 1 + apps/server/src/mcp/linkOrigin.test.ts | 8 +- apps/server/src/mcp/toolkits/core.test.ts | 4 + .../src/mcp/toolkits/thread/handlers.ts | 13 ++ apps/server/src/mcp/toolkits/thread/tools.ts | 7 +- .../src/observability/RpcInstrumentation.ts | 1 + .../CheckpointScopeOwnership.test.ts | 2 + .../src/orchestration-v2/CheckpointService.ts | 9 +- .../src/orchestration-v2/Orchestrator.ts | 57 ++++++- .../SelectionRestart.integration.test.ts | 158 ++++++++++++++++++ .../src/orchestration-v2/runtimeLayer.test.ts | 117 +++++++++++++ .../src/orchestration-v2/runtimeLayer.ts | 11 ++ apps/server/src/peer/PeerForwarding.test.ts | 9 +- apps/server/src/project/ThreadProjectMove.ts | 112 +++++++++++++ .../src/provider/AgentContextBudget.test.ts | 2 + .../src/provider/agentContextBudget.json | 2 +- apps/server/src/ws.test.ts | 8 + apps/server/src/ws.ts | 18 +- apps/web/src/components/CommandPalette.tsx | 53 ++++++ apps/web/src/components/Sidebar.tsx | 20 +++ .../src/components/threadActionMenu.logic.ts | 17 ++ apps/web/src/contextMenuFallback.ts | 10 ++ .../web/src/hooks/useThreadActionMenu.test.ts | 2 + apps/web/src/hooks/useThreadActionMenu.ts | 18 +- apps/web/src/hooks/useThreadActions.ts | 40 ++++- docs/user/thread-sidebar.md | 14 ++ evals/mcp-tool-use/cases/projects.ndjson | 1 + packages/client-runtime/src/state/models.ts | 16 ++ .../src/state/projectCommands.ts | 6 + .../contracts/src/clientRpcPermissions.ts | 1 + packages/contracts/src/environment.ts | 1 + packages/contracts/src/orchestrationV2.ts | 14 ++ packages/contracts/src/project.ts | 6 + packages/contracts/src/rpc.ts | 8 + packages/shared/package.json | 4 + packages/shared/src/threadMove.ts | 9 + 41 files changed, 989 insertions(+), 23 deletions(-) create mode 100644 apps/mobile/src/features/threads/moveThreadToProject.ts create mode 100644 apps/server/src/project/ThreadProjectMove.ts create mode 100644 packages/shared/src/threadMove.ts diff --git a/apps/mobile/src/features/threads/moveThreadToProject.ts b/apps/mobile/src/features/threads/moveThreadToProject.ts new file mode 100644 index 0000000000000..6f6c44e0fdd99 --- /dev/null +++ b/apps/mobile/src/features/threads/moveThreadToProject.ts @@ -0,0 +1,62 @@ +import { threadMoveTargets, type EnvironmentProject } from "@t3tools/client-runtime/state/models"; +import { + isAtomCommandInterrupted, + runAtomCommand, + squashAtomCommandFailure, +} from "@t3tools/client-runtime/state/runtime"; +import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell"; +import { AuthOrchestrationOperateScope } from "@t3tools/contracts"; +import { threadMoveNotice } from "@t3tools/shared/threadMove"; +import * as Haptics from "expo-haptics"; + +import * as Dialog from "../../components/ui/Dialog"; +import { appAtomRegistry } from "../../state/atom-registry"; +import { projectEnvironment } from "../../state/projects"; +import { environmentServerConfigsAtom } from "../../state/server"; +import { readEnvironmentScope } from "../../state/session"; + +/** Projects this thread can move into, on a server that can move it. */ +export function readThreadMoveTargets( + thread: EnvironmentThreadShell, + projects: ReadonlyArray, +): ReadonlyArray { + const config = appAtomRegistry.get(environmentServerConfigsAtom).get(thread.environmentId); + if (config?.environment.capabilities.threadMoveToProject !== true) return []; + return threadMoveTargets(projects, thread, config.scratchWorkspaceRoot); +} + +export function moveThreadToProject( + thread: EnvironmentThreadShell, + project: EnvironmentProject, +): void { + const failureTitle = "Could not move thread"; + if (!readEnvironmentScope(thread.environmentId, AuthOrchestrationOperateScope)) { + Dialog.alert(failureTitle, "This connection cannot change threads."); + return; + } + Dialog.confirm({ + title: `Move "${thread.title}" to ${project.title}?`, + message: threadMoveNotice({ + projectTitle: project.title, + fromWorktree: thread.worktreePath !== null, + }), + confirmText: "Move", + onConfirm: () => { + void Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light); + void runAtomCommand( + appAtomRegistry, + projectEnvironment.moveThread, + { + environmentId: thread.environmentId, + input: { threadId: thread.id, projectId: project.id }, + }, + { reportFailure: false }, + ).then((result) => { + if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { + const error = squashAtomCommandFailure(result); + Dialog.alert(failureTitle, error instanceof Error ? error.message : "Try again."); + } + }); + }, + }); +} diff --git a/apps/mobile/src/features/threads/thread-list-v2-items.tsx b/apps/mobile/src/features/threads/thread-list-v2-items.tsx index 69d0c84ecaa8d..5d1ecd4ed8b14 100644 --- a/apps/mobile/src/features/threads/thread-list-v2-items.tsx +++ b/apps/mobile/src/features/threads/thread-list-v2-items.tsx @@ -11,6 +11,7 @@ import { import { RowPressable } from "../../components/ui/RowPressable"; import { CustomSnoozeSheet } from "./CustomSnoozeSheet"; import { appAtomRegistry } from "../../state/atom-registry"; +import { useProjects } from "../../state/entities"; import { threadArrangementOpenAtom } from "../../state/thread-order"; import { threadEnvironment } from "../../state/threads"; import { useAtomCommand } from "../../state/use-atom-command"; @@ -72,6 +73,7 @@ import { useSwipeRowDormant } from "../home/swipe-row-activation"; import { ThreadSwipeable } from "../home/thread-swipe-actions"; import { buildThreadTitleRegenerationMenuItems } from "./thread-title-regeneration-menu"; import { canTurnThreadIntoProject, turnThreadIntoProject } from "./turnThreadIntoProject"; +import { moveThreadToProject, readThreadMoveTargets } from "./moveThreadToProject"; import { threadCanArchive } from "../home/threadArchive"; import { THREAD_LIST_V2_SETTLED_PAGE_COUNT, @@ -927,6 +929,8 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: { [props.autoSettleOptOutSupported, thread.autoSettleDisabledAt], ); const canTurnIntoProject = canTurnThreadIntoProject(thread); + const projects = useProjects(); + const moveTargets = useMemo(() => readThreadMoveTargets(thread, projects), [thread, projects]); const titleMenuItems = useMemo( () => [ { id: "rename", title: "Rename", image: "square.and.pencil" }, @@ -944,8 +948,28 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: { } satisfies MenuAction, ] : []), + ...(moveTargets.length > 0 + ? [ + { + id: "move-to-project", + title: "Move to project", + image: "folder", + attributes: { disabled: !threadCanArchive(thread.runtime) }, + subactions: moveTargets.map((project) => ({ + id: `move-to-project:${project.id}`, + title: project.title, + })), + } satisfies MenuAction, + ] + : []), + ], + [ + canTurnIntoProject, + moveTargets, + props.titleRegenerationSupported, + thread.runtime, + isRegeneratingTitle, ], - [canTurnIntoProject, props.titleRegenerationSupported, thread.runtime, isRegeneratingTitle], ); const menuActions = useMemo(() => { const nested = Platform.OS === "ios"; @@ -1048,6 +1072,11 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: { if (nativeEvent.event === "rename") handleRename(); if (nativeEvent.event === "regenerate-title") handleRegenerateTitle(); if (nativeEvent.event === "turn-into-project") void turnThreadIntoProject(thread); + if (nativeEvent.event.startsWith("move-to-project:")) { + const projectId = nativeEvent.event.slice("move-to-project:".length); + const project = moveTargets.find((candidate) => candidate.id === projectId); + if (project) moveThreadToProject(thread, project); + } if (nativeEvent.event === "copy-thread") { const target = threadChipCopyTarget( { environmentId: thread.environmentId, threadId: thread.id }, @@ -1099,6 +1128,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: { setCustomSnoozeOpen, snoozePresets, props.snoozePresets, + moveTargets, ], ); const primaryAction = useMemo(() => { diff --git a/apps/server/src/checkpointing/CheckpointDiffQuery.test.ts b/apps/server/src/checkpointing/CheckpointDiffQuery.test.ts index 7c516e97fa730..0dabc34472443 100644 --- a/apps/server/src/checkpointing/CheckpointDiffQuery.test.ts +++ b/apps/server/src/checkpointing/CheckpointDiffQuery.test.ts @@ -15,7 +15,12 @@ import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts"; import * as VcsProcess from "../vcs/VcsProcess.ts"; import * as CheckpointDiffQuery from "./CheckpointDiffQuery.ts"; import * as CheckpointStore from "./CheckpointStore.ts"; -import { CheckpointRefUnavailableError, CheckpointTurnRangeUnavailableError } from "./Errors.ts"; +import { + CheckpointFolderMissingError, + CheckpointRangeSpansFoldersError, + CheckpointRefUnavailableError, + CheckpointTurnRangeUnavailableError, +} from "./Errors.ts"; const threadId = ThreadId.make("thread:checkpoint-diff-v2"); const firstRunId = RunId.make("run:checkpoint-diff-v2:1"); @@ -51,6 +56,7 @@ function layerFor(input: { readonly projection: Effect.Effect; readonly diffCheckpoints?: CheckpointStore.CheckpointStore["Service"]["diffCheckpoints"]; readonly authoredPaths?: ReadonlySet; + readonly missingFolder?: string; }) { return CheckpointDiffQuery.layer.pipe( Layer.provide( @@ -58,6 +64,7 @@ function layerFor(input: { Layer.mock(ThreadManagement.ThreadManagementService)({ getCheckpointContext: () => input.projection, }), + FileSystem.layerNoop({ exists: (path) => Effect.succeed(path !== input.missingFolder) }), Layer.mock(CheckpointStore.CheckpointStore)({ diffCheckpoints: input.diffCheckpoints ?? (() => Effect.succeed("diff")), listAuthoredPaths: () => Effect.succeed(input.authoredPaths ?? null), @@ -190,6 +197,70 @@ it.effect.each([false, true])( }, ); +it.effect("diffs a moved thread's turns in their own folders and names a missing one", () => { + const checkpoint = ( + scopeId: CheckpointScopeId, + ordinalWithinScope: number, + runId: RunId | null, + appRunOrdinal: number | null, + ): ProjectionCheckpointContext["checkpoints"][number] => ({ + scopeId, + runId, + ordinalWithinScope, + appRunOrdinal, + status: "ready", + ref: CheckpointRef.make(`refs/t3/test/${scopeId}/${ordinalWithinScope}`), + }); + const projection: ProjectionCheckpointContext = { + runs: [ + { id: firstRunId, ordinal: 1, status: "completed" }, + { id: secondRunId, ordinal: 2, status: "completed" }, + ], + checkpointScopes: [ + { id: firstScopeId, runId: firstRunId, kind: "root_run", cwd: "/repo-before-move" }, + { id: secondScopeId, runId: secondRunId, kind: "root_run", cwd: "/repo-after-move" }, + ], + checkpoints: [ + checkpoint(firstScopeId, 0, null, null), + checkpoint(firstScopeId, 1, firstRunId, 1), + checkpoint(secondScopeId, 0, null, null), + checkpoint(secondScopeId, 1, secondRunId, 2), + ], + }; + const diffCheckpoints = vi.fn((_input: CheckpointStore.DiffCheckpointsInput) => + Effect.succeed("diff --git a/file b/file"), + ); + + return Effect.gen(function* () { + const query = yield* CheckpointDiffQuery.CheckpointDiffQuery; + yield* query.getTurnDiff({ threadId, fromTurnCount: 1, toTurnCount: 2 }); + assert.deepEqual( + diffCheckpoints.mock.calls.map(([input]) => [input.cwd, input.fromCheckpointRef]), + [["/repo-after-move", `refs/t3/test/${secondScopeId}/0`]], + ); + assert.instanceOf( + yield* query.getFullThreadDiff({ threadId, toTurnCount: 2 }).pipe(Effect.flip), + CheckpointRangeSpansFoldersError, + ); + const missing = yield* query + .getTurnDiff({ threadId, fromTurnCount: 0, toTurnCount: 1 }) + .pipe(Effect.flip); + assert.instanceOf(missing, CheckpointFolderMissingError); + assert.equal( + missing.message, + "The folder these changes were made in no longer exists: /repo-before-move", + ); + }).pipe( + Effect.provide( + layerFor({ + projection: Effect.succeed(projection), + diffCheckpoints, + missingFolder: "/repo-before-move", + }), + ), + ); +}); + const layerVcsProcess = VcsProcess.layer.pipe(Layer.provide(NodeServices.layer)); const layerStore = CheckpointStore.layer.pipe( Layer.provide(VcsDriverRegistry.layer.pipe(Layer.provide(layerVcsProcess))), diff --git a/apps/server/src/checkpointing/CheckpointDiffQuery.ts b/apps/server/src/checkpointing/CheckpointDiffQuery.ts index bf9543919de65..a447bd77f9f30 100644 --- a/apps/server/src/checkpointing/CheckpointDiffQuery.ts +++ b/apps/server/src/checkpointing/CheckpointDiffQuery.ts @@ -10,6 +10,7 @@ import { import * as Context from "effect/Context"; import * as Digest from "effect/crypto/Digest"; import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Schema from "effect/Schema"; @@ -18,6 +19,8 @@ import { checkpointRefForScopeOrdinal } from "../orchestration-v2/CheckpointServ import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.ts"; import { CheckpointDiffResultInvalidError, + CheckpointFolderMissingError, + CheckpointRangeSpansFoldersError, CheckpointRefUnavailableError, CheckpointThreadNotFoundError, CheckpointTurnRangeUnavailableError, @@ -85,6 +88,7 @@ export const make = Effect.gen(function* () { const threads = yield* ThreadManagement.ThreadManagementService; const checkpointStore = yield* CheckpointStore.CheckpointStore; const digest = yield* Digest.Digest; + const fileSystem = yield* FileSystem.FileSystem; const getTurnDiff: CheckpointDiffQuery["Service"]["getTurnDiff"] = Effect.fn("getTurnDiff")( function* (input) { @@ -179,6 +183,13 @@ export const make = Effect.gen(function* () { input.fromTurnCount === 0 ? projection.checkpointScopes.find((scope) => scope.kind === "root_run") : undefined; + const fromCheckpoint = + input.fromTurnCount === 0 + ? undefined + : (parentCheckpoint ?? + readyCheckpoints.find( + (checkpoint) => checkpoint.appRunOrdinal === input.fromTurnCount, + )); const fromCheckpointRef = input.fromTurnCount === 0 ? firstScope === undefined @@ -187,12 +198,21 @@ export const make = Effect.gen(function* () { scopeId: firstScope.id, ordinalWithinScope: 0, }).pipe(Effect.provideService(Digest.Digest, digest)) - : ( - parentCheckpoint ?? - readyCheckpoints.find( - (checkpoint) => checkpoint.appRunOrdinal === input.fromTurnCount, - ) - )?.ref; + : fromCheckpoint?.ref; + // A moved thread's earlier refs live in the repository it left. + const fromScope = + firstScope ?? + projection.checkpointScopes.find((scope) => scope.id === fromCheckpoint?.scopeId); + if (fromScope !== undefined && fromScope.cwd !== toScope.cwd) { + return yield* new CheckpointRangeSpansFoldersError({ operation, threadId: input.threadId }); + } + if (!(yield* fileSystem.exists(toScope.cwd).pipe(Effect.orElseSucceed(() => true)))) { + return yield* new CheckpointFolderMissingError({ + operation, + threadId: input.threadId, + cwd: toScope.cwd, + }); + } if (fromCheckpointRef === undefined) { return yield* new CheckpointRefUnavailableError({ operation, diff --git a/apps/server/src/checkpointing/Errors.ts b/apps/server/src/checkpointing/Errors.ts index b36fe817e9faa..829fb8376534f 100644 --- a/apps/server/src/checkpointing/Errors.ts +++ b/apps/server/src/checkpointing/Errors.ts @@ -79,6 +79,36 @@ export class CheckpointRefUnavailableError extends Schema.TaggedError()( + "CheckpointFolderMissingError", + { + operation: CheckpointDiffOperation, + threadId: ThreadId, + cwd: Schema.String, + }, +) { + override get message(): string { + return `The folder these changes were made in no longer exists: ${this.cwd}`; + } +} + +export class CheckpointRangeSpansFoldersError extends Schema.TaggedError()( + "CheckpointRangeSpansFoldersError", + { + operation: CheckpointDiffOperation, + threadId: ThreadId, + }, +) { + override get message(): string { + return "These turns ran in different folders after the thread moved, so their changes can't be shown together. Pick a single turn."; + } +} + +/** Diff failures caused by a thread's folder, whose messages are meant for the user. */ +export const isCheckpointFolderError = Schema.is( + Schema.Union([CheckpointFolderMissingError, CheckpointRangeSpansFoldersError]), +); + export type CheckpointServiceError = | CheckpointStoreError | ProjectionRepositoryError @@ -86,4 +116,6 @@ export type CheckpointServiceError = | CheckpointThreadNotFoundError | CheckpointWorkspacePathMissingError | CheckpointTurnRangeUnavailableError - | CheckpointRefUnavailableError; + | CheckpointRefUnavailableError + | CheckpointFolderMissingError + | CheckpointRangeSpansFoldersError; diff --git a/apps/server/src/environment/ServerEnvironment.ts b/apps/server/src/environment/ServerEnvironment.ts index 813efbe53ea30..bffbe574983d2 100644 --- a/apps/server/src/environment/ServerEnvironment.ts +++ b/apps/server/src/environment/ServerEnvironment.ts @@ -260,6 +260,7 @@ export const make = Effect.gen(function* () { threadActiveReorder: true, threadAutoSettleOptOut: true, threadProjectFromScratch: true, + threadMoveToProject: true, threadTitleRegeneration: true, commandOutputStreaming: true, threadVisitedTracking: true, diff --git a/apps/server/src/mcp/linkOrigin.test.ts b/apps/server/src/mcp/linkOrigin.test.ts index 928fda0dd72f8..10be29acc24d6 100644 --- a/apps/server/src/mcp/linkOrigin.test.ts +++ b/apps/server/src/mcp/linkOrigin.test.ts @@ -1,4 +1,5 @@ import * as DocumentText from "../provider/DocumentText.ts"; +import * as ThreadProjectMove from "../project/ThreadProjectMove.ts"; import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, it } from "@effect/vitest"; @@ -131,7 +132,12 @@ const layerTools = Layer.mergeAll( list: () => Effect.succeed([]), }), ), - Layer.provide(Layer.mock(ScheduledTaskService.ScheduledTaskService)({})), + Layer.provide( + Layer.merge( + Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), + Layer.mock(ThreadProjectMove.ThreadProjectMove)({}), + ), + ), Layer.provide( Layer.mock(ProjectService.ProjectService)({ getById: (id) => diff --git a/apps/server/src/mcp/toolkits/core.test.ts b/apps/server/src/mcp/toolkits/core.test.ts index 35a18f5f0b460..723b86df687ef 100644 --- a/apps/server/src/mcp/toolkits/core.test.ts +++ b/apps/server/src/mcp/toolkits/core.test.ts @@ -1,4 +1,5 @@ import * as AssetSigner from "../../assets/AssetSigner.ts"; +import * as ThreadProjectMove from "../../project/ThreadProjectMove.ts"; import * as DocumentText from "../../provider/DocumentText.ts"; import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; @@ -86,6 +87,7 @@ const decodeThreadSearchResult = Schema.decodeUnknownEffect( const layerThreadToolkit = McpHttpServer.layerThreadToolkit.pipe( Layer.provide(Layer.mock(ThreadSearch.ThreadSearch)({})), Layer.provide(Layer.mock(ScheduledTaskService.ScheduledTaskService)({})), + Layer.provide(Layer.mock(ThreadProjectMove.ThreadProjectMove)({})), Layer.provide(Layer.mock(PeerForwarding.PeerForwarding)({})), Layer.provide(Layer.mock(PeerLinkRequests.PeerLinkRequests)({})), Layer.provide(Layer.mock(PeerLinks.PeerLinks)({})), @@ -791,6 +793,7 @@ it.effect("search names the calling thread, so an agent can tell its own match a Effect.provide( McpHttpServer.layerThreadToolkit.pipe( Layer.provideMerge(McpHttpServer.layerInProcessMcpServer), + Layer.provide(Layer.mock(ThreadProjectMove.ThreadProjectMove)({})), Layer.provide(NodeCrypto.layer), Layer.provide(McpToolAccessTestkit.liveThreadsLayer), Layer.provide( @@ -1031,6 +1034,7 @@ it.effect.each([ Effect.provide( McpHttpServer.layerThreadToolkit.pipe( Layer.provideMerge(McpHttpServer.layerInProcessMcpServer), + Layer.provide(Layer.mock(ThreadProjectMove.ThreadProjectMove)({})), Layer.provide(NodeCrypto.layer), Layer.provide(Layer.mock(ThreadManagement.ThreadManagementService)({})), Layer.provide(Layer.mock(ThreadSearch.ThreadSearch)({})), diff --git a/apps/server/src/mcp/toolkits/thread/handlers.ts b/apps/server/src/mcp/toolkits/thread/handlers.ts index 88bb91bf62b77..9bd96183f0854 100644 --- a/apps/server/src/mcp/toolkits/thread/handlers.ts +++ b/apps/server/src/mcp/toolkits/thread/handlers.ts @@ -20,6 +20,7 @@ import { unavailable, } from "../../threadAccess.ts"; import * as ThreadSearch from "../../../orchestration-v2/ThreadSearch.ts"; +import * as ThreadProjectMove from "../../../project/ThreadProjectMove.ts"; import * as ScheduledTasks from "../../../scheduledTasks/ScheduledTaskService.ts"; import { queuedRunsInDeliveryOrder } from "../../../orchestration-v2/QueuedRunOrder.ts"; import { ThreadToolkit } from "./tools.ts"; @@ -346,6 +347,18 @@ export const layer = McpToolAccess.toLayer(ThreadToolkit, { Effect.gen(function* () { const { threads, projection, caller } = yield* readThread(input.threadId); const common = { commandId: yield* newCommandId(), threadId: projection.thread.id }; + if (input.action === "move") { + const projectId = yield* required(input.projectId, "projectId"); + const { notice } = yield* (yield* ThreadProjectMove.ThreadProjectMove) + .move({ threadId: projection.thread.id, projectId }) + .pipe( + Effect.mapError( + (error) => + new OrchestratorMcpFailure({ code: "orchestration_error", message: error.message }), + ), + ); + return { movedToProjectId: projectId, notice }; + } if (input.action === "settle") { return yield* threads .settleThread({ ...common, byOwnAgent: caller?.id === projection.thread.id }) diff --git a/apps/server/src/mcp/toolkits/thread/tools.ts b/apps/server/src/mcp/toolkits/thread/tools.ts index 4c59ea4f2028f..9c90a894a8fff 100644 --- a/apps/server/src/mcp/toolkits/thread/tools.ts +++ b/apps/server/src/mcp/toolkits/thread/tools.ts @@ -25,13 +25,14 @@ import * as Schema from "effect/Schema"; import { Tool, Toolkit } from "effect/ai"; import * as ThreadSearch from "../../../orchestration-v2/ThreadSearch.ts"; +import * as ThreadProjectMove from "../../../project/ThreadProjectMove.ts"; import * as ScheduledTaskService from "../../../scheduledTasks/ScheduledTaskService.ts"; import * as ThreadManagementService from "../../../orchestration-v2/ThreadManagementService.ts"; import * as McpInvocationContext from "../../McpInvocationContext.ts"; const ThreadOrganizeTool = Tool.make("t3_thread_organize", { description: - "Pin, snooze, settle, archive, or mark a thread unread. Omit `threadId` for this thread. `snooze` needs `snoozedUntil`. Settling this thread applies at turn end. A failed turn or queued message leaves it active.", + "Pin, snooze, settle, archive, mark unread, or move a thread to another project. Omit `threadId` for this thread. `snooze` needs `snoozedUntil`. Settling this thread applies at turn end. A failed turn or queued message leaves it active. `move` needs `projectId` and an idle thread (not this one mid-turn); its history continues in that project's root. From a worktree, its changes stay behind and earlier turns can't be restored; `notice` says what changed.", parameters: Schema.Struct({ environmentId: OrchestratorMcpEnvironmentTarget, threadId: Schema.optional(ThreadId), @@ -45,18 +46,22 @@ const ThreadOrganizeTool = Tool.make("t3_thread_organize", { "archive", "unarchive", "mark_unread", + "move", ]), snoozedUntil: Schema.optional(IsoDateTime), + projectId: Schema.optional(ProjectId), }), success: Schema.Union([ OrchestrationV2DispatchCommandResult, Schema.Struct({ settlesWhenTurnEnds: Schema.Literal(true) }), + Schema.Struct({ movedToProjectId: ProjectId, notice: Schema.String }), ]), failure: OrchestratorMcpFailure, failureMode: "return" as const, dependencies: [ McpInvocationContext.McpInvocationContext, ThreadManagementService.ThreadManagementService, + ThreadProjectMove.ThreadProjectMove, SecureRandom.SecureRandom, ], }) diff --git a/apps/server/src/observability/RpcInstrumentation.ts b/apps/server/src/observability/RpcInstrumentation.ts index f31165e6dafc1..ace9673ac182c 100644 --- a/apps/server/src/observability/RpcInstrumentation.ts +++ b/apps/server/src/observability/RpcInstrumentation.ts @@ -165,6 +165,7 @@ const RPC_AGGREGATES = { [WS_METHODS.projectsEnsureScratch]: "orchestration", [WS_METHODS.projectsCreateNew]: "orchestration", [WS_METHODS.projectsCreateFromThread]: "orchestration", + [WS_METHODS.projectsMoveThread]: "orchestration", [WS_METHODS.shellOpenInEditor]: "workspace", [WS_METHODS.filesystemBrowse]: "workspace", [WS_METHODS.filesystemGetMetadata]: "workspace", diff --git a/apps/server/src/orchestration-v2/CheckpointScopeOwnership.test.ts b/apps/server/src/orchestration-v2/CheckpointScopeOwnership.test.ts index 33a7490a0245a..4cc6b01bd56f1 100644 --- a/apps/server/src/orchestration-v2/CheckpointScopeOwnership.test.ts +++ b/apps/server/src/orchestration-v2/CheckpointScopeOwnership.test.ts @@ -2,6 +2,7 @@ import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import { assert, it } from "@effect/vitest"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import { CheckpointId, @@ -218,6 +219,7 @@ it.effect("resolves the thread baseline after a second root run replaces scope o Layer.mock(ThreadManagement.ThreadManagementService)({ getCheckpointContext: () => Effect.succeed(context), }), + FileSystem.layerNoop({ exists: () => Effect.succeed(true) }), Layer.mock(CheckpointStore.CheckpointStore)({ listAuthoredPaths: () => Effect.succeed(null), diffCheckpoints: (input) => { diff --git a/apps/server/src/orchestration-v2/CheckpointService.ts b/apps/server/src/orchestration-v2/CheckpointService.ts index 3e0fbe95e8aa4..359c6158fbbeb 100644 --- a/apps/server/src/orchestration-v2/CheckpointService.ts +++ b/apps/server/src/orchestration-v2/CheckpointService.ts @@ -5,6 +5,7 @@ import { NodeId, OrchestrationV2Checkpoint, OrchestrationV2CheckpointScope, + type ProjectId, ProviderThreadId, RunId, ThreadId, @@ -108,6 +109,7 @@ const isCheckpointRestoreError = Schema.is(CheckpointRestoreError); export interface CheckpointServiceV2Shape { readonly prepareRootRunScope: (input: { readonly threadId: ThreadId; + readonly scopeProjectId: ProjectId | undefined; readonly runId: RunId; readonly rootNodeId: NodeId; readonly providerThreadId: ProviderThreadId; @@ -180,6 +182,7 @@ function checkpointIdForScopeOrdinal( const makeRootRunScope = Effect.fn("CheckpointService.makeRootRunScope")(function* (input: { readonly idAllocator: IdAllocator.IdAllocatorV2["Service"]; readonly threadId: ThreadId; + readonly scopeProjectId: ProjectId | undefined; readonly runId: RunId; readonly rootNodeId: NodeId; readonly providerThreadId: ProviderThreadId; @@ -188,7 +191,11 @@ const makeRootRunScope = Effect.fn("CheckpointService.makeRootRunScope")(functio }) { const scopeId = yield* input.idAllocator.allocate.checkpointScope({ threadId: input.threadId, - name: ROOT_CHECKPOINT_SCOPE_NAME, + // A moved thread's refs live in another repository, so each project gets its own scope. + name: + input.scopeProjectId === undefined + ? ROOT_CHECKPOINT_SCOPE_NAME + : `${ROOT_CHECKPOINT_SCOPE_NAME}:${input.scopeProjectId}`, }); return { id: scopeId, diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 226b7d703d0b1..24b9b9ac2a4d8 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -650,6 +650,7 @@ function commandThreadId(command: OrchestrationV2ServerCommand): ThreadId { case "thread.pull-request.sync": case "thread.title.regeneration.complete": case "thread.project.adopt-folder": + case "thread.project.move": case "thread.runtime-mode.set": case "thread.interaction-mode.set": case "thread.model-selection.set": @@ -2858,6 +2859,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio Effect.flatMap((resolvedRuntimePolicy) => checkpointService.prepareRootRunScope({ threadId, + scopeProjectId: projection.thread.checkpointScopeProjectId, runId: queuedRun.id, rootNodeId: rootNode.id, providerThreadId: queuedProviderThread.id, @@ -4083,6 +4085,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio | "thread.pull-request-watch.checks-reopen" | "thread.pull-request.sync" | "thread.title.regeneration.complete" + | "thread.project.move" | "thread.runtime-mode.set" | "thread.interaction-mode.set" | "thread.model-selection.set" @@ -4392,6 +4395,31 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio } } + let projectMoveChangesCwd = false; + if (command.type === "thread.project.move") { + const reject = (cause: string) => + new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: `Thread ${command.threadId} ${cause}`, + }); + if (thread.projectId === command.projectId) return yield* reject("is already there."); + const records = yield* projectionStore + .getThreadRecords(command.threadId, ["runs", "runtimeRequests"], { turnItemTypes: [] }) + .pipe(mapDispatchError(command)); + if (threadHasUnfinishedWork(records)) { + return yield* reject("still has work in progress. Finish or stop it first."); + } + const current = yield* projects.get(thread.projectId).pipe(mapDispatchError(command)); + const target = yield* projects.get(command.projectId).pipe(mapDispatchError(command)); + if (Option.isNone(target) || target.value.deletedAt !== null) { + return yield* reject(`cannot move to missing project ${command.projectId}.`); + } + projectMoveChangesCwd = + (thread.worktreePath ?? Option.getOrUndefined(current)?.workspaceRoot) !== + target.value.workspaceRoot; + } + const needsProviderState = command.type === "thread.runtime-mode.set" || command.type === "thread.model-selection.set" || @@ -4400,7 +4428,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio command.type === "thread.settle" || (command.type === "thread.metadata.update" && command.worktreePath !== undefined && - command.worktreePath !== thread.worktreePath); + command.worktreePath !== thread.worktreePath) || + projectMoveChangesCwd; const providerContext = needsProviderState ? yield* projectionStore .getThreadProviderContext( @@ -4450,9 +4479,10 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const detachSessionIds = new Set( command.type === "thread.archive" || command.type === "thread.settle" ? (providerContext?.providerSessions ?? []).map((session) => session.id) - : command.type === "thread.metadata.update" && - command.worktreePath !== undefined && - command.worktreePath !== thread.worktreePath + : (command.type === "thread.metadata.update" && + command.worktreePath !== undefined && + command.worktreePath !== thread.worktreePath) || + projectMoveChangesCwd ? (providerContext?.providerSessions ?? []).map((session) => session.id) : command.type === "thread.runtime-mode.set" ? (providerContext?.providerSessions ?? []) @@ -4853,6 +4883,15 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio updatedAt: now, }; } + case "thread.project.move": + return { + ...thread, + projectId: command.projectId, + worktreePath: null, + branch: projectMoveChangesCwd ? command.branch : thread.branch, + ...(projectMoveChangesCwd ? { checkpointScopeProjectId: command.projectId } : {}), + updatedAt: now, + }; case "thread.pull-request.link": case "thread.pull-request.unlink": case "thread.pull-request-link.sync": { @@ -5189,6 +5228,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio return "thread.marked-unread" as const; case "thread.metadata.update": case "thread.title.regeneration.complete": + case "thread.project.move": return "thread.metadata-updated" as const; case "thread.pull-request.link": case "thread.pull-request.unlink": @@ -5389,7 +5429,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ? "Thread archived." : command.type === "thread.settle" ? "Thread settled." - : command.type === "thread.metadata.update" + : command.type === "thread.metadata.update" || + command.type === "thread.project.move" ? "Workspace changed." : command.type === "thread.runtime-mode.set" ? "Runtime mode changed." @@ -6448,6 +6489,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const checkpointScope = yield* checkpointService .prepareRootRunScope({ threadId: input.command.threadId, + scopeProjectId: input.projection.thread.checkpointScopeProjectId, runId: targetRun.id, rootNodeId: nextRootNodeId, providerThreadId: restartProviderThread.id, @@ -7506,6 +7548,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio Effect.flatMap((resolvedRuntimePolicy) => checkpointService.prepareRootRunScope({ threadId: command.threadId, + scopeProjectId: projection.thread.checkpointScopeProjectId, runId, rootNodeId, providerThreadId: queuedProviderThread.id, @@ -7988,6 +8031,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio Effect.flatMap((resolvedRuntimePolicy) => checkpointService.prepareRootRunScope({ threadId: command.threadId, + scopeProjectId: projection.thread.checkpointScopeProjectId, runId, rootNodeId, providerThreadId, @@ -8773,6 +8817,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const checkpointScope = yield* checkpointService .prepareRootRunScope({ threadId: command.threadId, + scopeProjectId: projection.thread.checkpointScopeProjectId, runId, rootNodeId, providerThreadId: providerThread.id, @@ -11838,6 +11883,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const checkpointScope = yield* checkpointService .prepareRootRunScope({ threadId: command.threadId, + scopeProjectId: projection.thread.checkpointScopeProjectId, runId: state.run.id, rootNodeId: state.rootNode.id, providerThreadId: state.providerThread.id, @@ -15001,6 +15047,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio case "thread.pull-request.watch": case "thread.pull-request.sync": case "thread.title.regeneration.complete": + case "thread.project.move": case "thread.runtime-mode.set": case "thread.interaction-mode.set": case "thread.model-selection.set": diff --git a/apps/server/src/orchestration-v2/SelectionRestart.integration.test.ts b/apps/server/src/orchestration-v2/SelectionRestart.integration.test.ts index 7b12f72f4cead..2fa6adc35dd2d 100644 --- a/apps/server/src/orchestration-v2/SelectionRestart.integration.test.ts +++ b/apps/server/src/orchestration-v2/SelectionRestart.integration.test.ts @@ -29,7 +29,9 @@ import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts"; import * as EffectWorker from "./EffectWorker.ts"; import * as EventSink from "./EventSink.ts"; import * as Orchestrator from "./Orchestrator.ts"; +import * as ProjectStore from "./ProjectStore.ts"; import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts"; +import * as SqlitePersistence from "../persistence/Sqlite.ts"; import * as ProviderReplayHarness from "./testkit/ProviderReplayHarness.ts"; import { checkpointWorkspace } from "@t3tools/provider-testing/replayWorkspace"; import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; @@ -592,6 +594,162 @@ it.live.each(["pooled", "exclusive"] as const)( }), ); +it.live("moving a thread to another project resumes its conversation in the new root", () => + Effect.gen(function* () { + const name = "project-move"; + const sourceRoot = yield* checkpointWorkspace(`${name}-source`); + const targetRoot = yield* checkpointWorkspace(`${name}-target`); + const threadId = ThreadId.make(`thread:${name}`); + const sourceId = ProjectId.make(`project:${name}:source`); + const targetId = ProjectId.make(`project:${name}:target`); + const state = yield* Ref.make({ + activeTurn: null, + opened: [], + started: [], + closedSessionCount: 0, + failedReplacementOpen: true, + }); + const database = SqlitePersistence.layerMemory; + + const result = yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const eventSink = yield* EventSink.EventSinkV2; + const projects = yield* ProjectStore.ProjectStoreV2; + for (const [index, [projectId, workspaceRoot]] of ( + [ + [sourceId, sourceRoot], + [targetId, targetRoot], + ] as const + ).entries()) { + yield* projects.apply({ + sequence: index + 1, + eventId: EventId.make(`event:${projectId}`), + aggregateKind: "project", + aggregateId: projectId, + occurredAt: "2026-01-01T00:00:00.000Z", + commandId: null, + causationEventId: null, + correlationId: null, + metadata: {}, + type: "project.created", + payload: { + projectId, + title: projectId, + workspaceRoot, + defaultModelSelection: null, + scripts: [], + createdAt: "2026-01-01T00:00:00.000Z", + updatedAt: "2026-01-01T00:00:00.000Z", + }, + }); + } + const send = (step: string) => + Effect.gen(function* () { + const terminal = yield* orchestrator.streamDomainEvents.pipe( + Stream.filter( + (event) => event.type === "run.updated" && event.payload.status === "completed", + ), + Stream.take(1), + Stream.runDrain, + Effect.forkScoped, + ); + yield* orchestrator.dispatch({ + type: "message.dispatch", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make(`${name}:${step}`), + threadId, + messageId: MessageId.make(`${name}:${step}`), + text: step, + attachments: [], + modelSelection: seedSelection, + dispatchMode: { type: "start_immediately" }, + }); + yield* worker.drain(); + yield* Fiber.join(terminal); + yield* worker.drain(); + return yield* orchestrator.getThreadProjection(threadId); + }); + yield* orchestrator.dispatch({ + type: "thread.create", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make(`${name}:create`), + threadId, + projectId: sourceId, + title: name, + modelSelection: seedSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: "source-branch", + worktreePath: null, + }); + const first = yield* send("first"); + const move = (projectId: ProjectId, branch: string | null) => + orchestrator.dispatch({ + type: "thread.project.move", + commandId: CommandId.make(`${name}:move:${projectId}`), + threadId, + projectId, + branch, + }); + const moved = yield* move(targetId, "target-branch"); + yield* worker.drain(); + const second = yield* send("second"); + yield* move(sourceId, "source-branch"); + yield* worker.drain(); + const third = yield* send("third"); + const detached = yield* eventSink + .readByCommandId({ commandId: CommandId.make(`${name}:move:${targetId}`) }) + .pipe(Stream.runCollect); + return { first, moved, second, third, detached: [...detached] }; + }).pipe( + Effect.provide( + Layer.merge( + ProviderReplayHarness.layerWithRegistry( + { name }, + ProviderAdapterRegistry.layerSingle(makeRestartAdapter(state, exclusiveCapabilities)), + { databaseLayer: database }, + ), + ProjectStore.layer.pipe(Layer.provide(database)), + ), + ), + ); + + const firstSession = result.first.providerSessions.find( + (session) => session.status !== "stopped" && session.status !== "error", + ); + assert.isDefined(firstSession); + assert.deepEqual( + result.detached.flatMap(({ event }) => + event.type === "provider-session.detached" ? [event.payload.providerSessionId] : [], + ), + [firstSession.id], + ); + assert.equal(result.second.thread.projectId, targetId); + assert.isNull(result.second.thread.worktreePath); + assert.equal(result.second.thread.branch, "target-branch"); + assert.equal(result.third.thread.projectId, sourceId); + // Each move ends the live session, so every turn opens one in its new root. + assert.lengthOf((yield* Ref.get(state)).opened, 3); + // Each move starts a checkpoint scope of its own, so earlier refs stay in their repository. + assert.lengthOf( + new Set( + result.third.checkpointScopes + .filter((scope) => scope.kind === "root_run") + .map((scope) => scope.id), + ), + 3, + ); + // The provider conversation carries over; only its session moved. + assert.deepEqual( + [...new Set(result.third.providerThreads.map((thread) => thread.nativeThreadRef?.nativeId))], + [`native-thread:${threadId}`], + ); + }), +); + it.live("Stop during a restart interrupts the turn the restart could not stop", () => Effect.gen(function* () { const cwd = yield* checkpointWorkspace("selection-restart-stop"); diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index 08397c580519d..4e812ae195267 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -87,6 +87,7 @@ import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts"; import * as ThreadManagementService from "./ThreadManagementService.ts"; import * as ManagedProjectFolders from "../project/ManagedProjectFolders.ts"; import * as ScratchThreadPromotion from "../project/ScratchThreadPromotion.ts"; +import * as ThreadProjectMove from "../project/ThreadProjectMove.ts"; import * as ScheduledTaskService from "../scheduledTasks/ScheduledTaskService.ts"; import * as ManagedPolicy from "../policy/ManagedPolicy.ts"; import * as Scheduler from "../scheduling/Scheduler.ts"; @@ -10191,6 +10192,122 @@ it.layer(layerScratchPromotionTest)("turning a No project thread into a project" ); }); +const layerThreadProjectMoveTest = ThreadProjectMove.layer.pipe( + Layer.provide( + Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({ + isScratchProject: (projectId) => Effect.succeed(projectId === SCRATCH_PROJECT_ID), + namedProjectsRoot: "/projects", + }), + ), + Layer.provide( + Layer.mock(GitWorkflow.GitWorkflowService)({ + currentBranch: (cwd) => Effect.succeed(`branch-of:${cwd}`), + }), + ), + Layer.provide(NodeCrypto.layer), + Layer.provideMerge(layerProjectDeletionTest), +); + +it.layer(layerThreadProjectMoveTest)("moving a thread to another project", (it) => { + it.effect( + "moves an idle thread and its bound tasks, and refuses No project or busy threads", + () => + Effect.gen(function* () { + const move = (yield* ThreadProjectMove.ThreadProjectMove).move; + const projects = yield* ProjectService.ProjectService; + const orchestrator = yield* Orchestrator.OrchestratorV2; + const tasks = yield* ScheduledTaskService.ScheduledTaskService; + const sourceId = ProjectId.make("thread-move-source"); + const targetId = ProjectId.make("thread-move-target"); + for (const [projectId, workspaceRoot] of [ + [sourceId, "/tmp/thread-move-source"], + [targetId, "/tmp/thread-move-target"], + [SCRATCH_PROJECT_ID, SCRATCH_ROOT], + ] as const) { + if (Option.isNone(yield* projects.getById(projectId))) { + yield* projects.create({ + commandId: CommandId.make(`${projectId}-create`), + projectId, + title: projectId, + workspaceRoot, + }); + } + } + const createThread = (name: string) => + orchestrator + .dispatch({ + type: "thread.create", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make(`thread-move-${name}-create`), + threadId: ThreadId.make(`thread-move-${name}`), + projectId: sourceId, + title: name, + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: "source-branch", + worktreePath: "/tmp/thread-move-source-worktree", + }) + .pipe(Effect.as(ThreadId.make(`thread-move-${name}`))); + const threadId = yield* createThread("idle"); + const busyId = yield* createThread("busy"); + yield* orchestrator.dispatch({ + type: "message.dispatch", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make("thread-move-busy-message"), + threadId: busyId, + messageId: MessageId.make("thread-move-busy-message"), + text: "Keep this run active.", + attachments: [], + modelSelection, + dispatchMode: { type: "start_immediately" }, + }); + const { task } = yield* tasks.upsert({ + id: ScheduledTaskId.make("thread-move-bound"), + title: "Bound", + prompt: "Check in", + enabled: true, + schedule: { type: "interval", everyMs: 60_000 }, + projectId: sourceId, + threadId, + workspaceStrategy: { type: "root" }, + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + createdBy: "user", + creationSource: "web", + }); + const shellOf = (id: ThreadId) => orchestrator.getThreadShell(id); + + const scratch = yield* move({ threadId, projectId: SCRATCH_PROJECT_ID }).pipe(Effect.flip); + assert.equal(scratch.message, "A thread cannot move into No project."); + const busy = yield* move({ threadId: busyId, projectId: targetId }).pipe(Effect.flip); + assert.equal( + busy.message, + `Thread ${busyId} still has work in progress. Finish or stop it first.`, + ); + assert.equal((yield* shellOf(busyId))?.projectId, sourceId); + + const fromWorktree = yield* move({ threadId, projectId: targetId }); + assert.include(fromWorktree.notice, "not this thread's worktree"); + const moved = yield* shellOf(threadId); + assert.equal(moved?.projectId, targetId); + // It lands in the project root; the old worktree stays where it was. + assert.isNull(moved?.worktreePath); + assert.equal(moved?.branch, "branch-of:/tmp/thread-move-target"); + const saved = (yield* tasks.list()).tasks.find((candidate) => candidate.id === task.id); + assert.equal(saved?.projectId, targetId); + + yield* move({ threadId, projectId: targetId }); + const fromRoot = yield* move({ threadId, projectId: sourceId }); + assert.notInclude(fromRoot.notice, "worktree"); + assert.equal((yield* shellOf(threadId))?.projectId, sourceId); + }), + ); +}); + it.layer(layerSharedApplicationDataPlaneTest)("snooze projection", (it) => { it.effect("carries snooze, settle and title state through the V2 shell projection", () => Effect.gen(function* () { diff --git a/apps/server/src/orchestration-v2/runtimeLayer.ts b/apps/server/src/orchestration-v2/runtimeLayer.ts index 4f834535cc2d2..261ba9d79a0fa 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.ts @@ -19,6 +19,7 @@ import * as ProjectService from "../project/ProjectService.ts"; import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts"; import * as ManagedProjectFolders from "../project/ManagedProjectFolders.ts"; import * as ScratchThreadPromotion from "../project/ScratchThreadPromotion.ts"; +import * as ThreadProjectMove from "../project/ThreadProjectMove.ts"; import * as CheckpointCaptureService from "./CheckpointCaptureService.ts"; import * as CheckpointService from "./CheckpointService.ts"; import * as CheckpointRollbackService from "./CheckpointRollbackService.ts"; @@ -314,6 +315,15 @@ const layerScratchThreadPromotionProvided = ScratchThreadPromotion.layer.pipe( ).pipe(Layer.provideMerge(layerProjectService)), ), ); +const layerThreadProjectMoveProvided = ThreadProjectMove.layer.pipe( + Layer.provide( + Layer.mergeAll( + layerManagedProjectFoldersProvided, + layerThreadManagementProvided, + layerScheduledTaskProvided, + ).pipe(Layer.provideMerge(layerProjectService)), + ), +); const layerProviderContinuationWorkerProvided = ProviderContinuationService.layer.pipe( Layer.provide( Layer.mergeAll( @@ -395,6 +405,7 @@ export const layerProduction = Layer.mergeAll( layerThreadLaunchProvided, layerScheduledTaskProvided, layerScratchThreadPromotionProvided, + layerThreadProjectMoveProvided, layerSecretRequestsProvided, GuestShareService.layer.pipe( Layer.provide(Layer.merge(layerOrchestratorProvided, layerCommandOutputHubProvided)), diff --git a/apps/server/src/peer/PeerForwarding.test.ts b/apps/server/src/peer/PeerForwarding.test.ts index 84fe35c6f21f8..a9e37c7eaefb4 100644 --- a/apps/server/src/peer/PeerForwarding.test.ts +++ b/apps/server/src/peer/PeerForwarding.test.ts @@ -1,4 +1,5 @@ import * as DocumentText from "../provider/DocumentText.ts"; +import * as ThreadProjectMove from "../project/ThreadProjectMove.ts"; import { NodeHttpServer } from "@effect/platform-node"; import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; @@ -245,7 +246,12 @@ const serveBox = (seen: Ref.Ref, linkSession: Ref.Ref) => Layer.mock(ProviderRegistry.ProviderRegistry)({ getProviders: Effect.succeed([]) }), ), Layer.provide(Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({})), - Layer.provide(Layer.mock(ScheduledTaskService.ScheduledTaskService)({})), + Layer.provide( + Layer.merge( + Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), + Layer.mock(ThreadProjectMove.ThreadProjectMove)({}), + ), + ), Layer.provide(Layer.mock(ProjectCloneTracker.ProjectCloneTracker)({})), Layer.provide(Layer.mock(SecretRequests.SecretRequests)({})), Layer.provide(ServerSettings.layerTest()), @@ -326,6 +332,7 @@ const makeLaptop = Effect.gen(function* () { Layer.mock(ProviderRegistry.ProviderRegistry)({}), Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({}), Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), + Layer.mock(ThreadProjectMove.ThreadProjectMove)({}), Layer.mock(ProjectService.ProjectService)({}), Layer.mock(ProjectCloneTracker.ProjectCloneTracker)({}), Layer.mock(SecretRequests.SecretRequests)({}), diff --git a/apps/server/src/project/ThreadProjectMove.ts b/apps/server/src/project/ThreadProjectMove.ts new file mode 100644 index 0000000000000..fc8cf2c2db936 --- /dev/null +++ b/apps/server/src/project/ThreadProjectMove.ts @@ -0,0 +1,112 @@ +import { CommandId, type ProjectId, type ThreadId } from "@t3tools/contracts"; +import { threadMoveNotice } from "@t3tools/shared/threadMove"; +import * as Context from "effect/Context"; +import * as SecureRandom from "effect/crypto/SecureRandom"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; + +import * as GitWorkflowService from "../git/GitWorkflowService.ts"; +import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts"; +import { userFacingDispatchErrorMessage } from "../orchestration-v2/UserFacingErrors.ts"; +import * as ScheduledTaskService from "../scheduledTasks/ScheduledTaskService.ts"; +import * as ManagedProjectFolders from "./ManagedProjectFolders.ts"; +import * as ProjectService from "./ProjectService.ts"; + +export class ThreadProjectMoveError extends Schema.TaggedError()( + "ThreadProjectMoveError", + { + reason: Schema.String, + cause: Schema.optional(Schema.Defect()), + }, +) { + override get message(): string { + return this.reason; + } +} + +export class ThreadProjectMove extends Context.Service< + ThreadProjectMove, + { + /** + * Moves an idle thread, with its scheduled tasks, into another project's root folder. + * Running it again finishes a partial move. + */ + readonly move: (input: { + readonly threadId: ThreadId; + readonly projectId: ProjectId; + }) => Effect.Effect<{ readonly notice: string }, ThreadProjectMoveError>; + } +>()("t3/project/ThreadProjectMove") {} + +const make = Effect.gen(function* () { + const managedFolders = yield* ManagedProjectFolders.ManagedProjectFolders; + const projects = yield* ProjectService.ProjectService; + const threads = yield* ThreadManagementService.ThreadManagementService; + const scheduledTasks = yield* ScheduledTaskService.ScheduledTaskService; + const git = yield* GitWorkflowService.GitWorkflowService; + const randomId = (yield* SecureRandom.SecureRandom).uuidV4(); + + const fail = (reason: string) => (cause: unknown) => + new ThreadProjectMoveError({ reason, cause }); + + const move: ThreadProjectMove["Service"]["move"] = Effect.fn("ThreadProjectMove.move")( + function* (input) { + const target = yield* projects + .getById(input.projectId) + .pipe(Effect.mapError(fail("Could not read the project."))); + if (Option.isNone(target) || target.value.deletedAt !== null) { + return yield* new ThreadProjectMoveError({ reason: "Project not found." }); + } + // No project holds one folder per thread, so its root is no place to work. + if (yield* managedFolders.isScratchProject(input.projectId)) { + return yield* new ThreadProjectMoveError({ + reason: "A thread cannot move into No project.", + }); + } + const thread = yield* threads.getThreadShell(input.threadId).pipe( + Effect.mapError(fail("Could not read the thread.")), + Effect.filterOrFail( + (shell) => shell !== null, + () => new ThreadProjectMoveError({ reason: "Thread not found." }), + ), + ); + if (thread.projectId !== input.projectId) { + const branch = yield* git + .currentBranch(target.value.workspaceRoot) + .pipe(Effect.orElseSucceed(() => null)); + yield* threads + .dispatch({ + type: "thread.project.move", + commandId: CommandId.make(`thread-project-move:${yield* randomId}`), + threadId: input.threadId, + projectId: input.projectId, + branch, + }) + .pipe( + Effect.mapError( + (cause) => + new ThreadProjectMoveError({ + reason: userFacingDispatchErrorMessage(cause) ?? "Could not move the thread.", + cause, + }), + ), + ); + } + yield* scheduledTasks + .moveThreadTasks({ threadIds: [input.threadId], projectId: input.projectId }) + .pipe(Effect.mapError(fail("Moved the thread, but not its scheduled tasks. Try again."))); + return { + notice: threadMoveNotice({ + projectTitle: target.value.title, + fromWorktree: thread.worktreePath !== null, + }), + }; + }, + ); + + return ThreadProjectMove.of({ move }); +}); + +export const layer = Layer.effect(ThreadProjectMove, make); diff --git a/apps/server/src/provider/AgentContextBudget.test.ts b/apps/server/src/provider/AgentContextBudget.test.ts index c5925b844979a..203d1c231fd28 100644 --- a/apps/server/src/provider/AgentContextBudget.test.ts +++ b/apps/server/src/provider/AgentContextBudget.test.ts @@ -39,6 +39,7 @@ import { ProjectSetupScriptRunner } from "../project/ProjectSetupScriptRunner.ts import { PullRequestReviewGuideService } from "../pullRequest/PullRequestReviewGuideService.ts"; import { PullRequestService } from "../pullRequest/PullRequestService.ts"; import { ScheduledTaskService } from "../scheduledTasks/ScheduledTaskService.ts"; +import { ThreadProjectMove } from "../project/ThreadProjectMove.ts"; import { SecretRequests } from "../secrets/SecretRequests.ts"; import { ServerSettingsService } from "../serverSettings.ts"; import { SourceControlRepositoryService } from "../sourceControl/SourceControlRepositoryService.ts"; @@ -78,6 +79,7 @@ const toolHandlerServices = Layer.mergeAll( Layer.mock(PullRequestService)({}), Layer.mock(RemoteDelegation)({}), Layer.mock(ScheduledTaskService)({}), + Layer.mock(ThreadProjectMove)({}), Layer.mock(SecretRequests)({}), ServerConfig.layerTest(process.cwd(), { prefix: "t3-agent-context-budget-" }), Layer.mock(ServerEnvironment)({}), diff --git a/apps/server/src/provider/agentContextBudget.json b/apps/server/src/provider/agentContextBudget.json index 75de9863056ec..771b2d07ae179 100644 --- a/apps/server/src/provider/agentContextBudget.json +++ b/apps/server/src/provider/agentContextBudget.json @@ -1,5 +1,5 @@ { "claudeSystemAppendBytes": 5930, "codexAdditionalContextBytes": 7324, - "mcpToolListJsonBytes": 52659 + "mcpToolListJsonBytes": 52942 } diff --git a/apps/server/src/ws.test.ts b/apps/server/src/ws.test.ts index 4152b22cb7d01..01a7258402a3c 100644 --- a/apps/server/src/ws.test.ts +++ b/apps/server/src/ws.test.ts @@ -79,6 +79,7 @@ import * as GitWorkflowService from "./git/GitWorkflowService.ts"; import * as HostResources from "./resourceTelemetry/HostResources.ts"; import * as ManagedProjectFolders from "./project/ManagedProjectFolders.ts"; import * as ScratchThreadPromotion from "./project/ScratchThreadPromotion.ts"; +import * as ThreadProjectMove from "./project/ThreadProjectMove.ts"; import * as McpAppRequests from "./mcpApps/McpAppRequests.ts"; import * as ModelManifest from "./provider/ModelManifest.ts"; import * as Orchestrator from "./orchestration-v2/Orchestrator.ts"; @@ -978,6 +979,7 @@ it.effect.each([ namedProjectsRoot: process.cwd(), }), Layer.mock(ScratchThreadPromotion.ScratchThreadPromotion)({}), + Layer.mock(ThreadProjectMove.ThreadProjectMove)({}), Layer.mock(ServerEnvironment.ServerEnvironment)({ getDescriptor: Effect.succeed({ environmentId: EnvironmentId.make("config-test"), @@ -1202,6 +1204,7 @@ it.effect("access changes made while the snapshot loads reach the client after i namedProjectsRoot: "/unused", }), Layer.mock(ScratchThreadPromotion.ScratchThreadPromotion)({}), + Layer.mock(ThreadProjectMove.ThreadProjectMove)({}), Layer.mock(ServerEnvironment.ServerEnvironment)({}), Layer.mock(EnvironmentAuth.EnvironmentAuth)({ listPairingLinks: () => Effect.succeed([]), @@ -1359,6 +1362,7 @@ it.effect("on-demand clients get provider config without workspace snapshots", ( namedProjectsRoot: process.cwd(), }), Layer.mock(ScratchThreadPromotion.ScratchThreadPromotion)({}), + Layer.mock(ThreadProjectMove.ThreadProjectMove)({}), Layer.mock(ServerEnvironment.ServerEnvironment)({ getDescriptor: Effect.succeed({ environmentId: EnvironmentId.make("config-test"), @@ -1738,6 +1742,7 @@ it.effect("a missing thread worktree gets its project's skills in the cwd snapsh namedProjectsRoot: process.cwd(), }), Layer.mock(ScratchThreadPromotion.ScratchThreadPromotion)({}), + Layer.mock(ThreadProjectMove.ThreadProjectMove)({}), Layer.mock(ServerEnvironment.ServerEnvironment)({}), Layer.mock(EnvironmentAuth.EnvironmentAuth)({}), ); @@ -1824,6 +1829,7 @@ it.effect("a git action that fails partway still refreshes the repository status Layer.mock(DirectEndpoints.DirectEndpoints)({}), Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({ namedProjectsRoot: "/unused" }), Layer.mock(ScratchThreadPromotion.ScratchThreadPromotion)({}), + Layer.mock(ThreadProjectMove.ThreadProjectMove)({}), Layer.mock(ServerEnvironment.ServerEnvironment)({}), Layer.mock(EnvironmentAuth.EnvironmentAuth)({}), ); @@ -1904,6 +1910,7 @@ it.effect("a publish whose push fails still refreshes the new remote", () => Layer.mock(DirectEndpoints.DirectEndpoints)({}), Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({ namedProjectsRoot: "/unused" }), Layer.mock(ScratchThreadPromotion.ScratchThreadPromotion)({}), + Layer.mock(ThreadProjectMove.ThreadProjectMove)({}), Layer.mock(ServerEnvironment.ServerEnvironment)({}), Layer.mock(EnvironmentAuth.EnvironmentAuth)({}), ); @@ -2364,6 +2371,7 @@ it.effect("ACP session RPCs list a thread missing its history and repair it on i Layer.mock(DirectEndpoints.DirectEndpoints)({}), Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({ namedProjectsRoot: "/unused" }), Layer.mock(ScratchThreadPromotion.ScratchThreadPromotion)({}), + Layer.mock(ThreadProjectMove.ThreadProjectMove)({}), Layer.mock(ServerEnvironment.ServerEnvironment)({}), Layer.mock(EnvironmentAuth.EnvironmentAuth)({}), Layer.mock(ProjectService.ProjectService)({ diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 7d9267e93c2f5..400f52f6cb45e 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -222,6 +222,8 @@ import * as ProjectService from "./project/ProjectService.ts"; import { threadWorkspaceRoot } from "./project/threadWorkspaceRoot.ts"; import * as ManagedProjectFolders from "./project/ManagedProjectFolders.ts"; import * as ScratchThreadPromotion from "./project/ScratchThreadPromotion.ts"; +import * as ThreadProjectMove from "./project/ThreadProjectMove.ts"; +import { isCheckpointFolderError } from "./checkpointing/Errors.ts"; import { mutateProjectWithClone } from "./project/ProjectMutation.ts"; import * as ProjectCloneTracker from "./project/ProjectCloneTracker.ts"; import * as RepositoryIdentityResolver from "./project/RepositoryIdentityResolver.ts"; @@ -1442,6 +1444,7 @@ export const layerWsRpc = ( const projectService = yield* ProjectService.ProjectService; const managedFolders = yield* ManagedProjectFolders.ManagedProjectFolders; const scratchThreadPromotion = yield* ScratchThreadPromotion.ScratchThreadPromotion; + const threadProjectMove = yield* ThreadProjectMove.ThreadProjectMove; const eventLoopMonitor = yield* EventLoopMonitor.EventLoopMonitor; const threadSearch = yield* ThreadSearch.ThreadSearch; @@ -2026,7 +2029,9 @@ export const layerWsRpc = ( Effect.mapError( (cause) => new OrchestrationGetTurnDiffError({ - message: "Failed to load turn diff", + message: isCheckpointFolderError(cause) + ? cause.message + : "Failed to load turn diff", cause, }), ), @@ -2036,7 +2041,9 @@ export const layerWsRpc = ( Effect.mapError( (cause) => new OrchestrationGetFullThreadDiffError({ - message: "Failed to load full thread diff", + message: isCheckpointFolderError(cause) + ? cause.message + : "Failed to load full thread diff", cause, }), ), @@ -2900,6 +2907,13 @@ export const layerWsRpc = ( (cause) => new OrchestrationDispatchCommandError({ message: cause.message, cause }), ), ), + [WS_METHODS.projectsMoveThread]: (input) => + threadProjectMove.move(input).pipe( + Effect.asVoid, + Effect.mapError( + (cause) => new OrchestrationDispatchCommandError({ message: cause.message, cause }), + ), + ), [WS_METHODS.projectCloneCancel]: (input) => projectCloneTracker.cancel(input.projectId).pipe(Effect.map((applied) => ({ applied }))), [WS_METHODS.projectCloneRetry]: (input) => diff --git a/apps/web/src/components/CommandPalette.tsx b/apps/web/src/components/CommandPalette.tsx index 0ec1ddfd9bb8f..e0a48722ab389 100644 --- a/apps/web/src/components/CommandPalette.tsx +++ b/apps/web/src/components/CommandPalette.tsx @@ -66,6 +66,7 @@ import { FileSearchIcon, FolderGit2Icon, FolderIcon, + FolderInputIcon, FolderPlusIcon, KeyboardIcon, MessageSquareDashedIcon, @@ -126,6 +127,7 @@ import { readEnvironmentScope, useEnvironmentScope } from "~/state/session"; import { sourceControlEnvironment } from "../state/sourceControl"; import { useAtomCommand } from "../state/use-atom-command"; import { useRestartAgentSession } from "../hooks/useRestartAgentSession"; +import { confirmThreadMove } from "../hooks/useThreadActions"; import { useOrchestrationCommand } from "../state/use-orchestration-command"; import { useAtomQueryRunner } from "../state/use-atom-query-runner"; import { useScratchProject } from "../hooks/useScratchProject"; @@ -149,6 +151,7 @@ import { waitForProject, } from "../state/entities"; import { visibleLinkedThreads } from "@t3tools/client-runtime/state/threads"; +import { threadMoveTargets, threadRuntimeCanArchive } from "@t3tools/client-runtime/state/models"; import { resolveThreadActionProjectRef, startNewThreadFromContext, @@ -485,6 +488,7 @@ function OpenCommandPaletteDialog(props: { reportFailure: false, }); const restartAgentSession = useRestartAgentSession(); + const moveThread = useAtomCommand(projectEnvironment.moveThread, { reportFailure: false }); const { environments } = useEnvironments(); const desktopLocalBootstraps = useDesktopLocalBootstraps(); const primaryEnvironmentId = usePrimaryEnvironmentId(); @@ -1500,6 +1504,55 @@ function OpenCommandPaletteDialog(props: { }); } + const moveTargets = + activeThread !== null && + activeThreadServerConfig?.environment.capabilities.threadMoveToProject === true + ? threadMoveTargets(projects, activeThread, activeThreadServerConfig.scratchWorkspaceRoot) + : []; + if (activeThread !== null && moveTargets.length > 0) { + const threadRef = scopeThreadRef(activeThread.environmentId, activeThread.id); + actionItems.push({ + kind: "submenu", + value: "action:move-thread-to-project", + searchTerms: ["move", "project", "folder", "relocate", "wrong project"], + title: "Move thread to...", + icon: , + addonIcon: , + disabled: !threadRuntimeCanArchive(activeThread.runtime), + groups: [ + { + value: "move-thread-to-project", + label: "Projects", + items: moveTargets.map((project) => ({ + kind: "action" as const, + value: `move-thread-to:${project.environmentId}:${project.id}`, + searchTerms: [project.title, project.workspaceRoot], + title: project.title, + description: project.workspaceRoot, + icon: , + run: async () => { + if (!(await confirmThreadMove(threadRef, project.id))) return; + const result = await moveThread({ + environmentId: threadRef.environmentId, + input: { threadId: threadRef.threadId, projectId: project.id }, + }); + if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { + const error = squashAtomCommandFailure(result); + toastManager.add( + stackedThreadToast({ + type: "error", + title: "Could not move thread", + description: error instanceof Error ? error.message : "An error occurred.", + }), + ); + } + }, + })), + }, + ], + }); + } + if (activeThread !== null) { const thread = activeThread; actionItems.push({ diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 7409f4c83b295..5886aa1b7f750 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -120,6 +120,8 @@ import { } from "../threadSelectionStore"; import { canTurnThreadIntoProject, + confirmThreadMove, + readThreadMoveTargets, useAcknowledgeThreadWoke, useThreadActions, } from "../hooks/useThreadActions"; @@ -930,6 +932,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve confirmAndUnpinThread, setThreadAutoSettle, turnThreadIntoProject, + moveThreadToProject, reorderPinnedThread, reorderActiveThread, markThreadUnread, @@ -2652,6 +2655,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve canShareWithGuestAtom(threadRef.environmentId), ), canTurnIntoProject: canTurnThreadIntoProject(threadRef), + moveTargets: readThreadMoveTargets(threadRef), supports: { settlement: configLoaded, autoSettleOptOut: supportsAutoSettleOptOut, @@ -2679,6 +2683,22 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve if (preset) attemptSnooze(threadRef, preset); return; } + if (clicked.value.startsWith("move-to-project:")) { + const projectId = ProjectId.make(clicked.value.slice("move-to-project:".length)); + if (!(await confirmThreadMove(threadRef, projectId))) return; + const result = await moveThreadToProject(threadRef, projectId); + if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { + const error = squashAtomCommandFailure(result); + toastManager.add( + stackedThreadToast({ + type: "error", + title: "Could not move thread", + description: error instanceof Error ? error.message : "An error occurred.", + }), + ); + } + return; + } switch (clicked.value) { case "filter-by-project": if (threadProjectGroup) { diff --git a/apps/web/src/components/threadActionMenu.logic.ts b/apps/web/src/components/threadActionMenu.logic.ts index 1e3eddd0b9389..e9f6ba012e554 100644 --- a/apps/web/src/components/threadActionMenu.logic.ts +++ b/apps/web/src/components/threadActionMenu.logic.ts @@ -6,6 +6,8 @@ export type ThreadActionMenuId = | "new-thread-on-branch" | "filter-by-project" | "turn-into-project" + | "move-to-project" + | `move-to-project:${string}` | "project-settings" | "pin" | "unpin" @@ -95,6 +97,7 @@ export interface ThreadActionMenuState { readonly canShareWithGuest?: boolean; /** A No project thread with its own folder, on a server that can promote it. */ readonly canTurnIntoProject?: boolean; + readonly moveTargets?: ReadonlyArray<{ readonly id: string; readonly title: string }>; } /** Local navigation, read markers, and copying remain available to read-only clients. */ @@ -203,6 +206,20 @@ export function buildThreadActionMenuItems( }, ] : []), + ...(state.moveTargets && state.moveTargets.length > 0 + ? [ + { + id: "move-to-project" as const, + label: "Move to project", + icon: "folder-input", + disabled: state.isRunning, + children: state.moveTargets.map((project) => ({ + id: `move-to-project:${project.id}` as const, + label: project.title, + })), + }, + ] + : []), ...(state.supports.autoSettleOptOut ? [ { diff --git a/apps/web/src/contextMenuFallback.ts b/apps/web/src/contextMenuFallback.ts index 22c0c575b4c84..01e32c753387e 100644 --- a/apps/web/src/contextMenuFallback.ts +++ b/apps/web/src/contextMenuFallback.ts @@ -124,6 +124,16 @@ const ICON_PATHS: Record ({ })); vi.mock("./useThreadActions", () => ({ canTurnThreadIntoProject: () => false, + confirmThreadMove: async () => false, + readThreadMoveTargets: () => [], useThreadActions: () => Object.fromEntries( [ diff --git a/apps/web/src/hooks/useThreadActionMenu.ts b/apps/web/src/hooks/useThreadActionMenu.ts index f96baf908b3d9..124445ec05fb1 100644 --- a/apps/web/src/hooks/useThreadActionMenu.ts +++ b/apps/web/src/hooks/useThreadActionMenu.ts @@ -10,6 +10,7 @@ import { import { canSnooze, effectiveSnoozed } from "@t3tools/client-runtime/state/thread-settled"; import { AuthOrchestrationOperateScope, + ProjectId, type ScopedThreadRef, type ThreadId, } from "@t3tools/contracts"; @@ -47,7 +48,12 @@ import { threadRuntimeCanArchive } from "@t3tools/client-runtime/state/models"; import { useCopyToClipboard } from "./useCopyToClipboard"; import { useNewThreadHandler } from "./useHandleNewThread"; import { useClientSettings } from "./useSettings"; -import { canTurnThreadIntoProject, useThreadActions } from "./useThreadActions"; +import { + canTurnThreadIntoProject, + confirmThreadMove, + readThreadMoveTargets, + useThreadActions, +} from "./useThreadActions"; function failureToast(title: string, error: unknown) { toastManager.add( @@ -88,6 +94,7 @@ export function useThreadActionMenu(input: { deleteThread, markThreadUnread, turnThreadIntoProject, + moveThreadToProject, } = useThreadActions(); const regenerateThreadTitle = useOrchestrationCommand(threadEnvironment.regenerateTitle, { reportFailure: false, @@ -144,6 +151,7 @@ export function useThreadActionMenu(input: { snoozePresets, canShareWithGuest, canTurnIntoProject: canTurnThreadIntoProject(threadRef), + moveTargets: readThreadMoveTargets(threadRef), }); const clicked = await settlePromise(() => api.contextMenu.show(items, position)); if (clicked._tag === "Failure" || clicked.value === null) return; @@ -184,6 +192,14 @@ export function useThreadActionMenu(input: { failureToast(title, squashAtomCommandFailure(result)); } }; + if (action.startsWith("move-to-project:")) { + const projectId = ProjectId.make(action.slice("move-to-project:".length)); + if (!(await confirmThreadMove(threadRef, projectId))) return; + await reportFailure("Could not move thread", () => + moveThreadToProject(threadRef, projectId), + ); + return; + } switch (action) { case "find": onFind?.(threadRef); diff --git a/apps/web/src/hooks/useThreadActions.ts b/apps/web/src/hooks/useThreadActions.ts index 6a8ce92af5e38..0324e9c15344b 100644 --- a/apps/web/src/hooks/useThreadActions.ts +++ b/apps/web/src/hooks/useThreadActions.ts @@ -6,17 +6,19 @@ import { } from "@t3tools/client-runtime/environment"; import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; import { canSnooze, threadWokeAt } from "@t3tools/client-runtime/state/thread-settled"; -import { threadRuntimeCanArchive } from "@t3tools/client-runtime/state/models"; +import { threadMoveTargets, threadRuntimeCanArchive } from "@t3tools/client-runtime/state/models"; import { AuthOrchestrationOperateScope, AuthSourceControlWriteScope, EnvironmentAuthorizationError, EnvironmentId, + type ProjectId, type ScopedThreadRef, ThreadId, sessionGrantsScope, } from "@t3tools/contracts"; import { resolveWorktreeCleanup } from "@t3tools/shared/projectSettings"; +import { threadMoveNotice } from "@t3tools/shared/threadMove"; import * as Cause from "effect/Cause"; import * as Schema from "effect/Schema"; import { AsyncResult } from "effect/reactivity"; @@ -42,6 +44,7 @@ import { readEnvironmentSupportsAutoSettleOptOut, readEnvironmentThreadRefs, readProject, + readProjects, readThreadShell, readThreadShells, } from "../state/entities"; @@ -261,6 +264,35 @@ export function canTurnThreadIntoProject(threadRef: ScopedThreadRef): boolean { return project !== null && isScratchProject(project, config.scratchWorkspaceRoot); } +/** Projects this thread can move into, on a server that can move it. */ +export function readThreadMoveTargets(threadRef: ScopedThreadRef) { + const thread = readThreadShell(threadRef); + const config = appAtomRegistry.get(environmentServerConfigsAtom).get(threadRef.environmentId); + if (!thread || config?.environment.capabilities.threadMoveToProject !== true) return []; + return threadMoveTargets(readProjects(), thread, config.scratchWorkspaceRoot); +} + +/** Says what the move changes for this thread before it happens. */ +export async function confirmThreadMove( + threadRef: ScopedThreadRef, + projectId: ProjectId, +): Promise { + const thread = readThreadShell(threadRef); + const project = readProject({ environmentId: threadRef.environmentId, projectId }); + const api = readLocalApi(); + if (!thread || !project || !api) return false; + const notice = threadMoveNotice({ + projectTitle: project.title, + fromWorktree: thread.worktreePath !== null, + }); + const confirmed = await settlePromise(() => + api.dialogs.confirm(`Move "${thread.title}" to ${project.title}?\n${notice}`, { + initialFocus: "confirm", + }), + ); + return confirmed._tag === "Success" && confirmed.value; +} + function threadOperationFailure(target: ScopedThreadRef) { return readEnvironmentScope(target.environmentId, AuthOrchestrationOperateScope) ? null @@ -315,6 +347,7 @@ export function useThreadActions() { const createProjectFromThread = useAtomCommand(projectEnvironment.createFromThread, { reportFailure: false, }); + const moveThread = useAtomCommand(projectEnvironment.moveThread, { reportFailure: false }); const stopThreadSession = useOrchestrationCommand(threadEnvironment.stopSession); const removeWorktree = useAtomCommand(vcsEnvironment.removeWorktree, { reportFailure: false, @@ -1032,5 +1065,10 @@ export function useThreadActions() { environmentId: target.environmentId, input: { threadId: target.threadId }, }), + moveThreadToProject: (target: ScopedThreadRef, projectId: ProjectId) => + moveThread({ + environmentId: target.environmentId, + input: { threadId: target.threadId, projectId }, + }), }; } diff --git a/docs/user/thread-sidebar.md b/docs/user/thread-sidebar.md index 89fb443049a5f..c655e19a847ed 100644 --- a/docs/user/thread-sidebar.md +++ b/docs/user/thread-sidebar.md @@ -46,6 +46,20 @@ moves and the agent keeps working in the same place. Other threads in that folde move with it. Rename the project in its settings, and use **Initialize Git** to get branch and diff controls. +### Move a thread to another project + +Started in the wrong place? Pick **Move to project** from the thread's menu, or +**Move thread to...** in the command palette, and choose a project on the same +machine. The thread keeps its history and continues in that project's root folder +from your next message. Stop a running thread before moving it. + +Earlier turns keep their diffs for as long as the folder they ran in exists. A +thread that had its own worktree leaves it behind: the worktree and branch stay on +disk, but the agent no longer sees changes left there, and earlier turns can't be +restored. The old worktree shows as unused in +[Storage cleanup](./project-settings.md#storage-cleanup). To keep working in a fresh +worktree, hand the moved thread off to one. + ### Start in the background In a desktop browser or the desktop app, press `Cmd+Enter` on macOS or `Ctrl+Enter` diff --git a/evals/mcp-tool-use/cases/projects.ndjson b/evals/mcp-tool-use/cases/projects.ndjson index b52ee4eff30bc..409f4f4cdd082 100644 --- a/evals/mcp-tool-use/cases/projects.ndjson +++ b/evals/mcp-tool-use/cases/projects.ndjson @@ -1 +1,2 @@ {"id": "archive-project-not-delete", "area": "projects", "kind": "guard", "pattern": "archive a project by deleting it", "experience": "Projects gained an archive flag. Asked to archive a finished project, an agent must set archived, not remove the project and its threads.", "rule": "t3_project_update archived: Threads and files are kept.", "privacy": "commit-safe", "setup": {"role": "top", "mocks": {"t3_project_list": {"projects": [{"id": "project-app", "title": "app", "workspaceRoot": "/home/dev/code/app", "defaultModelSelection": null, "scripts": [], "pinnedAt": null, "archivedAt": null, "createdAt": "2026-09-01T00:00:00.000Z", "updatedAt": "2026-10-20T00:00:00.000Z", "deletedAt": null}, {"id": "project-old-site", "title": "old-site", "workspaceRoot": "/home/dev/code/old-site", "defaultModelSelection": null, "scripts": [], "pinnedAt": null, "archivedAt": null, "createdAt": "2026-03-01T00:00:00.000Z", "updatedAt": "2026-04-02T00:00:00.000Z", "deletedAt": null}], "nextCursor": null}}}, "prompt": "I'm done with the old-site project. Archive it in T3 Code so it stops showing up in my project pickers.", "expect": {"calls": [{"tool": "t3_project_update", "args": {"projectId": "project-old-site", "archived": true}}], "callsMustNot": [{"tool": "t3_project_delete"}, {"tool": "t3_project_update", "args": {"projectId": "project-app"}}]}, "maxSteps": 6} +{"id": "move-thread-to-another-project", "area": "projects", "kind": "bad", "pattern": "move a thread by copying it", "experience": "Asked to move a started thread into the right project, an agent had no move action, so it could only fork the thread or start a new one, which leaves the conversation behind (batchema/t3code#6).", "rule": "t3_thread_organize move: the thread keeps its history and continues in the target project's root.", "privacy": "commit-safe", "setup": {"role": "top", "mocks": {"t3_project_list": {"projects": [{"id": "project-web", "title": "web", "workspaceRoot": "/home/user/code/web", "defaultModelSelection": null, "scripts": [], "pinnedAt": null, "archivedAt": null, "createdAt": "2026-09-01T00:00:00.000Z", "updatedAt": "2026-10-20T00:00:00.000Z", "deletedAt": null}, {"id": "project-api", "title": "api", "workspaceRoot": "/home/user/code/api", "defaultModelSelection": null, "scripts": [], "pinnedAt": null, "archivedAt": null, "createdAt": "2026-09-01T00:00:00.000Z", "updatedAt": "2026-10-20T00:00:00.000Z", "deletedAt": null}], "nextCursor": null}, "t3_thread_organize": {"movedToProjectId": "project-api", "notice": "The conversation moves with it, and the agent works in api's folder from the next message. Earlier diffs open while their original folder exists."}}}, "prompt": "I started thread thread-auth-retry in the web project by mistake; the bug is in api. Move that thread over to the api project so it keeps going there.", "expect": {"calls": [{"tool": "t3_thread_organize", "args": {"action": "move", "threadId": "thread-auth-retry", "projectId": "project-api"}}], "callsMustNot": [{"tool": "t3_thread_launch"}, {"tool": "create_threads"}, {"tool": "t3_thread_transfer"}]}, "maxSteps": 6} diff --git a/packages/client-runtime/src/state/models.ts b/packages/client-runtime/src/state/models.ts index 6bc914b8572fd..4939b540aeabc 100644 --- a/packages/client-runtime/src/state/models.ts +++ b/packages/client-runtime/src/state/models.ts @@ -18,6 +18,7 @@ import type { } from "@t3tools/contracts"; import * as DateTime from "effect/DateTime"; +import { isScratchProject } from "./projects.ts"; import { formatSubagentDisplayTitle } from "./subagentDisplay.ts"; export interface EnvironmentProject extends OrchestrationProjectShell { @@ -25,6 +26,21 @@ export interface EnvironmentProject extends OrchestrationProjectShell { readonly isScratch?: true; } +/** Where a thread can move: the other live projects on its environment, except No project. */ +export function threadMoveTargets( + projects: ReadonlyArray, + thread: { readonly environmentId: EnvironmentId; readonly projectId: ProjectId }, + scratchWorkspaceRoot: string | null | undefined, +): ReadonlyArray { + return projects.filter( + (project) => + project.environmentId === thread.environmentId && + project.id !== thread.projectId && + project.archivedAt == null && + !isScratchProject(project, scratchWorkspaceRoot), + ); +} + /** * The projection stays nested so the server projection and all structurally * shared collections retain their identities. diff --git a/packages/client-runtime/src/state/projectCommands.ts b/packages/client-runtime/src/state/projectCommands.ts index 119b1de81fcb6..0f5e19e7aa01d 100644 --- a/packages/client-runtime/src/state/projectCommands.ts +++ b/packages/client-runtime/src/state/projectCommands.ts @@ -223,6 +223,12 @@ export function createProjectEnvironmentAtoms( scheduler: projectScheduler, concurrency: { mode: "serial", key: ({ environmentId }) => environmentId }, }), + moveThread: createEnvironmentRpcCommand(runtime, { + label: "environment-data:projects:move-thread", + tag: WS_METHODS.projectsMoveThread, + scheduler: projectScheduler, + concurrency: { mode: "serial", key: ({ environmentId }) => environmentId }, + }), writeFile: createEnvironmentRpcCommand(runtime, { label: "environment-data:projects:write-file", tag: WS_METHODS.projectsWriteFile, diff --git a/packages/contracts/src/clientRpcPermissions.ts b/packages/contracts/src/clientRpcPermissions.ts index 8681c1ea8abeb..6fa13eb05b0dc 100644 --- a/packages/contracts/src/clientRpcPermissions.ts +++ b/packages/contracts/src/clientRpcPermissions.ts @@ -43,6 +43,7 @@ export const CLIENT_GUARDED_RPC_SCOPES = { // Writing a guide runs a model on this environment's providers, which reading one does not. [WS_METHODS.pullRequestsGenerateReviewGuide]: AuthOrchestrationOperateScope, [WS_METHODS.projectsCreateFromThread]: AuthOrchestrationOperateScope, + [WS_METHODS.projectsMoveThread]: AuthOrchestrationOperateScope, [WS_METHODS.sourceControlCloneRepository]: AuthSourceControlWriteScope, [WS_METHODS.sourceControlPublishRepository]: AuthSourceControlWriteScope, [WS_METHODS.sourceControlStar]: AuthSourceControlWriteScope, diff --git a/packages/contracts/src/environment.ts b/packages/contracts/src/environment.ts index ad1cfe30b0214..632f58d97bd97 100644 --- a/packages/contracts/src/environment.ts +++ b/packages/contracts/src/environment.ts @@ -136,6 +136,7 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({ threadActiveReorder: Schema.optionalKey(Schema.Boolean), threadAutoSettleOptOut: Schema.optionalKey(Schema.Boolean), threadProjectFromScratch: Schema.optionalKey(Schema.Boolean), + threadMoveToProject: Schema.optionalKey(Schema.Boolean), threadTitleRegeneration: Schema.optionalKey(Schema.Boolean), threadVisitedTracking: Schema.optionalKey(Schema.Boolean), threadPullRequestLinking: Schema.optionalKey(Schema.Boolean), diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index 44e9aa8290e9a..477332ed8aa4e 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -474,6 +474,8 @@ export const OrchestrationV2AppThread = Schema.Struct({ interactionMode: ProviderInteractionMode, branch: Schema.NullOr(TrimmedNonEmptyString), worktreePath: Schema.NullOr(TrimmedNonEmptyString), + /** Set when a move changed the thread's folder, so later checkpoints keep their own repository. */ + checkpointScopeProjectId: Schema.optional(ProjectId), linkedPullRequest: Schema.optional(Schema.NullOr(ThreadLinkedPullRequest)), pullRequests: Schema.optional(Schema.Array(ThreadPullRequestLink)), branchPullRequest: Schema.optional(Schema.NullOr(ThreadLinkedPullRequest)), @@ -3605,6 +3607,18 @@ const OrchestrationV2InternalCommand = Schema.Union([ text: Schema.String, attachments: Schema.optional(Schema.Array(ChatAttachment)), }), + /** + * Moves an idle thread into another project's root folder. A changed folder ends its provider + * sessions, so the next turn resumes or hands off the conversation there. + */ + Schema.Struct({ + type: Schema.Literal("thread.project.move"), + commandId: CommandId, + threadId: ThreadId, + projectId: ProjectId, + /** The target root's current branch, read by the caller. */ + branch: Schema.NullOr(TrimmedNonEmptyString), + }), /** Moves a thread to a project rooted at the folder it already works in, so its cwd never changes. */ Schema.Struct({ type: Schema.Literal("thread.project.adopt-folder"), diff --git a/packages/contracts/src/project.ts b/packages/contracts/src/project.ts index 80848ba81f557..f51e67bcdb08b 100644 --- a/packages/contracts/src/project.ts +++ b/packages/contracts/src/project.ts @@ -553,6 +553,12 @@ export const ProjectCreateFromThreadResult = Schema.Struct({ }); export type ProjectCreateFromThreadResult = typeof ProjectCreateFromThreadResult.Type; +export const ProjectMoveThreadInput = Schema.Struct({ + threadId: ThreadId, + projectId: ProjectId, +}); +export type ProjectMoveThreadInput = typeof ProjectMoveThreadInput.Type; + export class ProjectWriteFileError extends Schema.TaggedError()( "ProjectWriteFileError", { diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts index 00025550dc41a..63e0767474bdc 100644 --- a/packages/contracts/src/rpc.ts +++ b/packages/contracts/src/rpc.ts @@ -246,6 +246,7 @@ import { ProjectCreateNewResult, ProjectCreateFromThreadInput, ProjectCreateFromThreadResult, + ProjectMoveThreadInput, ProjectEnsureScratchResult, ProjectListEntriesError, ProjectListEntriesInput, @@ -430,6 +431,7 @@ export const WS_METHODS = { projectsEnsureScratch: "projects.ensureScratch", projectsCreateNew: "projects.createNew", projectsCreateFromThread: "projects.createFromThread", + projectsMoveThread: "projects.moveThread", shellOpenInEditor: "shell.openInEditor", @@ -1431,6 +1433,11 @@ const WsProjectsCreateFromThreadRpc = Rpc.make(WS_METHODS.projectsCreateFromThre error: Schema.Union([OrchestrationDispatchCommandError, EnvironmentAuthorizationError]), }); +const WsProjectsMoveThreadRpc = Rpc.make(WS_METHODS.projectsMoveThread, { + payload: ProjectMoveThreadInput, + error: Schema.Union([OrchestrationDispatchCommandError, EnvironmentAuthorizationError]), +}); + const WsShellOpenInEditorRpc = Rpc.make(WS_METHODS.shellOpenInEditor, { payload: LaunchEditorInput, error: Schema.Union([ExternalLauncherError, EnvironmentAuthorizationError]), @@ -2250,6 +2257,7 @@ export const WsRpcGroup = RpcGroup.make( WsProjectsEnsureScratchRpc, WsProjectsCreateNewRpc, WsProjectsCreateFromThreadRpc, + WsProjectsMoveThreadRpc, WsProjectsWriteFileRpc, WsProjectsMutateRpc, WsShellOpenInEditorRpc, diff --git a/packages/shared/package.json b/packages/shared/package.json index 0e46f15e7aa45..efd26b1b68fba 100644 --- a/packages/shared/package.json +++ b/packages/shared/package.json @@ -3,6 +3,10 @@ "private": true, "type": "module", "exports": { + "./threadMove": { + "types": "./src/threadMove.ts", + "import": "./src/threadMove.ts" + }, "./png": { "types": "./src/png.ts", "import": "./src/png.ts" diff --git a/packages/shared/src/threadMove.ts b/packages/shared/src/threadMove.ts new file mode 100644 index 0000000000000..9fc39ce925df4 --- /dev/null +++ b/packages/shared/src/threadMove.ts @@ -0,0 +1,9 @@ +/** What moving a thread to another project changes, worded the same for people and agents. */ +export function threadMoveNotice(input: { + readonly projectTitle: string; + readonly fromWorktree: boolean; +}): string { + return input.fromWorktree + ? `The agent will work in ${input.projectTitle}'s root folder, not this thread's worktree. The worktree and its branch stay on disk, but the agent won't see changes left there; earlier diffs open while it exists, and earlier turns can't be restored.` + : `The conversation moves with it, and the agent works in ${input.projectTitle}'s folder from the next message. Earlier diffs open while their original folder exists.`; +} From 14fe8363ea1dec1e446a87e302a1dfa23fac1ebe Mon Sep 17 00:00:00 2001 From: Batch Processor <46352227+batchema@users.noreply.github.com> Date: Sat, 14 Nov 2026 22:29:56 +0100 Subject: [PATCH 14/20] fix: review round 1 for moving threads between projects - Refuse a move while the thread's rollback effect is still pending or running. - Scheduled tasks follow the thread's committed project, so racing moves converge. - Turn diffs no longer depend on the current folder being a Git repository. - Clearer move notice: files from earlier turns can't be restored after any move. --- apps/server/src/mcp/toolkits/thread/tools.ts | 2 +- .../src/orchestration-v2/Orchestrator.ts | 12 +++ .../SelectionRestart.integration.test.ts | 64 ++++++++++++++- .../src/orchestration-v2/runtimeLayer.test.ts | 56 ++++++++++--- apps/server/src/project/ThreadProjectMove.ts | 17 +++- .../src/components/DiffPanel.browser.test.tsx | 80 ++++++++++++------- apps/web/src/components/DiffPanel.tsx | 5 +- docs/user/thread-sidebar.md | 8 +- evals/mcp-tool-use/cases/projects.ndjson | 2 +- packages/shared/src/threadMove.ts | 4 +- 10 files changed, 192 insertions(+), 58 deletions(-) diff --git a/apps/server/src/mcp/toolkits/thread/tools.ts b/apps/server/src/mcp/toolkits/thread/tools.ts index 9c90a894a8fff..150debe747d4e 100644 --- a/apps/server/src/mcp/toolkits/thread/tools.ts +++ b/apps/server/src/mcp/toolkits/thread/tools.ts @@ -32,7 +32,7 @@ import * as McpInvocationContext from "../../McpInvocationContext.ts"; const ThreadOrganizeTool = Tool.make("t3_thread_organize", { description: - "Pin, snooze, settle, archive, mark unread, or move a thread to another project. Omit `threadId` for this thread. `snooze` needs `snoozedUntil`. Settling this thread applies at turn end. A failed turn or queued message leaves it active. `move` needs `projectId` and an idle thread (not this one mid-turn); its history continues in that project's root. From a worktree, its changes stay behind and earlier turns can't be restored; `notice` says what changed.", + "Pin, snooze, settle, archive, mark unread, or move a thread to another project. Omit `threadId` for this thread. `snooze` needs `snoozedUntil`. Settling this thread applies at turn end. A failed turn or queued message leaves it active. `move` needs `projectId` and an idle thread (not this one mid-turn); its history continues in that project's root. Earlier turns' files can't be restored, and a worktree's changes stay behind; `notice` says what changed.", parameters: Schema.Struct({ environmentId: OrchestratorMcpEnvironmentTarget, threadId: Schema.optional(ThreadId), diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 24b9b9ac2a4d8..f30fc65c7db33 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -4410,6 +4410,18 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio if (threadHasUnfinishedWork(records)) { return yield* reject("still has work in progress. Finish or stop it first."); } + // Its effect would restore files and the provider thread for the old folder. + const rollbackEffects = + thread.rollbackRequestId === undefined + ? [] + : yield* effectOutbox + .listByCommandId(thread.rollbackRequestId) + .pipe(mapDispatchError(command)); + if ( + rollbackEffects.some((effect) => effect.status === "pending" || effect.status === "running") + ) { + return yield* reject("is still rolling back. Wait for it to finish, then move it."); + } const current = yield* projects.get(thread.projectId).pipe(mapDispatchError(command)); const target = yield* projects.get(command.projectId).pipe(mapDispatchError(command)); if (Option.isNone(target) || target.value.deletedAt !== null) { diff --git a/apps/server/src/orchestration-v2/SelectionRestart.integration.test.ts b/apps/server/src/orchestration-v2/SelectionRestart.integration.test.ts index 2fa6adc35dd2d..2073d79c0882a 100644 --- a/apps/server/src/orchestration-v2/SelectionRestart.integration.test.ts +++ b/apps/server/src/orchestration-v2/SelectionRestart.integration.test.ts @@ -26,6 +26,7 @@ import * as Ref from "effect/Ref"; import * as Stream from "effect/Stream"; import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts"; +import * as EffectOutbox from "./EffectOutbox.ts"; import * as EffectWorker from "./EffectWorker.ts"; import * as EventSink from "./EventSink.ts"; import * as Orchestrator from "./Orchestrator.ts"; @@ -610,11 +611,15 @@ it.live("moving a thread to another project resumes its conversation in the new failedReplacementOpen: true, }); const database = SqlitePersistence.layerMemory; + const backgroundWork = yield* Ref.make(false); + const adapter = makeRestartAdapter(state, exclusiveCapabilities); + const rollbackCommandId = CommandId.make(`${name}:rollback`); const result = yield* Effect.gen(function* () { const orchestrator = yield* Orchestrator.OrchestratorV2; const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; const eventSink = yield* EventSink.EventSinkV2; + const outbox = yield* EffectOutbox.EffectOutboxV2; const projects = yield* ProjectStore.ProjectStoreV2; for (const [index, [projectId, workspaceRoot]] of ( [ @@ -686,14 +691,18 @@ it.live("moving a thread to another project resumes its conversation in the new worktreePath: null, }); const first = yield* send("first"); - const move = (projectId: ProjectId, branch: string | null) => + const move = (projectId: ProjectId, branch: string | null, attempt = "") => orchestrator.dispatch({ type: "thread.project.move", - commandId: CommandId.make(`${name}:move:${projectId}`), + commandId: CommandId.make(`${name}:move:${projectId}${attempt}`), threadId, projectId, branch, }); + // Detaching would end the session's background agents, as with a worktree handoff. + yield* Ref.set(backgroundWork, true); + const refusedBusy = yield* move(targetId, "target-branch", ":busy").pipe(Effect.flip); + yield* Ref.set(backgroundWork, false); const moved = yield* move(targetId, "target-branch"); yield* worker.drain(); const second = yield* send("second"); @@ -703,13 +712,58 @@ it.live("moving a thread to another project resumes its conversation in the new const detached = yield* eventSink .readByCommandId({ commandId: CommandId.make(`${name}:move:${targetId}`) }) .pipe(Stream.runCollect); - return { first, moved, second, third, detached: [...detached] }; + // A rollback whose effect has not run yet would restore the old folder after the move. + const occurredAt = yield* DateTime.now; + yield* eventSink.write({ + events: [ + { + id: EventId.make(`event:${name}:rollback`), + type: "thread.metadata-updated", + threadId, + providerInstanceId: third.thread.providerInstanceId, + occurredAt, + payload: { ...third.thread, rollbackRequestId: rollbackCommandId }, + }, + ], + }); + yield* outbox.enqueue([ + { + id: `effect:${rollbackCommandId}`, + commandId: rollbackCommandId, + threadId, + request: { + type: "provider-thread.rollback", + providerThreadId: third.providerThreads[0]!.id, + checkpointId: third.checkpoints[0]!.id, + scopeId: third.checkpoints[0]!.scopeId, + }, + }, + ]); + const refusedRollback = yield* move(targetId, null, ":rollback").pipe(Effect.flip); + return { + first, + moved, + second, + third, + detached: [...detached], + refusedBusy, + refusedRollback, + }; }).pipe( Effect.provide( Layer.merge( ProviderReplayHarness.layerWithRegistry( { name }, - ProviderAdapterRegistry.layerSingle(makeRestartAdapter(state, exclusiveCapabilities)), + ProviderAdapterRegistry.layerSingle({ + ...adapter, + openSession: (input) => + adapter.openSession(input).pipe( + Effect.map((session) => ({ + ...session, + hasPendingBackgroundWork: Ref.get(backgroundWork), + })), + ), + }), { databaseLayer: database }, ), ProjectStore.layer.pipe(Layer.provide(database)), @@ -717,6 +771,8 @@ it.live("moving a thread to another project resumes its conversation in the new ), ); + assert.include(String(result.refusedBusy.cause), "still running background agents or commands"); + assert.include(String(result.refusedRollback.cause), "still rolling back"); const firstSession = result.first.providerSessions.find( (session) => session.status !== "stopped" && session.status !== "error", ); diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index 4e812ae195267..b0e84bfe99f33 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -10193,18 +10193,18 @@ it.layer(layerScratchPromotionTest)("turning a No project thread into a project" }); const layerThreadProjectMoveTest = ThreadProjectMove.layer.pipe( - Layer.provide( - Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({ - isScratchProject: (projectId) => Effect.succeed(projectId === SCRATCH_PROJECT_ID), - namedProjectsRoot: "/projects", - }), - ), - Layer.provide( - Layer.mock(GitWorkflow.GitWorkflowService)({ - currentBranch: (cwd) => Effect.succeed(`branch-of:${cwd}`), - }), + Layer.provideMerge( + Layer.mergeAll( + Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({ + isScratchProject: (projectId) => Effect.succeed(projectId === SCRATCH_PROJECT_ID), + namedProjectsRoot: "/projects", + }), + Layer.mock(GitWorkflow.GitWorkflowService)({ + currentBranch: (cwd) => Effect.succeed(`branch-of:${cwd}`), + }), + NodeCrypto.layer, + ), ), - Layer.provide(NodeCrypto.layer), Layer.provideMerge(layerProjectDeletionTest), ); @@ -10219,9 +10219,11 @@ it.layer(layerThreadProjectMoveTest)("moving a thread to another project", (it) const tasks = yield* ScheduledTaskService.ScheduledTaskService; const sourceId = ProjectId.make("thread-move-source"); const targetId = ProjectId.make("thread-move-target"); + const otherId = ProjectId.make("thread-move-other"); for (const [projectId, workspaceRoot] of [ [sourceId, "/tmp/thread-move-source"], [targetId, "/tmp/thread-move-target"], + [otherId, "/tmp/thread-move-other"], [SCRATCH_PROJECT_ID, SCRATCH_ROOT], ] as const) { if (Option.isNone(yield* projects.getById(projectId))) { @@ -10291,7 +10293,7 @@ it.layer(layerThreadProjectMoveTest)("moving a thread to another project", (it) assert.equal((yield* shellOf(busyId))?.projectId, sourceId); const fromWorktree = yield* move({ threadId, projectId: targetId }); - assert.include(fromWorktree.notice, "not this thread's worktree"); + assert.include(fromWorktree.notice, "The worktree and its branch stay on disk"); const moved = yield* shellOf(threadId); assert.equal(moved?.projectId, targetId); // It lands in the project root; the old worktree stays where it was. @@ -10303,7 +10305,37 @@ it.layer(layerThreadProjectMoveTest)("moving a thread to another project", (it) yield* move({ threadId, projectId: targetId }); const fromRoot = yield* move({ threadId, projectId: sourceId }); assert.notInclude(fromRoot.notice, "worktree"); + assert.include(fromRoot.notice, "files from earlier turns can't be restored"); assert.equal((yield* shellOf(threadId))?.projectId, sourceId); + + // Another move commits between this move's commit and its task update. + const threads = yield* ThreadManagementService.ThreadManagementService; + const racing = Layer.fresh(ThreadProjectMove.layer).pipe( + Layer.provide( + Layer.succeed(ThreadManagementService.ThreadManagementService, { + ...threads, + dispatch: (command) => + threads.dispatch(command).pipe( + Effect.tap(() => + command.type === "thread.project.move" && command.projectId === targetId + ? threads.dispatch({ + ...command, + commandId: CommandId.make("thread-move-racing"), + projectId: otherId, + }) + : Effect.void, + ), + ), + }), + ), + ); + yield* ThreadProjectMove.ThreadProjectMove.pipe( + Effect.flatMap((service) => service.move({ threadId, projectId: targetId })), + Effect.provide(racing), + ); + assert.equal((yield* shellOf(threadId))?.projectId, otherId); + const raced = (yield* tasks.list()).tasks.find((candidate) => candidate.id === task.id); + assert.equal(raced?.projectId, otherId); }), ); }); diff --git a/apps/server/src/project/ThreadProjectMove.ts b/apps/server/src/project/ThreadProjectMove.ts index fc8cf2c2db936..78a69c99b3bd0 100644 --- a/apps/server/src/project/ThreadProjectMove.ts +++ b/apps/server/src/project/ThreadProjectMove.ts @@ -94,9 +94,20 @@ const make = Effect.gen(function* () { ), ); } - yield* scheduledTasks - .moveThreadTasks({ threadIds: [input.threadId], projectId: input.projectId }) - .pipe(Effect.mapError(fail("Moved the thread, but not its scheduled tasks. Try again."))); + // Another move can commit before these writes, so follow the thread until a read matches. + const currentProject = threads.getThreadShell(input.threadId).pipe( + Effect.map((shell) => shell?.projectId ?? input.projectId), + Effect.mapError(fail("Could not read the thread.")), + ); + let projectId = yield* currentProject; + while (true) { + yield* scheduledTasks + .moveThreadTasks({ threadIds: [input.threadId], projectId }) + .pipe(Effect.mapError(fail("Moved the thread, but not its scheduled tasks. Try again."))); + const now = yield* currentProject; + if (now === projectId) break; + projectId = now; + } return { notice: threadMoveNotice({ projectTitle: target.value.title, diff --git a/apps/web/src/components/DiffPanel.browser.test.tsx b/apps/web/src/components/DiffPanel.browser.test.tsx index 503f9b60c1b5d..4a569c03f7254 100644 --- a/apps/web/src/components/DiffPanel.browser.test.tsx +++ b/apps/web/src/components/DiffPanel.browser.test.tsx @@ -273,35 +273,57 @@ it.each([false, true])( }, ); -it("says a turn diff cut off at the server's size limit is incomplete", async () => { - using context = setup("origin/orphan"); - state.checkpoints = [ - { - runId: "run", - checkpointTurnCount: 1, - checkpointRef: "ref", - status: "ready", - files: [], - assistantMessageId: null, - completedAt: "2026-01-01T00:00:00Z", - }, - ]; - state.checkpointDiff = { - diff: "diff --git a/first.txt b/first.txt\n--- a/first.txt\n+++ b/first.txt\n@@ -0,0 +1 @@\n+visible\n\n[truncated]", - }; - useDiffPanelStore.getState().selectTurn(context.threadRef, RunId.make("run")); - await using screen = await render( - -
- -
-
, - ); - await expect.element(screen.getByText("first.txt", { exact: true }).first()).toBeVisible(); - await expect - .element(screen.getByText("This preview exceeds the size limit. Changes shown are incomplete.")) - .toBeVisible(); -}); +// A moved thread's turns diff in the folder they ran in, whatever the current project is. +it.each([true, false])( + "says a turn diff cut off at the server's size limit is incomplete (current folder is git: %s)", + async (isRepo) => { + using context = setup("origin/orphan"); + if (!isRepo) { + state.status = Atom.make( + AsyncResult.success({ + isRepo: false, + hasPrimaryRemote: false, + isDefaultRef: false, + refName: null, + hasWorkingTreeChanges: false, + workingTree: { rootPath: cwd, files: [], insertions: 0, deletions: 0 }, + hasUpstream: false, + aheadCount: 0, + behindCount: 0, + pr: null, + }), + ); + } + state.checkpoints = [ + { + runId: "run", + checkpointTurnCount: 1, + checkpointRef: "ref", + status: "ready", + files: [], + assistantMessageId: null, + completedAt: "2026-01-01T00:00:00Z", + }, + ]; + state.checkpointDiff = { + diff: "diff --git a/first.txt b/first.txt\n--- a/first.txt\n+++ b/first.txt\n@@ -0,0 +1 @@\n+visible\n\n[truncated]", + }; + useDiffPanelStore.getState().selectTurn(context.threadRef, RunId.make("run")); + await using screen = await render( + +
+ +
+
, + ); + await expect.element(screen.getByText("first.txt", { exact: true }).first()).toBeVisible(); + await expect + .element( + screen.getByText("This preview exceeds the size limit. Changes shown are incomplete."), + ) + .toBeVisible(); + }, +); // Paths as git's numstat reports them; the parsed patch trims the trailing space from its name. it.each([ diff --git a/apps/web/src/components/DiffPanel.tsx b/apps/web/src/components/DiffPanel.tsx index 99e0b07c1845e..eac530d367fbd 100644 --- a/apps/web/src/components/DiffPanel.tsx +++ b/apps/web/src/components/DiffPanel.tsx @@ -360,7 +360,8 @@ export default function DiffPanel({ ignoreWhitespace: diffIgnoreWhitespace, cacheScope: selectedTurn ? `turn:${selectedTurn.runId}` : null, }, - { enabled: isGitRepo && selectedTurn !== undefined }, + // Checkpoints diff in the folder each turn ran in, which a moved thread's current one may not be. + { enabled: selectedTurn !== undefined }, ); const branchDiffPreviewInput = canReadFiles && isGitSelection && activeThread && activeCwd @@ -1299,7 +1300,7 @@ export default function DiffPanel({
Select a thread to inspect turn diffs.
- ) : !isGitRepo && !toolCallSelection ? ( + ) : !isGitRepo && !toolCallSelection && selectedTurn === undefined ? (
Turn diffs are unavailable because this project is not a git repository.
diff --git a/docs/user/thread-sidebar.md b/docs/user/thread-sidebar.md index c655e19a847ed..64d17e206e7e5 100644 --- a/docs/user/thread-sidebar.md +++ b/docs/user/thread-sidebar.md @@ -53,10 +53,10 @@ Started in the wrong place? Pick **Move to project** from the thread's menu, or machine. The thread keeps its history and continues in that project's root folder from your next message. Stop a running thread before moving it. -Earlier turns keep their diffs for as long as the folder they ran in exists. A -thread that had its own worktree leaves it behind: the worktree and branch stay on -disk, but the agent no longer sees changes left there, and earlier turns can't be -restored. The old worktree shows as unused in +Earlier turns keep their diffs for as long as the folder they ran in exists, but +their files can't be restored. A thread that had its own worktree leaves it behind: +the worktree and branch stay on disk, but the agent no longer sees changes left +there. The old worktree shows as unused in [Storage cleanup](./project-settings.md#storage-cleanup). To keep working in a fresh worktree, hand the moved thread off to one. diff --git a/evals/mcp-tool-use/cases/projects.ndjson b/evals/mcp-tool-use/cases/projects.ndjson index 409f4f4cdd082..8048dc129ad0b 100644 --- a/evals/mcp-tool-use/cases/projects.ndjson +++ b/evals/mcp-tool-use/cases/projects.ndjson @@ -1,2 +1,2 @@ {"id": "archive-project-not-delete", "area": "projects", "kind": "guard", "pattern": "archive a project by deleting it", "experience": "Projects gained an archive flag. Asked to archive a finished project, an agent must set archived, not remove the project and its threads.", "rule": "t3_project_update archived: Threads and files are kept.", "privacy": "commit-safe", "setup": {"role": "top", "mocks": {"t3_project_list": {"projects": [{"id": "project-app", "title": "app", "workspaceRoot": "/home/dev/code/app", "defaultModelSelection": null, "scripts": [], "pinnedAt": null, "archivedAt": null, "createdAt": "2026-09-01T00:00:00.000Z", "updatedAt": "2026-10-20T00:00:00.000Z", "deletedAt": null}, {"id": "project-old-site", "title": "old-site", "workspaceRoot": "/home/dev/code/old-site", "defaultModelSelection": null, "scripts": [], "pinnedAt": null, "archivedAt": null, "createdAt": "2026-03-01T00:00:00.000Z", "updatedAt": "2026-04-02T00:00:00.000Z", "deletedAt": null}], "nextCursor": null}}}, "prompt": "I'm done with the old-site project. Archive it in T3 Code so it stops showing up in my project pickers.", "expect": {"calls": [{"tool": "t3_project_update", "args": {"projectId": "project-old-site", "archived": true}}], "callsMustNot": [{"tool": "t3_project_delete"}, {"tool": "t3_project_update", "args": {"projectId": "project-app"}}]}, "maxSteps": 6} -{"id": "move-thread-to-another-project", "area": "projects", "kind": "bad", "pattern": "move a thread by copying it", "experience": "Asked to move a started thread into the right project, an agent had no move action, so it could only fork the thread or start a new one, which leaves the conversation behind (batchema/t3code#6).", "rule": "t3_thread_organize move: the thread keeps its history and continues in the target project's root.", "privacy": "commit-safe", "setup": {"role": "top", "mocks": {"t3_project_list": {"projects": [{"id": "project-web", "title": "web", "workspaceRoot": "/home/user/code/web", "defaultModelSelection": null, "scripts": [], "pinnedAt": null, "archivedAt": null, "createdAt": "2026-09-01T00:00:00.000Z", "updatedAt": "2026-10-20T00:00:00.000Z", "deletedAt": null}, {"id": "project-api", "title": "api", "workspaceRoot": "/home/user/code/api", "defaultModelSelection": null, "scripts": [], "pinnedAt": null, "archivedAt": null, "createdAt": "2026-09-01T00:00:00.000Z", "updatedAt": "2026-10-20T00:00:00.000Z", "deletedAt": null}], "nextCursor": null}, "t3_thread_organize": {"movedToProjectId": "project-api", "notice": "The conversation moves with it, and the agent works in api's folder from the next message. Earlier diffs open while their original folder exists."}}}, "prompt": "I started thread thread-auth-retry in the web project by mistake; the bug is in api. Move that thread over to the api project so it keeps going there.", "expect": {"calls": [{"tool": "t3_thread_organize", "args": {"action": "move", "threadId": "thread-auth-retry", "projectId": "project-api"}}], "callsMustNot": [{"tool": "t3_thread_launch"}, {"tool": "create_threads"}, {"tool": "t3_thread_transfer"}]}, "maxSteps": 6} +{"id": "move-thread-to-another-project", "area": "projects", "kind": "bad", "pattern": "move a thread by copying it", "experience": "Asked to move a started thread into the right project, an agent had no move action, so it could only fork the thread or start a new one, which leaves the conversation behind (batchema/t3code#6).", "rule": "t3_thread_organize move: the thread keeps its history and continues in the target project's root.", "privacy": "commit-safe", "setup": {"role": "top", "mocks": {"t3_project_list": {"projects": [{"id": "project-web", "title": "web", "workspaceRoot": "/home/user/code/web", "defaultModelSelection": null, "scripts": [], "pinnedAt": null, "archivedAt": null, "createdAt": "2026-09-01T00:00:00.000Z", "updatedAt": "2026-10-20T00:00:00.000Z", "deletedAt": null}, {"id": "project-api", "title": "api", "workspaceRoot": "/home/user/code/api", "defaultModelSelection": null, "scripts": [], "pinnedAt": null, "archivedAt": null, "createdAt": "2026-09-01T00:00:00.000Z", "updatedAt": "2026-10-20T00:00:00.000Z", "deletedAt": null}], "nextCursor": null}, "t3_thread_organize": {"movedToProjectId": "project-api", "notice": "The conversation moves with it, and the agent works in api's folder from the next message. Earlier diffs open while their original folder exists, and files from earlier turns can't be restored."}}}, "prompt": "I started thread thread-auth-retry in the web project by mistake; the bug is in api. Move that thread over to the api project so it keeps going there.", "expect": {"calls": [{"tool": "t3_thread_organize", "args": {"action": "move", "threadId": "thread-auth-retry", "projectId": "project-api"}}], "callsMustNot": [{"tool": "t3_thread_launch"}, {"tool": "create_threads"}, {"tool": "t3_thread_transfer"}]}, "maxSteps": 6} diff --git a/packages/shared/src/threadMove.ts b/packages/shared/src/threadMove.ts index 9fc39ce925df4..3dc57eaa8037d 100644 --- a/packages/shared/src/threadMove.ts +++ b/packages/shared/src/threadMove.ts @@ -4,6 +4,6 @@ export function threadMoveNotice(input: { readonly fromWorktree: boolean; }): string { return input.fromWorktree - ? `The agent will work in ${input.projectTitle}'s root folder, not this thread's worktree. The worktree and its branch stay on disk, but the agent won't see changes left there; earlier diffs open while it exists, and earlier turns can't be restored.` - : `The conversation moves with it, and the agent works in ${input.projectTitle}'s folder from the next message. Earlier diffs open while their original folder exists.`; + ? `The agent will work in ${input.projectTitle}'s root folder. The worktree and its branch stay on disk, but the agent won't see changes left there. Earlier diffs open while the worktree exists, and files from earlier turns can't be restored.` + : `The conversation moves with it, and the agent works in ${input.projectTitle}'s folder from the next message. Earlier diffs open while their original folder exists, and files from earlier turns can't be restored.`; } From 998062cd1e6f8022645b9492851a8297733df2e8 Mon Sep 17 00:00:00 2001 From: Batch Processor <46352227+batchema@users.noreply.github.com> Date: Sat, 14 Nov 2026 22:43:16 +0100 Subject: [PATCH 15/20] fix(web): turns without a checkpoint keep the not-a-git-repository note Fetching a selected turn's diff regardless of the current folder made non-git turns, whose checkpoints are missing, show a load failure. Historical diffs now load when the folder is git or the turn's checkpoint is ready. Co-Authored-By: Claude Opus 5.5 --- .../src/components/DiffPanel.browser.test.tsx | 63 ++++++++++++++----- apps/web/src/components/DiffPanel.tsx | 7 ++- 2 files changed, 51 insertions(+), 19 deletions(-) diff --git a/apps/web/src/components/DiffPanel.browser.test.tsx b/apps/web/src/components/DiffPanel.browser.test.tsx index 4a569c03f7254..27f6875f86909 100644 --- a/apps/web/src/components/DiffPanel.browser.test.tsx +++ b/apps/web/src/components/DiffPanel.browser.test.tsx @@ -273,27 +273,58 @@ it.each([false, true])( }, ); +function setNotARepo() { + state.status = Atom.make( + AsyncResult.success({ + isRepo: false, + hasPrimaryRemote: false, + isDefaultRef: false, + refName: null, + hasWorkingTreeChanges: false, + workingTree: { rootPath: cwd, files: [], insertions: 0, deletions: 0 }, + hasUpstream: false, + aheadCount: 0, + behindCount: 0, + pr: null, + }), + ); +} + +it("explains a turn without a checkpoint in a folder outside git", async () => { + using context = setup("origin/orphan"); + setNotARepo(); + state.checkpoints = [ + { + runId: "run", + checkpointTurnCount: 1, + checkpointRef: "ref", + status: "missing", + files: [], + assistantMessageId: null, + completedAt: "2026-01-01T00:00:00Z", + }, + ]; + useDiffPanelStore.getState().selectTurn(context.threadRef, RunId.make("run")); + await using screen = await render( + +
+ +
+
, + ); + await expect + .element( + screen.getByText("Turn diffs are unavailable because this project is not a git repository."), + ) + .toBeVisible(); +}); + // A moved thread's turns diff in the folder they ran in, whatever the current project is. it.each([true, false])( "says a turn diff cut off at the server's size limit is incomplete (current folder is git: %s)", async (isRepo) => { using context = setup("origin/orphan"); - if (!isRepo) { - state.status = Atom.make( - AsyncResult.success({ - isRepo: false, - hasPrimaryRemote: false, - isDefaultRef: false, - refName: null, - hasWorkingTreeChanges: false, - workingTree: { rootPath: cwd, files: [], insertions: 0, deletions: 0 }, - hasUpstream: false, - aheadCount: 0, - behindCount: 0, - pr: null, - }), - ); - } + if (!isRepo) setNotARepo(); state.checkpoints = [ { runId: "run", diff --git a/apps/web/src/components/DiffPanel.tsx b/apps/web/src/components/DiffPanel.tsx index eac530d367fbd..f0f648c34a8c5 100644 --- a/apps/web/src/components/DiffPanel.tsx +++ b/apps/web/src/components/DiffPanel.tsx @@ -332,6 +332,8 @@ export default function DiffPanel({ : (orderedTurnDiffSummaries.find((summary) => summary.runId === selectedRunId) ?? orderedTurnDiffSummaries[0]); const selectedCheckpointTurnCount = selectedTurn?.checkpointTurnCount; + // A moved thread's turns diff in the folder they ran in, which may be git when the current one isn't. + const canDiffSelectedTurn = isGitRepo || selectedTurn?.status === "ready"; const latestTurn = orderedTurnDiffSummaries[0]; const reviewSectionId = toolCallSelection ? `tool-call:${toolCallSelection.threadId}:${toolCallSelection.itemId}` @@ -360,8 +362,7 @@ export default function DiffPanel({ ignoreWhitespace: diffIgnoreWhitespace, cacheScope: selectedTurn ? `turn:${selectedTurn.runId}` : null, }, - // Checkpoints diff in the folder each turn ran in, which a moved thread's current one may not be. - { enabled: selectedTurn !== undefined }, + { enabled: canDiffSelectedTurn && selectedTurn !== undefined }, ); const branchDiffPreviewInput = canReadFiles && isGitSelection && activeThread && activeCwd @@ -1300,7 +1301,7 @@ export default function DiffPanel({
Select a thread to inspect turn diffs.
- ) : !isGitRepo && !toolCallSelection && selectedTurn === undefined ? ( + ) : !canDiffSelectedTurn && !toolCallSelection ? (
Turn diffs are unavailable because this project is not a git repository.
From fd19ea46ad03a01d72526a748ed2fd2cbce82058 Mon Sep 17 00:00:00 2001 From: Batch Processor <46352227+batchema@users.noreply.github.com> Date: Sun, 15 Nov 2026 00:55:03 +0100 Subject: [PATCH 16/20] feat: move a started thread to another machine A thread's conversation can now move to a project on another connected machine. The client exports it from the source, imports it on the target as run-less history (the same model V1 imports use, so the first message hands it to a fresh provider session), then archives the source with a note saying where it went. Checkpoints, files, worktrees, attachments and scheduled tasks stay behind, and the confirmation names only those that apply. A failed import changes nothing; a failed archive is reported so the user doesn't keep two live copies. Reachable from the sidebar and chat-header thread menus, the command palette and the mobile row menu, on servers that advertise threadMoveToMachine on both ends. Co-Authored-By: Claude Opus 5.5 --- .../features/threads/moveThreadToMachine.ts | 82 +++++ .../features/threads/thread-list-v2-items.tsx | 30 ++ apps/server/src/auth/RpcAuthorization.test.ts | 9 + apps/server/src/auth/RpcAuthorization.ts | 1 + .../src/environment/ServerEnvironment.ts | 1 + .../src/observability/RpcInstrumentation.ts | 3 + .../src/orchestration-v2/runtimeLayer.test.ts | 109 +++++++ .../src/orchestration-v2/runtimeLayer.ts | 3 + .../src/project/AgentSessionImporter.ts | 19 +- apps/server/src/project/ThreadProjectMove.ts | 295 +++++++++++++++++- apps/server/src/ws.ts | 15 +- apps/web/src/components/CommandPalette.tsx | 46 ++- apps/web/src/components/Sidebar.tsx | 13 + .../src/components/threadActionMenu.logic.ts | 36 +++ apps/web/src/contextMenuFallback.ts | 6 + .../web/src/hooks/useThreadActionMenu.test.ts | 1 + apps/web/src/hooks/useThreadActionMenu.ts | 13 + apps/web/src/hooks/useThreadActions.ts | 89 +++++- docs/user/thread-sidebar.md | 12 + packages/client-runtime/package.json | 4 + packages/client-runtime/src/state/models.ts | 20 +- .../src/state/projectCommands.ts | 18 ++ .../src/state/threadMachineMove.test.ts | 105 +++++++ .../src/state/threadMachineMove.ts | 139 +++++++++ .../contracts/src/clientRpcPermissions.ts | 2 + packages/contracts/src/environment.ts | 1 + packages/contracts/src/project.ts | 54 ++++ packages/contracts/src/rpc.ts | 28 ++ packages/shared/src/threadMove.ts | 26 ++ 29 files changed, 1144 insertions(+), 36 deletions(-) create mode 100644 apps/mobile/src/features/threads/moveThreadToMachine.ts create mode 100644 packages/client-runtime/src/state/threadMachineMove.test.ts create mode 100644 packages/client-runtime/src/state/threadMachineMove.ts diff --git a/apps/mobile/src/features/threads/moveThreadToMachine.ts b/apps/mobile/src/features/threads/moveThreadToMachine.ts new file mode 100644 index 0000000000000..255e99f744b48 --- /dev/null +++ b/apps/mobile/src/features/threads/moveThreadToMachine.ts @@ -0,0 +1,82 @@ +import type { EnvironmentProject } from "@t3tools/client-runtime/state/models"; +import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell"; +import { + moveThreadToMachine as runThreadMachineMove, + threadMachineMoveTargets, + type ThreadMachineMoveTarget, +} from "@t3tools/client-runtime/state/threadMachineMove"; +import { AuthOrchestrationOperateScope, type EnvironmentId } from "@t3tools/contracts"; +import { threadMachineMoveNotice } from "@t3tools/shared/threadMove"; +import * as Haptics from "expo-haptics"; + +import * as Dialog from "../../components/ui/Dialog"; +import { appAtomRegistry } from "../../state/atom-registry"; +import { connectedEnvironmentIdsAtom, environmentPresentations } from "../../state/presentation"; +import { projectEnvironment } from "../../state/projects"; +import { environmentServerConfigsAtom } from "../../state/server"; +import { readEnvironmentScope } from "../../state/session"; + +const machineLabel = (environmentId: EnvironmentId) => + appAtomRegistry.get(environmentPresentations.presentationsAtom).get(environmentId)?.entry.target + .label; + +/** Other connected machines this thread can move to, each with its projects. */ +export function readThreadMachineMoveTargets( + thread: EnvironmentThreadShell, + projects: ReadonlyArray, +): ReadonlyArray { + return threadMachineMoveTargets({ + sourceEnvironmentId: thread.environmentId, + connectedEnvironmentIds: appAtomRegistry.get(connectedEnvironmentIdsAtom), + serverConfigs: appAtomRegistry.get(environmentServerConfigsAtom), + projects, + labelOf: machineLabel, + canOperate: (environmentId) => + readEnvironmentScope(environmentId, AuthOrchestrationOperateScope), + }); +} + +export async function moveThreadToMachine( + thread: EnvironmentThreadShell, + machine: ThreadMachineMoveTarget, + project: EnvironmentProject, +): Promise { + const fromMachine = machineLabel(thread.environmentId) ?? "this machine"; + if (!readEnvironmentScope(thread.environmentId, AuthOrchestrationOperateScope)) { + Dialog.alert("Could not move thread", "This connection cannot change threads."); + return; + } + const outcome = await runThreadMachineMove({ + registry: appAtomRegistry, + commands: projectEnvironment, + source: { environmentId: thread.environmentId, threadId: thread.id }, + sourceLabel: fromMachine, + target: { environmentId: machine.environmentId, projectId: project.id }, + targetLabel: `${project.title} on ${machine.label}`, + confirm: ({ leftBehind }) => + new Promise((resolve) => + Dialog.confirm({ + title: `Move "${thread.title}" to ${machine.label}?`, + message: threadMachineMoveNotice({ + fromMachine, + toMachine: machine.label, + projectTitle: project.title, + leftBehind, + }), + confirmText: "Move", + onCancel: () => resolve(false), + onConfirm: () => { + void Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light); + resolve(true); + }, + }), + ), + }); + if (outcome._tag === "Failed") Dialog.alert("Could not move thread", outcome.message); + if (outcome._tag === "Moved" && outcome.archiveError !== null) { + Dialog.alert( + `Moved, but the thread is still active on ${fromMachine}`, + `${outcome.archiveError} Archive it there so you don't continue both.`, + ); + } +} diff --git a/apps/mobile/src/features/threads/thread-list-v2-items.tsx b/apps/mobile/src/features/threads/thread-list-v2-items.tsx index 5d1ecd4ed8b14..b282e61007971 100644 --- a/apps/mobile/src/features/threads/thread-list-v2-items.tsx +++ b/apps/mobile/src/features/threads/thread-list-v2-items.tsx @@ -74,6 +74,7 @@ import { ThreadSwipeable } from "../home/thread-swipe-actions"; import { buildThreadTitleRegenerationMenuItems } from "./thread-title-regeneration-menu"; import { canTurnThreadIntoProject, turnThreadIntoProject } from "./turnThreadIntoProject"; import { moveThreadToProject, readThreadMoveTargets } from "./moveThreadToProject"; +import { moveThreadToMachine, readThreadMachineMoveTargets } from "./moveThreadToMachine"; import { threadCanArchive } from "../home/threadArchive"; import { THREAD_LIST_V2_SETTLED_PAGE_COUNT, @@ -931,6 +932,10 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: { const canTurnIntoProject = canTurnThreadIntoProject(thread); const projects = useProjects(); const moveTargets = useMemo(() => readThreadMoveTargets(thread, projects), [thread, projects]); + const machineMoveTargets = useMemo( + () => readThreadMachineMoveTargets(thread, projects), + [thread, projects], + ); const titleMenuItems = useMemo( () => [ { id: "rename", title: "Rename", image: "square.and.pencil" }, @@ -962,9 +967,27 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: { } satisfies MenuAction, ] : []), + // One level: Android menus cannot nest a machine's projects inside a submenu. + ...(machineMoveTargets.length > 0 + ? [ + { + id: "move-to-machine", + title: "Move to machine", + image: "server.rack", + attributes: { disabled: !threadCanArchive(thread.runtime) }, + subactions: machineMoveTargets.flatMap((machine, machineIndex) => + machine.projects.map((project, projectIndex) => ({ + id: `move-to-machine:${machineIndex}:${projectIndex}`, + title: `${project.title} · ${machine.label}`, + })), + ), + } satisfies MenuAction, + ] + : []), ], [ canTurnIntoProject, + machineMoveTargets, moveTargets, props.titleRegenerationSupported, thread.runtime, @@ -1072,6 +1095,12 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: { if (nativeEvent.event === "rename") handleRename(); if (nativeEvent.event === "regenerate-title") handleRegenerateTitle(); if (nativeEvent.event === "turn-into-project") void turnThreadIntoProject(thread); + const machinePick = /^move-to-machine:(\d+):(\d+)$/.exec(nativeEvent.event); + if (machinePick) { + const machine = machineMoveTargets[Number(machinePick[1])]; + const project = machine?.projects[Number(machinePick[2])]; + if (machine && project) void moveThreadToMachine(thread, machine, project); + } if (nativeEvent.event.startsWith("move-to-project:")) { const projectId = nativeEvent.event.slice("move-to-project:".length); const project = moveTargets.find((candidate) => candidate.id === projectId); @@ -1129,6 +1158,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: { snoozePresets, props.snoozePresets, moveTargets, + machineMoveTargets, ], ); const primaryAction = useMemo(() => { diff --git a/apps/server/src/auth/RpcAuthorization.test.ts b/apps/server/src/auth/RpcAuthorization.test.ts index 37abf3d1593d3..d315bf334ce28 100644 --- a/apps/server/src/auth/RpcAuthorization.test.ts +++ b/apps/server/src/auth/RpcAuthorization.test.ts @@ -75,6 +75,15 @@ describe("RPC authorization scopes", () => { } }); + it("lets thread readers export a conversation but only operators move one in or archive it", () => { + expect(requiredScopeForRpcMethod(WS_METHODS.projectsExportThread)).toBe( + AuthOrchestrationReadScope, + ); + for (const method of [WS_METHODS.projectsImportThread, WS_METHODS.projectsFinishThreadMove]) { + expect(requiredScopeForRpcMethod(method)).toBe(AuthOrchestrationOperateScope); + } + }); + it("rejects unknown RPC method names", () => { for (const method of ["server.notRegistered", "toString", "constructor"]) { expect(() => requiredScopeForRpcMethod(method)).toThrow( diff --git a/apps/server/src/auth/RpcAuthorization.ts b/apps/server/src/auth/RpcAuthorization.ts index 071e5733687d4..4f28b0a3b3826 100644 --- a/apps/server/src/auth/RpcAuthorization.ts +++ b/apps/server/src/auth/RpcAuthorization.ts @@ -157,6 +157,7 @@ export const RPC_REQUIRED_SCOPES = { [WS_METHODS.projectsWriteFile]: AuthFilesystemWriteScope, [WS_METHODS.projectsEnsureScratch]: AuthOrchestrationOperateScope, [WS_METHODS.projectsCreateNew]: AuthOrchestrationOperateScope, + [WS_METHODS.projectsExportThread]: AuthOrchestrationReadScope, [WS_METHODS.shellOpenInEditor]: AuthOrchestrationOperateScope, [WS_METHODS.filesystemBrowse]: AuthFilesystemReadScope, [WS_METHODS.filesystemGetMetadata]: AuthFilesystemReadScope, diff --git a/apps/server/src/environment/ServerEnvironment.ts b/apps/server/src/environment/ServerEnvironment.ts index bffbe574983d2..4e44ef1dcace3 100644 --- a/apps/server/src/environment/ServerEnvironment.ts +++ b/apps/server/src/environment/ServerEnvironment.ts @@ -261,6 +261,7 @@ export const make = Effect.gen(function* () { threadAutoSettleOptOut: true, threadProjectFromScratch: true, threadMoveToProject: true, + threadMoveToMachine: true, threadTitleRegeneration: true, commandOutputStreaming: true, threadVisitedTracking: true, diff --git a/apps/server/src/observability/RpcInstrumentation.ts b/apps/server/src/observability/RpcInstrumentation.ts index ace9673ac182c..83b2366fbaa4a 100644 --- a/apps/server/src/observability/RpcInstrumentation.ts +++ b/apps/server/src/observability/RpcInstrumentation.ts @@ -166,6 +166,9 @@ const RPC_AGGREGATES = { [WS_METHODS.projectsCreateNew]: "orchestration", [WS_METHODS.projectsCreateFromThread]: "orchestration", [WS_METHODS.projectsMoveThread]: "orchestration", + [WS_METHODS.projectsExportThread]: "orchestration", + [WS_METHODS.projectsImportThread]: "orchestration", + [WS_METHODS.projectsFinishThreadMove]: "orchestration", [WS_METHODS.shellOpenInEditor]: "workspace", [WS_METHODS.filesystemBrowse]: "workspace", [WS_METHODS.filesystemGetMetadata]: "workspace", diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index b0e84bfe99f33..ec22d5797e744 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -88,6 +88,8 @@ import * as ThreadManagementService from "./ThreadManagementService.ts"; import * as ManagedProjectFolders from "../project/ManagedProjectFolders.ts"; import * as ScratchThreadPromotion from "../project/ScratchThreadPromotion.ts"; import * as ThreadProjectMove from "../project/ThreadProjectMove.ts"; +import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; +import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts"; import * as ScheduledTaskService from "../scheduledTasks/ScheduledTaskService.ts"; import * as ManagedPolicy from "../policy/ManagedPolicy.ts"; import * as Scheduler from "../scheduling/Scheduler.ts"; @@ -10202,6 +10204,14 @@ const layerThreadProjectMoveTest = ThreadProjectMove.layer.pipe( Layer.mock(GitWorkflow.GitWorkflowService)({ currentBranch: (cwd) => Effect.succeed(`branch-of:${cwd}`), }), + Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({ + list: () => Effect.succeed([modelSelection.instanceId]), + }), + ServerSettings.layerTest( + { defaultModelSelection: modelSelection }, + { organization: "Org", lockedSettings: [], limits: { maxRuntimeMode: "auto" } }, + ), + IdAllocator.layer, NodeCrypto.layer, ), ), @@ -10338,6 +10348,105 @@ it.layer(layerThreadProjectMoveTest)("moving a thread to another project", (it) assert.equal(raced?.projectId, otherId); }), ); + + it.effect("moves a conversation to another machine's project and archives the source after", () => + Effect.gen(function* () { + const service = yield* ThreadProjectMove.ThreadProjectMove; + const projects = yield* ProjectService.ProjectService; + const orchestrator = yield* Orchestrator.OrchestratorV2; + const threads = yield* ThreadManagementService.ThreadManagementService; + const targetId = ProjectId.make("machine-move-target"); + yield* projects.create({ + commandId: CommandId.make("machine-move-target-create"), + projectId: targetId, + title: "Target", + workspaceRoot: "/tmp/machine-move-target", + }); + const bundle = { + title: "Port the parser", + modelSelection: { instanceId: ProviderInstanceId.make("elsewhere-only"), model: "m" }, + runtimeMode: "full-access", + interactionMode: "plan", + createdAt: "2026-01-01T00:00:00.000Z", + messages: [ + { role: "user", text: "Port the parser.", createdAt: "2026-01-01T00:00:01.000Z" }, + { role: "assistant", text: "Ported.", createdAt: "2026-01-01T00:00:02.000Z" }, + ], + } as const; + + const { threadId } = yield* service.importThread({ + projectId: targetId, + bundle, + movedFrom: "Laptop", + }); + const imported = (yield* orchestrator.getThreadRecords(threadId, [])).thread; + assert.equal(imported.projectId, targetId); + assert.equal(imported.branch, "branch-of:/tmp/machine-move-target"); + assert.isNull(imported.activeProviderThreadId); + // This machine has no such provider instance, and the policy caps the runtime mode. + assert.equal(imported.modelSelection.instanceId, "codex"); + assert.equal(imported.runtimeMode, "auto"); + assert.equal(imported.interactionMode, "plan"); + + // Moving it back carries the same conversation, and names what stays behind. + const exported = yield* service.exportThread(threadId); + assert.deepEqual(exported.bundle.messages, bundle.messages); + assert.equal(exported.bundle.title, bundle.title); + assert.deepEqual(exported.leftBehind, { + diffs: false, + worktree: false, + attachments: 0, + scheduledTasks: 0, + }); + const { projection } = yield* threads.getThreadSnapshot(threadId); + assert.include( + projection.visibleTurnItems.map(({ item }) => + item.type === "system_notice" ? item.message : "", + ), + "Moved from Laptop. Its files and diffs stayed there.", + ); + + yield* service.finishMove({ threadId, movedTo: "VPS" }); + const finished = yield* threads.getThreadSnapshot(threadId); + assert.isNotNull(finished.projection.thread.archivedAt); + assert.include( + finished.projection.visibleTurnItems.map(({ item }) => + item.type === "system_notice" ? item.message : "", + ), + "Moved to VPS. Messages sent here stay separate from that thread.", + ); + + const busyId = ThreadId.make("machine-move-busy"); + yield* orchestrator.dispatch({ + type: "thread.create", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make("machine-move-busy-create"), + threadId: busyId, + projectId: targetId, + title: "Busy", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + }); + yield* orchestrator.dispatch({ + type: "message.dispatch", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make("machine-move-busy-message"), + threadId: busyId, + messageId: MessageId.make("machine-move-busy-message"), + text: "Keep this run active.", + attachments: [], + modelSelection, + dispatchMode: { type: "start_immediately" }, + }); + const busy = yield* service.exportThread(busyId).pipe(Effect.flip); + assert.equal(busy.message, "The thread still has work in progress. Finish or stop it first."); + }), + ); }); it.layer(layerSharedApplicationDataPlaneTest)("snooze projection", (it) => { diff --git a/apps/server/src/orchestration-v2/runtimeLayer.ts b/apps/server/src/orchestration-v2/runtimeLayer.ts index 261ba9d79a0fa..88705c2318fad 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.ts @@ -321,6 +321,9 @@ const layerThreadProjectMoveProvided = ThreadProjectMove.layer.pipe( layerManagedProjectFoldersProvided, layerThreadManagementProvided, layerScheduledTaskProvided, + layerEventSink, + IdAllocator.layer, + ProviderAdapterRegistry.layerFromProviderInstanceRegistry, ).pipe(Layer.provideMerge(layerProjectService)), ), ); diff --git a/apps/server/src/project/AgentSessionImporter.ts b/apps/server/src/project/AgentSessionImporter.ts index 0ebd6688a28be..6356f79a6a5ca 100644 --- a/apps/server/src/project/AgentSessionImporter.ts +++ b/apps/server/src/project/AgentSessionImporter.ts @@ -109,7 +109,9 @@ type HistoryMessage = Omit - messageEvents({ threadId, index, message }), + messageEvents({ prefix: IMPORT_EVENT_PREFIX, threadId, index, message }), ), { id: EventId.make(`${IMPORT_EVENT_PREFIX}:provider-thread:${providerThreadId}`), @@ -529,7 +529,12 @@ const make = Effect.gen(function* () { yield* eventSink.write({ events: [ ...messages.flatMap((message, index) => - messageEvents({ threadId: input.threadId, index, message }), + messageEvents({ + prefix: IMPORT_EVENT_PREFIX, + threadId: input.threadId, + index, + message, + }), ), { id: EventId.make(`${IMPORT_EVENT_PREFIX}:thread:${input.threadId}:native-history`), diff --git a/apps/server/src/project/ThreadProjectMove.ts b/apps/server/src/project/ThreadProjectMove.ts index 78a69c99b3bd0..8576f7d56bfb2 100644 --- a/apps/server/src/project/ThreadProjectMove.ts +++ b/apps/server/src/project/ThreadProjectMove.ts @@ -1,19 +1,42 @@ -import { CommandId, type ProjectId, type ThreadId } from "@t3tools/contracts"; +import { + CommandId, + EventId, + isRuntimeModeAbove, + type OrchestrationV2AppThread, + type OrchestrationV2DomainEvent, + type ProjectExportThreadResult, + type ProjectFinishThreadMoveInput, + type ProjectId, + type ProjectImportThreadInput, + type ProjectImportThreadResult, + type ThreadId, + TurnItemId, +} from "@t3tools/contracts"; +import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; +import { resolveProjectSettings } from "@t3tools/shared/projectSettings"; import { threadMoveNotice } from "@t3tools/shared/threadMove"; import * as Context from "effect/Context"; import * as SecureRandom from "effect/crypto/SecureRandom"; +import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; import * as GitWorkflowService from "../git/GitWorkflowService.ts"; +import * as EventSink from "../orchestration-v2/EventSink.ts"; +import { threadHasUnfinishedWork } from "../orchestration-v2/Orchestrator.ts"; +import * as ProviderAdapterRegistry from "../orchestration-v2/ProviderAdapterRegistry.ts"; import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts"; import { userFacingDispatchErrorMessage } from "../orchestration-v2/UserFacingErrors.ts"; import * as ScheduledTaskService from "../scheduledTasks/ScheduledTaskService.ts"; +import * as ServerSettings from "../serverSettings.ts"; +import { messageEvents } from "./AgentSessionImporter.ts"; import * as ManagedProjectFolders from "./ManagedProjectFolders.ts"; import * as ProjectService from "./ProjectService.ts"; +const MOVE_EVENT_PREFIX = "thread-machine-move"; + export class ThreadProjectMoveError extends Schema.TaggedError()( "ThreadProjectMoveError", { @@ -37,6 +60,18 @@ export class ThreadProjectMove extends Context.Service< readonly threadId: ThreadId; readonly projectId: ProjectId; }) => Effect.Effect<{ readonly notice: string }, ThreadProjectMoveError>; + /** An idle thread's conversation, for moving it to another environment. Changes nothing. */ + readonly exportThread: ( + threadId: ThreadId, + ) => Effect.Effect; + /** A new thread in `projectId` holding the bundle's history; its first message starts a fresh session. */ + readonly importThread: ( + input: ProjectImportThreadInput, + ) => Effect.Effect; + /** Notes where the conversation went and archives the thread, once the import succeeded. */ + readonly finishMove: ( + input: ProjectFinishThreadMoveInput, + ) => Effect.Effect; } >()("t3/project/ThreadProjectMove") {} @@ -46,25 +81,34 @@ const make = Effect.gen(function* () { const threads = yield* ThreadManagementService.ThreadManagementService; const scheduledTasks = yield* ScheduledTaskService.ScheduledTaskService; const git = yield* GitWorkflowService.GitWorkflowService; + const eventSink = yield* EventSink.EventSinkV2; + const ids = yield* IdAllocator.IdAllocatorV2; + const registry = yield* ProviderAdapterRegistry.ProviderAdapterRegistryV2; + const settingsService = yield* ServerSettings.ServerSettingsService; const randomId = (yield* SecureRandom.SecureRandom).uuidV4(); const fail = (reason: string) => (cause: unknown) => new ThreadProjectMoveError({ reason, cause }); + const readTarget = Effect.fn("ThreadProjectMove.readTarget")(function* (projectId: ProjectId) { + const target = yield* projects + .getById(projectId) + .pipe(Effect.mapError(fail("Could not read the project."))); + if (Option.isNone(target) || target.value.deletedAt !== null) { + return yield* new ThreadProjectMoveError({ reason: "Project not found." }); + } + // No project holds one folder per thread, so its root is no place to work. + if (yield* managedFolders.isScratchProject(projectId)) { + return yield* new ThreadProjectMoveError({ + reason: "A thread cannot move into No project.", + }); + } + return target.value; + }); + const move: ThreadProjectMove["Service"]["move"] = Effect.fn("ThreadProjectMove.move")( function* (input) { - const target = yield* projects - .getById(input.projectId) - .pipe(Effect.mapError(fail("Could not read the project."))); - if (Option.isNone(target) || target.value.deletedAt !== null) { - return yield* new ThreadProjectMoveError({ reason: "Project not found." }); - } - // No project holds one folder per thread, so its root is no place to work. - if (yield* managedFolders.isScratchProject(input.projectId)) { - return yield* new ThreadProjectMoveError({ - reason: "A thread cannot move into No project.", - }); - } + const target = yield* readTarget(input.projectId); const thread = yield* threads.getThreadShell(input.threadId).pipe( Effect.mapError(fail("Could not read the thread.")), Effect.filterOrFail( @@ -74,7 +118,7 @@ const make = Effect.gen(function* () { ); if (thread.projectId !== input.projectId) { const branch = yield* git - .currentBranch(target.value.workspaceRoot) + .currentBranch(target.workspaceRoot) .pipe(Effect.orElseSucceed(() => null)); yield* threads .dispatch({ @@ -110,14 +154,233 @@ const make = Effect.gen(function* () { } return { notice: threadMoveNotice({ - projectTitle: target.value.title, + projectTitle: target.title, fromWorktree: thread.worktreePath !== null, }), }; }, ); - return ThreadProjectMove.of({ move }); + const exportThread: ThreadProjectMove["Service"]["exportThread"] = Effect.fn( + "ThreadProjectMove.exportThread", + )(function* (threadId) { + const records = yield* threads + .getThreadRecords(threadId, ["runs", "runtimeRequests"]) + .pipe(Effect.mapError(fail("Could not read the thread."))); + if (threadHasUnfinishedWork(records)) { + return yield* new ThreadProjectMoveError({ + reason: "The thread still has work in progress. Finish or stop it first.", + }); + } + const { projection } = yield* threads + .getThreadSnapshot(threadId) + .pipe(Effect.mapError(fail("Could not read the thread."))); + const thread = projection.thread; + let attachments = 0; + const messages = projection.visibleTurnItems.flatMap(({ item }) => { + if (item.type === "user_message") attachments += item.attachments.length; + if (item.type !== "user_message" && item.type !== "assistant_message") return []; + if (item.text.trim() === "") return []; + const createdAt = DateTime.formatIso(item.startedAt ?? item.updatedAt); + return [ + { role: item.type === "user_message" ? "user" : "assistant", text: item.text, createdAt }, + ] as const; + }); + if (messages.length === 0) { + return yield* new ThreadProjectMoveError({ + reason: "The thread has no conversation to move.", + }); + } + const tasks = yield* scheduledTasks + .list() + .pipe(Effect.mapError(fail("Could not read the thread's scheduled tasks."))); + return { + bundle: { + title: thread.title.trim() === "" ? "Untitled thread" : thread.title, + modelSelection: thread.modelSelection, + runtimeMode: thread.runtimeMode, + interactionMode: thread.interactionMode, + createdAt: DateTime.formatIso(thread.createdAt), + messages, + }, + leftBehind: { + diffs: projection.runs.length > 0, + worktree: thread.worktreePath !== null, + attachments, + scheduledTasks: tasks.tasks.filter((task) => task.threadId === threadId).length, + }, + }; + }); + + const importThread: ThreadProjectMove["Service"]["importThread"] = Effect.fn( + "ThreadProjectMove.importThread", + )(function* (input) { + const project = yield* readTarget(input.projectId); + const settings = yield* settingsService.getSettings.pipe( + Effect.mapError(fail("Could not read this machine's settings.")), + ); + const projectSettings = resolveProjectSettings(settings, project.id, project).settings; + // Provider instances are per machine; one this machine lacks falls back to the project default. + const instanceId = input.bundle.modelSelection.instanceId; + const usable = + (yield* registry.list()).includes(instanceId) && + (yield* threads.isProviderInstanceEnabledForProject({ projectId: project.id, instanceId })); + const modelSelection = usable + ? input.bundle.modelSelection + : (projectSettings.defaultModelSelection ?? input.bundle.modelSelection); + const ceiling = settingsService.managedPolicy?.limits?.maxRuntimeMode; + const runtimeMode = + ceiling !== undefined && isRuntimeModeAbove(input.bundle.runtimeMode, ceiling) + ? ceiling + : input.bundle.runtimeMode; + const branch = yield* git + .currentBranch(project.workspaceRoot) + .pipe(Effect.orElseSucceed(() => null)); + const threadId = yield* ids.allocate + .thread({ projectId: project.id }) + .pipe(Effect.mapError(fail("Could not create the thread."))); + const now = yield* DateTime.now; + const createdAt = Option.getOrElse(DateTime.make(input.bundle.createdAt), () => now); + const thread: OrchestrationV2AppThread = { + createdBy: "user", + creationSource: "server", + id: threadId, + projectId: project.id, + title: input.bundle.title, + providerInstanceId: modelSelection.instanceId, + modelSelection, + runtimeMode, + interactionMode: input.bundle.interactionMode, + branch, + worktreePath: null, + linkedPullRequest: null, + branchPullRequest: null, + activeProviderThreadId: null, + // Run-less history, which the first turn hands to a fresh provider session. + historyOrigin: "v1_import", + lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId }, + forkedFrom: null, + createdAt, + updatedAt: now, + archivedAt: null, + settledOverride: null, + settledAt: null, + unsettledAt: null, + snoozedUntil: null, + snoozedAt: null, + pinnedAt: null, + pinOrderKey: null, + activeOrderKey: null, + lastVisitedAt: null, + deletedAt: null, + }; + const noticeId = TurnItemId.make(`${MOVE_EVENT_PREFIX}:moved-from:${threadId}`); + const events: ReadonlyArray = [ + { + id: EventId.make(`${MOVE_EVENT_PREFIX}:thread:${threadId}:created`), + type: "thread.created", + threadId, + providerInstanceId: modelSelection.instanceId, + occurredAt: now, + payload: thread, + }, + ...input.bundle.messages.flatMap((message, index) => + messageEvents({ prefix: MOVE_EVENT_PREFIX, threadId, index, message }), + ), + { + id: EventId.make(noticeId), + type: "turn-item.updated", + threadId, + occurredAt: now, + payload: { + ...movedNoticeFields(noticeId, threadId, now), + runId: null, + nodeId: null, + providerThreadId: null, + ordinal: input.bundle.messages.length + 1, + message: `Moved from ${input.movedFrom}. Its files and diffs stayed there.`, + }, + }, + ]; + yield* eventSink.write({ events }).pipe(Effect.mapError(fail("Could not create the thread."))); + return { threadId }; + }); + + const finishMove: ThreadProjectMove["Service"]["finishMove"] = Effect.fn( + "ThreadProjectMove.finishMove", + )(function* (input) { + const { thread, runs } = yield* threads + .getThreadRecords(input.threadId, ["runs"]) + .pipe(Effect.mapError(fail("Could not read the thread."))); + const lastRun = runs.reduce<(typeof runs)[number] | undefined>( + (latest, run) => (latest === undefined || run.ordinal > latest.ordinal ? run : latest), + undefined, + ); + const now = yield* DateTime.now; + const noticeId = + lastRun === undefined + ? TurnItemId.make(`${MOVE_EVENT_PREFIX}:moved-to:${input.threadId}`) + : ids.derive.runSignalTurnItem({ runId: lastRun.id, signal: "moved-to-machine" }); + yield* eventSink + .write({ + events: [ + { + id: yield* ids.allocate + .event({ threadId: input.threadId }) + .pipe(Effect.mapError(fail("Could not note the move."))), + type: "turn-item.updated", + threadId: input.threadId, + ...(lastRun === undefined ? {} : { runId: lastRun.id }), + occurredAt: now, + payload: { + ...movedNoticeFields(noticeId, input.threadId, now), + runId: lastRun?.id ?? null, + nodeId: lastRun?.rootNodeId ?? null, + providerThreadId: lastRun?.providerThreadId ?? null, + // EventSink allocates the real position, after the run's existing items. + ordinal: 0, + message: `Moved to ${input.movedTo}. Messages sent here stay separate from that thread.`, + }, + }, + ], + }) + .pipe(Effect.mapError(fail("Could not note the move."))); + if (thread.archivedAt !== null) return; + yield* threads + .dispatch({ + type: "thread.archive", + commandId: CommandId.make(`thread-machine-move:${yield* randomId}`), + threadId: input.threadId, + }) + .pipe( + Effect.mapError( + (cause) => + new ThreadProjectMoveError({ + reason: userFacingDispatchErrorMessage(cause) ?? "Could not archive the thread.", + cause, + }), + ), + ); + }); + + return ThreadProjectMove.of({ move, exportThread, importThread, finishMove }); }); +function movedNoticeFields(id: TurnItemId, threadId: ThreadId, now: DateTime.Utc) { + return { + id, + threadId, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + status: "completed", + title: null, + startedAt: now, + completedAt: now, + updatedAt: now, + type: "system_notice", + level: "info", + } as const; +} + export const layer = Layer.effect(ThreadProjectMove, make); diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 400f52f6cb45e..381905bb677c6 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -1445,6 +1445,8 @@ export const layerWsRpc = ( const managedFolders = yield* ManagedProjectFolders.ManagedProjectFolders; const scratchThreadPromotion = yield* ScratchThreadPromotion.ScratchThreadPromotion; const threadProjectMove = yield* ThreadProjectMove.ThreadProjectMove; + const threadMoveError = (cause: ThreadProjectMove.ThreadProjectMoveError) => + new OrchestrationDispatchCommandError({ message: cause.message, cause }); const eventLoopMonitor = yield* EventLoopMonitor.EventLoopMonitor; const threadSearch = yield* ThreadSearch.ThreadSearch; @@ -2908,12 +2910,13 @@ export const layerWsRpc = ( ), ), [WS_METHODS.projectsMoveThread]: (input) => - threadProjectMove.move(input).pipe( - Effect.asVoid, - Effect.mapError( - (cause) => new OrchestrationDispatchCommandError({ message: cause.message, cause }), - ), - ), + threadProjectMove.move(input).pipe(Effect.asVoid, Effect.mapError(threadMoveError)), + [WS_METHODS.projectsExportThread]: (input) => + threadProjectMove.exportThread(input.threadId).pipe(Effect.mapError(threadMoveError)), + [WS_METHODS.projectsImportThread]: (input) => + threadProjectMove.importThread(input).pipe(Effect.mapError(threadMoveError)), + [WS_METHODS.projectsFinishThreadMove]: (input) => + threadProjectMove.finishMove(input).pipe(Effect.mapError(threadMoveError)), [WS_METHODS.projectCloneCancel]: (input) => projectCloneTracker.cancel(input.projectId).pipe(Effect.map((applied) => ({ applied }))), [WS_METHODS.projectCloneRetry]: (input) => diff --git a/apps/web/src/components/CommandPalette.tsx b/apps/web/src/components/CommandPalette.tsx index e0a48722ab389..821f81e3caa20 100644 --- a/apps/web/src/components/CommandPalette.tsx +++ b/apps/web/src/components/CommandPalette.tsx @@ -67,6 +67,7 @@ import { FolderGit2Icon, FolderIcon, FolderInputIcon, + ServerIcon, FolderPlusIcon, KeyboardIcon, MessageSquareDashedIcon, @@ -127,7 +128,11 @@ import { readEnvironmentScope, useEnvironmentScope } from "~/state/session"; import { sourceControlEnvironment } from "../state/sourceControl"; import { useAtomCommand } from "../state/use-atom-command"; import { useRestartAgentSession } from "../hooks/useRestartAgentSession"; -import { confirmThreadMove } from "../hooks/useThreadActions"; +import { + confirmThreadMove, + moveThreadToMachineAndOpen, + readThreadMachineMoveTargets, +} from "../hooks/useThreadActions"; import { useOrchestrationCommand } from "../state/use-orchestration-command"; import { useAtomQueryRunner } from "../state/use-atom-query-runner"; import { useScratchProject } from "../hooks/useScratchProject"; @@ -1553,6 +1558,45 @@ function OpenCommandPaletteDialog(props: { }); } + const machineMoveTargets = + activeThread !== null + ? readThreadMachineMoveTargets(scopeThreadRef(activeThread.environmentId, activeThread.id)) + : []; + if (activeThread !== null && machineMoveTargets.length > 0) { + const threadRef = scopeThreadRef(activeThread.environmentId, activeThread.id); + actionItems.push({ + kind: "submenu", + value: "action:move-thread-to-machine", + searchTerms: ["move", "machine", "environment", "server", "remote", "computer"], + title: "Move thread to machine...", + icon: , + addonIcon: , + disabled: !threadRuntimeCanArchive(activeThread.runtime), + groups: machineMoveTargets.map((machine) => ({ + value: `move-thread-to-machine:${machine.environmentId}`, + label: machine.label, + items: machine.projects.map((project) => ({ + kind: "action" as const, + value: `move-thread-to-machine:${machine.environmentId}:${project.id}`, + searchTerms: [machine.label, project.title, project.workspaceRoot], + title: project.title, + description: project.workspaceRoot, + icon: , + run: () => + moveThreadToMachineAndOpen( + threadRef, + { environmentId: machine.environmentId, projectId: project.id }, + (target) => + navigate({ + to: "/$environmentId/$threadId", + params: buildThreadRouteParams(target), + }), + ), + })), + })), + }); + } + if (activeThread !== null) { const thread = activeThread; actionItems.push({ diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 5886aa1b7f750..df7de46709977 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -121,6 +121,7 @@ import { import { canTurnThreadIntoProject, confirmThreadMove, + readThreadMachineMoveTargets, readThreadMoveTargets, useAcknowledgeThreadWoke, useThreadActions, @@ -174,6 +175,7 @@ import { ProjectRowActions } from "./ProjectComboboxRow"; import { buildDraftActionMenuItems, buildThreadActionMenuItems, + parseMachineMovePick, threadActionRequiresOperate, } from "./threadActionMenu.logic"; import { @@ -933,6 +935,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve setThreadAutoSettle, turnThreadIntoProject, moveThreadToProject, + moveThreadToMachine, reorderPinnedThread, reorderActiveThread, markThreadUnread, @@ -2612,6 +2615,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve serverConfigs.get(thread.environmentId)?.environment.capabilities .threadAutoSettleOptOut === true; const isRegeneratingTitle = thread.titleRegeneration != null; + const machineMoveTargets = readThreadMachineMoveTargets(threadRef); const isSettled = settledThreadKeysRef.current.has(threadKey); const isSnoozed = snoozedThreadKeysRef.current.has(threadKey); const isPinned = thread.pinnedAt != null; @@ -2656,6 +2660,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve ), canTurnIntoProject: canTurnThreadIntoProject(threadRef), moveTargets: readThreadMoveTargets(threadRef), + machineMoveTargets, supports: { settlement: configLoaded, autoSettleOptOut: supportsAutoSettleOptOut, @@ -2683,6 +2688,14 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve if (preset) attemptSnooze(threadRef, preset); return; } + const machinePick = parseMachineMovePick(clicked.value, machineMoveTargets); + if (machinePick) { + await moveThreadToMachine(threadRef, { + environmentId: machinePick.machine.environmentId, + projectId: machinePick.project.id, + }); + return; + } if (clicked.value.startsWith("move-to-project:")) { const projectId = ProjectId.make(clicked.value.slice("move-to-project:".length)); if (!(await confirmThreadMove(threadRef, projectId))) return; diff --git a/apps/web/src/components/threadActionMenu.logic.ts b/apps/web/src/components/threadActionMenu.logic.ts index e9f6ba012e554..8999d1830bb2c 100644 --- a/apps/web/src/components/threadActionMenu.logic.ts +++ b/apps/web/src/components/threadActionMenu.logic.ts @@ -8,6 +8,8 @@ export type ThreadActionMenuId = | "turn-into-project" | "move-to-project" | `move-to-project:${string}` + | "move-to-machine" + | `move-to-machine:${string}` | "project-settings" | "pin" | "unpin" @@ -98,6 +100,11 @@ export interface ThreadActionMenuState { /** A No project thread with its own folder, on a server that can promote it. */ readonly canTurnIntoProject?: boolean; readonly moveTargets?: ReadonlyArray<{ readonly id: string; readonly title: string }>; + /** Picked by `move-to-machine::`. */ + readonly machineMoveTargets?: ReadonlyArray<{ + readonly label: string; + readonly projects: ReadonlyArray<{ readonly title: string }>; + }>; } /** Local navigation, read markers, and copying remain available to read-only clients. */ @@ -116,6 +123,17 @@ export function threadActionRequiresOperate(action: ThreadActionMenuId): boolean ].includes(action); } +/** The machine and project a `move-to-machine::` pick names, by position. */ +export function parseMachineMovePick }>( + id: string, + targets: ReadonlyArray, +): { readonly machine: M; readonly project: M["projects"][number] } | null { + const match = /^move-to-machine:(\d+):(\d+)$/.exec(id); + const machine = match ? targets[Number(match[1])] : undefined; + const project = match ? machine?.projects[Number(match[2])] : undefined; + return machine && project !== undefined ? { machine, project } : null; +} + export function buildThreadActionMenuItems( state: ThreadActionMenuState, ): ReadonlyArray> { @@ -220,6 +238,24 @@ export function buildThreadActionMenuItems( }, ] : []), + ...(state.machineMoveTargets && state.machineMoveTargets.length > 0 + ? [ + { + id: "move-to-machine" as const, + label: "Move to machine", + icon: "server", + disabled: state.isRunning, + children: state.machineMoveTargets.map((machine, machineIndex) => ({ + id: `move-to-machine:${machineIndex}` as const, + label: machine.label, + children: machine.projects.map((project, projectIndex) => ({ + id: `move-to-machine:${machineIndex}:${projectIndex}` as const, + label: project.title, + })), + })), + }, + ] + : []), ...(state.supports.autoSettleOptOut ? [ { diff --git a/apps/web/src/contextMenuFallback.ts b/apps/web/src/contextMenuFallback.ts index 01e32c753387e..c3846feddc53e 100644 --- a/apps/web/src/contextMenuFallback.ts +++ b/apps/web/src/contextMenuFallback.ts @@ -124,6 +124,12 @@ const ICON_PATHS: Record ({ canTurnThreadIntoProject: () => false, confirmThreadMove: async () => false, readThreadMoveTargets: () => [], + readThreadMachineMoveTargets: () => [], useThreadActions: () => Object.fromEntries( [ diff --git a/apps/web/src/hooks/useThreadActionMenu.ts b/apps/web/src/hooks/useThreadActionMenu.ts index 124445ec05fb1..a8501906b51cf 100644 --- a/apps/web/src/hooks/useThreadActionMenu.ts +++ b/apps/web/src/hooks/useThreadActionMenu.ts @@ -19,6 +19,7 @@ import { useRouter } from "@tanstack/react-router"; import { pickSnoozePreset, resolveSnoozePresets } from "../components/Sidebar.snooze"; import { buildThreadActionMenuItems, + parseMachineMovePick, threadActionRequiresOperate, type ThreadActionMenuId, } from "../components/threadActionMenu.logic"; @@ -51,6 +52,7 @@ import { useClientSettings } from "./useSettings"; import { canTurnThreadIntoProject, confirmThreadMove, + readThreadMachineMoveTargets, readThreadMoveTargets, useThreadActions, } from "./useThreadActions"; @@ -95,6 +97,7 @@ export function useThreadActionMenu(input: { markThreadUnread, turnThreadIntoProject, moveThreadToProject, + moveThreadToMachine, } = useThreadActions(); const regenerateThreadTitle = useOrchestrationCommand(threadEnvironment.regenerateTitle, { reportFailure: false, @@ -135,6 +138,7 @@ export function useThreadActionMenu(input: { }; const isRegeneratingTitle = thread.titleRegeneration != null; const snoozePresets = resolveSnoozePresets(now, timestampFormat, threadRef.environmentId); + const machineMoveTargets = readThreadMachineMoveTargets(threadRef); const items = buildThreadActionMenuItems({ canOperate: readEnvironmentScope(threadRef.environmentId, AuthOrchestrationOperateScope), canFind: onFind !== undefined, @@ -152,6 +156,7 @@ export function useThreadActionMenu(input: { canShareWithGuest, canTurnIntoProject: canTurnThreadIntoProject(threadRef), moveTargets: readThreadMoveTargets(threadRef), + machineMoveTargets, }); const clicked = await settlePromise(() => api.contextMenu.show(items, position)); if (clicked._tag === "Failure" || clicked.value === null) return; @@ -192,6 +197,14 @@ export function useThreadActionMenu(input: { failureToast(title, squashAtomCommandFailure(result)); } }; + const machinePick = parseMachineMovePick(action, machineMoveTargets); + if (machinePick) { + await moveThreadToMachine(threadRef, { + environmentId: machinePick.machine.environmentId, + projectId: machinePick.project.id, + }); + return; + } if (action.startsWith("move-to-project:")) { const projectId = ProjectId.make(action.slice("move-to-project:".length)); if (!(await confirmThreadMove(threadRef, projectId))) return; diff --git a/apps/web/src/hooks/useThreadActions.ts b/apps/web/src/hooks/useThreadActions.ts index 0324e9c15344b..5312a33e7fa5b 100644 --- a/apps/web/src/hooks/useThreadActions.ts +++ b/apps/web/src/hooks/useThreadActions.ts @@ -7,6 +7,10 @@ import { import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; import { canSnooze, threadWokeAt } from "@t3tools/client-runtime/state/thread-settled"; import { threadMoveTargets, threadRuntimeCanArchive } from "@t3tools/client-runtime/state/models"; +import { + moveThreadToMachine, + threadMachineMoveTargets, +} from "@t3tools/client-runtime/state/threadMachineMove"; import { AuthOrchestrationOperateScope, AuthSourceControlWriteScope, @@ -18,7 +22,7 @@ import { sessionGrantsScope, } from "@t3tools/contracts"; import { resolveWorktreeCleanup } from "@t3tools/shared/projectSettings"; -import { threadMoveNotice } from "@t3tools/shared/threadMove"; +import { threadMachineMoveNotice, threadMoveNotice } from "@t3tools/shared/threadMove"; import * as Cause from "effect/Cause"; import * as Schema from "effect/Schema"; import { AsyncResult } from "effect/reactivity"; @@ -29,6 +33,8 @@ import { useComposerDraftStore } from "../composerDraftStore"; import { environmentSession, readEnvironmentScope } from "../state/session"; import { appAtomRegistry } from "../rpc/atomRegistry"; import { environmentServerConfigsAtom } from "../state/server"; +import { readEnvironment } from "../state/environments"; +import { environmentSummaries } from "../state/presentation"; import { isScratchProject } from "@t3tools/client-runtime/state/projects"; import { orchestrationEnvironment } from "../state/orchestration"; import { projectEnvironment } from "../state/projects"; @@ -293,6 +299,77 @@ export async function confirmThreadMove( return confirmed._tag === "Success" && confirmed.value; } +/** Other connected machines this thread can move to, each with its projects. */ +export function readThreadMachineMoveTargets(threadRef: ScopedThreadRef) { + return threadMachineMoveTargets({ + sourceEnvironmentId: threadRef.environmentId, + connectedEnvironmentIds: appAtomRegistry.get(environmentSummaries.connectedEnvironmentIdsAtom), + serverConfigs: appAtomRegistry.get(environmentServerConfigsAtom), + projects: readProjects(), + labelOf: (environmentId) => readEnvironment(environmentId)?.label, + canOperate: (environmentId) => + readEnvironmentScope(environmentId, AuthOrchestrationOperateScope), + }); +} + +/** Confirms, moves the thread to a project on another machine, then opens it there. */ +export async function moveThreadToMachineAndOpen( + source: ScopedThreadRef, + target: { readonly environmentId: EnvironmentId; readonly projectId: ProjectId }, + open: (threadRef: ScopedThreadRef) => Promise, +): Promise { + const thread = readThreadShell(source); + const project = readProject(target); + const fromMachine = readEnvironment(source.environmentId)?.label; + const toMachine = readEnvironment(target.environmentId)?.label; + const api = readLocalApi(); + if (!thread || !project || !fromMachine || !toMachine || !api) return; + const outcome = await moveThreadToMachine({ + registry: appAtomRegistry, + commands: projectEnvironment, + source, + sourceLabel: fromMachine, + target, + targetLabel: `${project.title} on ${toMachine}`, + confirm: async ({ leftBehind }) => { + const notice = threadMachineMoveNotice({ + fromMachine, + toMachine, + projectTitle: project.title, + leftBehind, + }); + const confirmed = await settlePromise(() => + api.dialogs.confirm(`Move "${thread.title}" to ${toMachine}?\n${notice}`, { + initialFocus: "confirm", + }), + ); + return confirmed._tag === "Success" && confirmed.value; + }, + }); + if (outcome._tag === "Cancelled") return; + if (outcome._tag === "Failed") { + toastManager.add( + stackedThreadToast({ + type: "error", + title: "Could not move thread", + description: outcome.message, + }), + ); + return; + } + refreshArchivedThreadsForEnvironment(source.environmentId); + if (outcome.archiveError !== null) { + toastManager.add( + stackedThreadToast({ + type: "warning", + title: `Moved, but the thread is still active on ${fromMachine}`, + description: `${outcome.archiveError} Archive it there so you don't continue both.`, + }), + ); + } + await settlePromise(() => open(outcome.threadRef)); +} + function threadOperationFailure(target: ScopedThreadRef) { return readEnvironmentScope(target.environmentId, AuthOrchestrationOperateScope) ? null @@ -1070,5 +1147,15 @@ export function useThreadActions() { environmentId: target.environmentId, input: { threadId: target.threadId, projectId }, }), + moveThreadToMachine: ( + source: ScopedThreadRef, + target: { readonly environmentId: EnvironmentId; readonly projectId: ProjectId }, + ) => + moveThreadToMachineAndOpen(source, target, (threadRef) => + router.navigate({ + to: "/$environmentId/$threadId", + params: buildThreadRouteParams(threadRef), + }), + ), }; } diff --git a/docs/user/thread-sidebar.md b/docs/user/thread-sidebar.md index 64d17e206e7e5..04cccc383ccbd 100644 --- a/docs/user/thread-sidebar.md +++ b/docs/user/thread-sidebar.md @@ -60,6 +60,18 @@ there. The old worktree shows as unused in [Storage cleanup](./project-settings.md#storage-cleanup). To keep working in a fresh worktree, hand the moved thread off to one. +### Move a thread to another machine + +To continue a conversation on another connected machine, pick **Move to machine** +from the thread's menu, or **Move thread to machine...** in the command palette, +and choose a project there. Both machines need this version of T3 Code, and your +connection must be allowed to change threads on both. + +The new thread gets the conversation, and your next message starts a fresh agent +session there with that history. Files, diffs, the worktree, attachments and +scheduled tasks stay on the first machine, where the old thread is archived. To go +back, unarchive it there, or move the new thread back the same way. + ### Start in the background In a desktop browser or the desktop app, press `Cmd+Enter` on macOS or `Ctrl+Enter` diff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.json index 19989716bc3c6..7c8eb5800a723 100644 --- a/packages/client-runtime/package.json +++ b/packages/client-runtime/package.json @@ -219,6 +219,10 @@ "types": "./src/state/models.ts", "default": "./src/state/models.ts" }, + "./state/threadMachineMove": { + "types": "./src/state/threadMachineMove.ts", + "default": "./src/state/threadMachineMove.ts" + }, "./state/orchestration": { "types": "./src/state/orchestration.ts", "default": "./src/state/orchestration.ts" diff --git a/packages/client-runtime/src/state/models.ts b/packages/client-runtime/src/state/models.ts index 4939b540aeabc..88009a242eccc 100644 --- a/packages/client-runtime/src/state/models.ts +++ b/packages/client-runtime/src/state/models.ts @@ -26,21 +26,31 @@ export interface EnvironmentProject extends OrchestrationProjectShell { readonly isScratch?: true; } -/** Where a thread can move: the other live projects on its environment, except No project. */ -export function threadMoveTargets( +/** The live projects on `environmentId` a thread can move into: all but No project. */ +export function threadMoveProjects( projects: ReadonlyArray, - thread: { readonly environmentId: EnvironmentId; readonly projectId: ProjectId }, + environmentId: EnvironmentId, scratchWorkspaceRoot: string | null | undefined, ): ReadonlyArray { return projects.filter( (project) => - project.environmentId === thread.environmentId && - project.id !== thread.projectId && + project.environmentId === environmentId && project.archivedAt == null && !isScratchProject(project, scratchWorkspaceRoot), ); } +/** Where a thread can move: the other live projects on its environment, except No project. */ +export function threadMoveTargets( + projects: ReadonlyArray, + thread: { readonly environmentId: EnvironmentId; readonly projectId: ProjectId }, + scratchWorkspaceRoot: string | null | undefined, +): ReadonlyArray { + return threadMoveProjects(projects, thread.environmentId, scratchWorkspaceRoot).filter( + (project) => project.id !== thread.projectId, + ); +} + /** * The projection stays nested so the server projection and all structurally * shared collections retain their identities. diff --git a/packages/client-runtime/src/state/projectCommands.ts b/packages/client-runtime/src/state/projectCommands.ts index 0f5e19e7aa01d..31c632d974145 100644 --- a/packages/client-runtime/src/state/projectCommands.ts +++ b/packages/client-runtime/src/state/projectCommands.ts @@ -229,6 +229,24 @@ export function createProjectEnvironmentAtoms( scheduler: projectScheduler, concurrency: { mode: "serial", key: ({ environmentId }) => environmentId }, }), + exportThread: createEnvironmentRpcCommand(runtime, { + label: "environment-data:projects:export-thread", + tag: WS_METHODS.projectsExportThread, + scheduler: projectScheduler, + concurrency: { mode: "serial", key: ({ environmentId }) => environmentId }, + }), + importThread: createEnvironmentRpcCommand(runtime, { + label: "environment-data:projects:import-thread", + tag: WS_METHODS.projectsImportThread, + scheduler: projectScheduler, + concurrency: { mode: "serial", key: ({ environmentId }) => environmentId }, + }), + finishThreadMove: createEnvironmentRpcCommand(runtime, { + label: "environment-data:projects:finish-thread-move", + tag: WS_METHODS.projectsFinishThreadMove, + scheduler: projectScheduler, + concurrency: { mode: "serial", key: ({ environmentId }) => environmentId }, + }), writeFile: createEnvironmentRpcCommand(runtime, { label: "environment-data:projects:write-file", tag: WS_METHODS.projectsWriteFile, diff --git a/packages/client-runtime/src/state/threadMachineMove.test.ts b/packages/client-runtime/src/state/threadMachineMove.test.ts new file mode 100644 index 0000000000000..17a9c815864f7 --- /dev/null +++ b/packages/client-runtime/src/state/threadMachineMove.test.ts @@ -0,0 +1,105 @@ +import { + EnvironmentId, + ProjectId, + ProviderInstanceId, + ThreadId, + type ProjectExportThreadResult, +} from "@t3tools/contracts"; +import * as Cause from "effect/Cause"; +import { AsyncResult, AtomRegistry } from "effect/reactivity"; +import { describe, expect, it } from "vite-plus/test"; + +import type { AtomCommand } from "./runtime.ts"; +import { moveThreadToMachine, type ThreadMachineMoveCommands } from "./threadMachineMove.ts"; + +const source = { environmentId: EnvironmentId.make("laptop"), threadId: ThreadId.make("old") }; +const target = { environmentId: EnvironmentId.make("vps"), projectId: ProjectId.make("api") }; +const exported: ProjectExportThreadResult = { + bundle: { + title: "Port the parser", + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "m" }, + runtimeMode: "full-access", + interactionMode: "default", + createdAt: "2026-01-01T00:00:00.000Z", + messages: [{ role: "user", text: "Port it.", createdAt: "2026-01-01T00:00:00.000Z" }], + }, + leftBehind: { diffs: true, worktree: false, attachments: 0, scheduledTasks: 0 }, +}; + +type Step = "export" | "import" | "finish"; + +function setup(failing: ReadonlySet) { + const calls: Array<{ readonly step: Step; readonly environmentId: string }> = []; + const command =
( + step: Step, + value: A, + ): AtomCommand< + { readonly environmentId: EnvironmentId; readonly input: unknown }, + A, + unknown + > => ({ + label: step, + run: async (_registry, { environmentId }) => { + calls.push({ step, environmentId }); + return failing.has(step) + ? AsyncResult.failure(Cause.fail(new Error(`${step} failed`))) + : AsyncResult.success(value); + }, + }); + const commands: ThreadMachineMoveCommands = { + exportThread: command("export", exported), + importThread: command("import", { threadId: ThreadId.make("new") }), + finishThreadMove: command("finish", undefined), + }; + const move = (confirm = true) => + moveThreadToMachine({ + registry: AtomRegistry.make(), + commands, + source, + sourceLabel: "Laptop", + target, + targetLabel: "api on VPS", + confirm: async () => confirm, + }); + return { calls, move }; +} + +describe("moveThreadToMachine", () => { + it("imports on the target before archiving on the source", async () => { + const { calls, move } = setup(new Set()); + expect(await move()).toEqual({ + _tag: "Moved", + threadRef: { environmentId: "vps", threadId: "new" }, + archiveError: null, + }); + expect(calls).toEqual([ + { step: "export", environmentId: "laptop" }, + { step: "import", environmentId: "vps" }, + { step: "finish", environmentId: "laptop" }, + ]); + }); + + it.each([ + { failing: "export" as const, reached: ["export"] }, + { failing: "import" as const, reached: ["export", "import"] }, + ])("archives nothing when $failing fails", async ({ failing, reached }) => { + const { calls, move } = setup(new Set([failing])); + expect(await move()).toEqual({ _tag: "Failed", message: `${failing} failed` }); + expect(calls.map((call) => call.step)).toEqual(reached); + }); + + it("changes nothing when the move is not confirmed", async () => { + const { calls, move } = setup(new Set()); + expect(await move(false)).toEqual({ _tag: "Cancelled" }); + expect(calls.map((call) => call.step)).toEqual(["export"]); + }); + + it("reports the new thread and the archive failure, so the user knows both copies exist", async () => { + const { move } = setup(new Set(["finish"])); + expect(await move()).toEqual({ + _tag: "Moved", + threadRef: { environmentId: "vps", threadId: "new" }, + archiveError: "finish failed", + }); + }); +}); diff --git a/packages/client-runtime/src/state/threadMachineMove.ts b/packages/client-runtime/src/state/threadMachineMove.ts new file mode 100644 index 0000000000000..2304cdb4cbb97 --- /dev/null +++ b/packages/client-runtime/src/state/threadMachineMove.ts @@ -0,0 +1,139 @@ +import type { + EnvironmentId, + ProjectExportThreadResult, + ProjectFinishThreadMoveInput, + ProjectId, + ProjectImportThreadInput, + ProjectImportThreadResult, + ScopedThreadRef, + ServerConfig, + ThreadId, +} from "@t3tools/contracts"; +import type { AtomRegistry } from "effect/reactivity"; + +import { type EnvironmentProject, threadMoveProjects } from "./models.ts"; +import { + type AtomCommand, + type AtomCommandResult, + isAtomCommandInterrupted, + squashAtomCommandFailure, +} from "./runtime.ts"; + +type EnvironmentCommand = AtomCommand< + { readonly environmentId: EnvironmentId; readonly input: I }, + A, + unknown +>; + +export interface ThreadMachineMoveCommands { + readonly exportThread: EnvironmentCommand< + { readonly threadId: ThreadId }, + ProjectExportThreadResult + >; + readonly importThread: EnvironmentCommand; + readonly finishThreadMove: EnvironmentCommand; +} + +export type ThreadMachineMoveOutcome = + | { readonly _tag: "Cancelled" } + /** Nothing changed on either machine. */ + | { readonly _tag: "Failed"; readonly message: string } + /** The new thread exists; `archiveError` says the old one is still active beside it. */ + | { + readonly _tag: "Moved"; + readonly threadRef: ScopedThreadRef; + readonly archiveError: string | null; + }; + +export interface ThreadMachineMoveTarget { + readonly environmentId: EnvironmentId; + readonly label: string; + readonly projects: ReadonlyArray; +} + +/** The other connected machines a thread can move to, each with its projects. Both ends must support it. */ +export function threadMachineMoveTargets(input: { + readonly sourceEnvironmentId: EnvironmentId; + readonly connectedEnvironmentIds: ReadonlyArray; + readonly serverConfigs: ReadonlyMap; + readonly projects: ReadonlyArray; + readonly labelOf: (environmentId: EnvironmentId) => string | undefined; + readonly canOperate: (environmentId: EnvironmentId) => boolean; +}): ReadonlyArray { + const supports = (environmentId: EnvironmentId) => + input.serverConfigs.get(environmentId)?.environment.capabilities.threadMoveToMachine === true; + if (!supports(input.sourceEnvironmentId)) return []; + return input.connectedEnvironmentIds.flatMap((environmentId) => { + const label = input.labelOf(environmentId); + if ( + environmentId === input.sourceEnvironmentId || + label === undefined || + !supports(environmentId) || + !input.canOperate(environmentId) + ) { + return []; + } + const projects = threadMoveProjects( + input.projects, + environmentId, + input.serverConfigs.get(environmentId)?.scratchWorkspaceRoot, + ); + return projects.length === 0 ? [] : [{ environmentId, label, projects }]; + }); +} + +function failureMessage(result: AtomCommandResult): string { + if (result._tag !== "Failure") return "Try again."; + const error = squashAtomCommandFailure(result); + return error instanceof Error && error.message !== "" ? error.message : "Try again."; +} + +/** + * Copies the thread's conversation to a project on another machine, then archives it here. The + * client carries the bundle over connections it already has, so the servers never trust each + * other. Archiving waits for the import, so a failed import changes nothing. + */ +export async function moveThreadToMachine(input: { + readonly registry: AtomRegistry.AtomRegistry; + readonly commands: ThreadMachineMoveCommands; + readonly source: ScopedThreadRef; + readonly sourceLabel: string; + readonly target: { readonly environmentId: EnvironmentId; readonly projectId: ProjectId }; + /** "api on VPS": where the archived thread says it went. */ + readonly targetLabel: string; + readonly confirm: (exported: ProjectExportThreadResult) => Promise; +}): Promise { + const { registry, commands, source, target } = input; + const settled = (result: AtomCommandResult): ThreadMachineMoveOutcome => + isAtomCommandInterrupted(result) + ? { _tag: "Cancelled" } + : { _tag: "Failed", message: failureMessage(result) }; + + const exported = await commands.exportThread.run(registry, { + environmentId: source.environmentId, + input: { threadId: source.threadId }, + }); + if (exported._tag !== "Success") return settled(exported); + if (!(await input.confirm(exported.value))) return { _tag: "Cancelled" }; + + const imported = await commands.importThread.run(registry, { + environmentId: target.environmentId, + input: { + projectId: target.projectId, + bundle: exported.value.bundle, + movedFrom: input.sourceLabel, + }, + }); + if (imported._tag !== "Success") return settled(imported); + const threadRef = { environmentId: target.environmentId, threadId: imported.value.threadId }; + + const finished = await commands.finishThreadMove.run(registry, { + environmentId: source.environmentId, + input: { threadId: source.threadId, movedTo: input.targetLabel }, + }); + return { + _tag: "Moved", + threadRef, + archiveError: finished._tag === "Success" ? null : failureMessage(finished), + }; +} diff --git a/packages/contracts/src/clientRpcPermissions.ts b/packages/contracts/src/clientRpcPermissions.ts index 6fa13eb05b0dc..897020a888a1b 100644 --- a/packages/contracts/src/clientRpcPermissions.ts +++ b/packages/contracts/src/clientRpcPermissions.ts @@ -44,6 +44,8 @@ export const CLIENT_GUARDED_RPC_SCOPES = { [WS_METHODS.pullRequestsGenerateReviewGuide]: AuthOrchestrationOperateScope, [WS_METHODS.projectsCreateFromThread]: AuthOrchestrationOperateScope, [WS_METHODS.projectsMoveThread]: AuthOrchestrationOperateScope, + [WS_METHODS.projectsImportThread]: AuthOrchestrationOperateScope, + [WS_METHODS.projectsFinishThreadMove]: AuthOrchestrationOperateScope, [WS_METHODS.sourceControlCloneRepository]: AuthSourceControlWriteScope, [WS_METHODS.sourceControlPublishRepository]: AuthSourceControlWriteScope, [WS_METHODS.sourceControlStar]: AuthSourceControlWriteScope, diff --git a/packages/contracts/src/environment.ts b/packages/contracts/src/environment.ts index 632f58d97bd97..3a76ea394e8b3 100644 --- a/packages/contracts/src/environment.ts +++ b/packages/contracts/src/environment.ts @@ -137,6 +137,7 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({ threadAutoSettleOptOut: Schema.optionalKey(Schema.Boolean), threadProjectFromScratch: Schema.optionalKey(Schema.Boolean), threadMoveToProject: Schema.optionalKey(Schema.Boolean), + threadMoveToMachine: Schema.optionalKey(Schema.Boolean), threadTitleRegeneration: Schema.optionalKey(Schema.Boolean), threadVisitedTracking: Schema.optionalKey(Schema.Boolean), threadPullRequestLinking: Schema.optionalKey(Schema.Boolean), diff --git a/packages/contracts/src/project.ts b/packages/contracts/src/project.ts index f51e67bcdb08b..b9ab2200e6970 100644 --- a/packages/contracts/src/project.ts +++ b/packages/contracts/src/project.ts @@ -2,6 +2,7 @@ import * as Schema from "effect/Schema"; import * as SchemaTransformation from "effect/SchemaTransformation"; import { RepositoryIdentity, ThreadEnvMode } from "./environment.ts"; import { ModelSelection } from "./modelSelection.ts"; +import { ProviderInteractionMode, RuntimeMode } from "./providerPolicy.ts"; import { CommandId, ForwardCompatibleUnion, @@ -559,6 +560,59 @@ export const ProjectMoveThreadInput = Schema.Struct({ }); export type ProjectMoveThreadInput = typeof ProjectMoveThreadInput.Type; +/** + * A thread's conversation as another environment can import it. Checkpoints, runs, provider + * sessions and attachments belong to the machine that made them, so they stay behind. + */ +export const ThreadMoveBundle = Schema.Struct({ + title: TrimmedNonEmptyString, + modelSelection: ModelSelection, + runtimeMode: RuntimeMode, + interactionMode: ProviderInteractionMode, + createdAt: IsoDateTime, + messages: Schema.Array( + Schema.Struct({ + role: Schema.Literals(["user", "assistant"]), + text: Schema.String, + createdAt: IsoDateTime, + }), + ), +}); +export type ThreadMoveBundle = typeof ThreadMoveBundle.Type; + +export const ProjectExportThreadInput = Schema.Struct({ threadId: ThreadId }); +export type ProjectExportThreadInput = typeof ProjectExportThreadInput.Type; + +export const ProjectExportThreadResult = Schema.Struct({ + bundle: ThreadMoveBundle, + /** What stays on this environment, so the confirmation names only what applies. */ + leftBehind: Schema.Struct({ + diffs: Schema.Boolean, + worktree: Schema.Boolean, + attachments: NonNegativeInt, + scheduledTasks: NonNegativeInt, + }), +}); +export type ProjectExportThreadResult = typeof ProjectExportThreadResult.Type; + +export const ProjectImportThreadInput = Schema.Struct({ + projectId: ProjectId, + bundle: ThreadMoveBundle, + /** The source machine as the user knows it, for the new thread's notice. */ + movedFrom: TrimmedNonEmptyString, +}); +export type ProjectImportThreadInput = typeof ProjectImportThreadInput.Type; + +export const ProjectImportThreadResult = Schema.Struct({ threadId: ThreadId }); +export type ProjectImportThreadResult = typeof ProjectImportThreadResult.Type; + +export const ProjectFinishThreadMoveInput = Schema.Struct({ + threadId: ThreadId, + /** Where the conversation went, as the user knows it, for the archived thread's notice. */ + movedTo: TrimmedNonEmptyString, +}); +export type ProjectFinishThreadMoveInput = typeof ProjectFinishThreadMoveInput.Type; + export class ProjectWriteFileError extends Schema.TaggedError()( "ProjectWriteFileError", { diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts index 63e0767474bdc..b76a9ac87541e 100644 --- a/packages/contracts/src/rpc.ts +++ b/packages/contracts/src/rpc.ts @@ -247,6 +247,11 @@ import { ProjectCreateFromThreadInput, ProjectCreateFromThreadResult, ProjectMoveThreadInput, + ProjectExportThreadInput, + ProjectExportThreadResult, + ProjectImportThreadInput, + ProjectImportThreadResult, + ProjectFinishThreadMoveInput, ProjectEnsureScratchResult, ProjectListEntriesError, ProjectListEntriesInput, @@ -432,6 +437,9 @@ export const WS_METHODS = { projectsCreateNew: "projects.createNew", projectsCreateFromThread: "projects.createFromThread", projectsMoveThread: "projects.moveThread", + projectsExportThread: "projects.exportThread", + projectsImportThread: "projects.importThread", + projectsFinishThreadMove: "projects.finishThreadMove", shellOpenInEditor: "shell.openInEditor", @@ -1438,6 +1446,23 @@ const WsProjectsMoveThreadRpc = Rpc.make(WS_METHODS.projectsMoveThread, { error: Schema.Union([OrchestrationDispatchCommandError, EnvironmentAuthorizationError]), }); +const WsProjectsExportThreadRpc = Rpc.make(WS_METHODS.projectsExportThread, { + payload: ProjectExportThreadInput, + success: ProjectExportThreadResult, + error: Schema.Union([OrchestrationDispatchCommandError, EnvironmentAuthorizationError]), +}); + +const WsProjectsImportThreadRpc = Rpc.make(WS_METHODS.projectsImportThread, { + payload: ProjectImportThreadInput, + success: ProjectImportThreadResult, + error: Schema.Union([OrchestrationDispatchCommandError, EnvironmentAuthorizationError]), +}); + +const WsProjectsFinishThreadMoveRpc = Rpc.make(WS_METHODS.projectsFinishThreadMove, { + payload: ProjectFinishThreadMoveInput, + error: Schema.Union([OrchestrationDispatchCommandError, EnvironmentAuthorizationError]), +}); + const WsShellOpenInEditorRpc = Rpc.make(WS_METHODS.shellOpenInEditor, { payload: LaunchEditorInput, error: Schema.Union([ExternalLauncherError, EnvironmentAuthorizationError]), @@ -2258,6 +2283,9 @@ export const WsRpcGroup = RpcGroup.make( WsProjectsCreateNewRpc, WsProjectsCreateFromThreadRpc, WsProjectsMoveThreadRpc, + WsProjectsExportThreadRpc, + WsProjectsImportThreadRpc, + WsProjectsFinishThreadMoveRpc, WsProjectsWriteFileRpc, WsProjectsMutateRpc, WsShellOpenInEditorRpc, diff --git a/packages/shared/src/threadMove.ts b/packages/shared/src/threadMove.ts index 3dc57eaa8037d..397498b0e8a99 100644 --- a/packages/shared/src/threadMove.ts +++ b/packages/shared/src/threadMove.ts @@ -7,3 +7,29 @@ export function threadMoveNotice(input: { ? `The agent will work in ${input.projectTitle}'s root folder. The worktree and its branch stay on disk, but the agent won't see changes left there. Earlier diffs open while the worktree exists, and files from earlier turns can't be restored.` : `The conversation moves with it, and the agent works in ${input.projectTitle}'s folder from the next message. Earlier diffs open while their original folder exists, and files from earlier turns can't be restored.`; } + +/** What moving a thread to another machine carries and leaves behind; names only what applies. */ +export function threadMachineMoveNotice(input: { + readonly fromMachine: string; + readonly toMachine: string; + readonly projectTitle: string; + readonly leftBehind: { + readonly diffs: boolean; + readonly worktree: boolean; + readonly attachments: number; + readonly scheduledTasks: number; + }; +}): string { + const { leftBehind } = input; + const count = (n: number, noun: string) => `${n} ${noun}${n === 1 ? "" : "s"}`; + const stays = [ + "Files", + ...(leftBehind.diffs ? ["diffs"] : []), + ...(leftBehind.worktree ? ["the worktree"] : []), + ...(leftBehind.attachments > 0 ? [count(leftBehind.attachments, "attachment")] : []), + ...(leftBehind.scheduledTasks > 0 ? [count(leftBehind.scheduledTasks, "scheduled task")] : []), + ]; + const list = + stays.length === 1 ? stays[0] : `${stays.slice(0, -1).join(", ")} and ${stays.at(-1)}`; + return `The conversation moves to ${input.projectTitle} on ${input.toMachine} and continues in a new session there. ${list} stay on ${input.fromMachine}, where this thread is archived. Unarchive it to come back.`; +} From a581d48c2744cf335c836ddae16bbaf9a8a4888a Mon Sep 17 00:00:00 2001 From: Batch Processor <46352227+batchema@users.noreply.github.com> Date: Sun, 15 Nov 2026 01:12:10 +0100 Subject: [PATCH 17/20] fix: review round 1 for moving threads between machines - Finishing a move refuses, and leaves the original active, when a run started on the source after the export; the client says the moved copy exists and why the original stayed. - A second move of the same thread is ignored while one is in flight. - Exports go through the transcript export's size preflight, budget and concurrency limit; imports refuse bundles over that budget. - Imports use the source's provider when the target runs it, else the target project's default only when usable, else refuse with what to set up. - The move menus need permission to change threads on the source too. - The new thread's notice names only what stayed behind. Co-Authored-By: Claude Opus 5.5 --- .../features/threads/moveThreadToMachine.ts | 4 +- .../src/orchestration-v2/runtimeLayer.test.ts | 44 +++++---- .../src/project/ThreadProjectMove.test.ts | 61 ++++++++++++ apps/server/src/project/ThreadProjectMove.ts | 93 +++++++++++++++---- apps/web/src/hooks/useThreadActions.ts | 4 +- docs/user/thread-sidebar.md | 4 + packages/client-runtime/src/state/models.ts | 10 +- .../src/state/threadMachineMove.test.ts | 44 ++++++++- .../src/state/threadMachineMove.ts | 53 +++++++++-- packages/contracts/src/project.ts | 21 +++-- packages/shared/src/threadMove.ts | 36 +++---- 11 files changed, 295 insertions(+), 79 deletions(-) create mode 100644 apps/server/src/project/ThreadProjectMove.test.ts diff --git a/apps/mobile/src/features/threads/moveThreadToMachine.ts b/apps/mobile/src/features/threads/moveThreadToMachine.ts index 255e99f744b48..a79586c2bf674 100644 --- a/apps/mobile/src/features/threads/moveThreadToMachine.ts +++ b/apps/mobile/src/features/threads/moveThreadToMachine.ts @@ -75,8 +75,8 @@ export async function moveThreadToMachine( if (outcome._tag === "Failed") Dialog.alert("Could not move thread", outcome.message); if (outcome._tag === "Moved" && outcome.archiveError !== null) { Dialog.alert( - `Moved, but the thread is still active on ${fromMachine}`, - `${outcome.archiveError} Archive it there so you don't continue both.`, + `Moved, but the original is still active on ${fromMachine}`, + `${outcome.archiveError} The moved copy is on ${machine.label}.`, ); } } diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index ec22d5797e744..95e0e85551433 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -88,6 +88,7 @@ import * as ThreadManagementService from "./ThreadManagementService.ts"; import * as ManagedProjectFolders from "../project/ManagedProjectFolders.ts"; import * as ScratchThreadPromotion from "../project/ScratchThreadPromotion.ts"; import * as ThreadProjectMove from "../project/ThreadProjectMove.ts"; +import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts"; import * as ScheduledTaskService from "../scheduledTasks/ScheduledTaskService.ts"; @@ -10211,6 +10212,9 @@ const layerThreadProjectMoveTest = ThreadProjectMove.layer.pipe( { defaultModelSelection: modelSelection }, { organization: "Org", lockedSettings: [], limits: { maxRuntimeMode: "auto" } }, ), + Layer.mock(ServerEnvironment.ServerEnvironmentIdentity)({ + getEnvironmentId: Effect.succeed(EnvironmentId.make("machine-move-test")), + }), IdAllocator.layer, NodeCrypto.layer, ), @@ -10378,6 +10382,7 @@ it.layer(layerThreadProjectMoveTest)("moving a thread to another project", (it) projectId: targetId, bundle, movedFrom: "Laptop", + leftBehind: { diffs: true, worktree: true, attachments: 0, scheduledTasks: 0 }, }); const imported = (yield* orchestrator.getThreadRecords(threadId, [])).thread; assert.equal(imported.projectId, targetId); @@ -10403,10 +10408,10 @@ it.layer(layerThreadProjectMoveTest)("moving a thread to another project", (it) projection.visibleTurnItems.map(({ item }) => item.type === "system_notice" ? item.message : "", ), - "Moved from Laptop. Its files and diffs stayed there.", + "Moved from Laptop. Files, diffs and the worktree stayed there.", ); - yield* service.finishMove({ threadId, movedTo: "VPS" }); + yield* service.finishMove({ threadId, movedTo: "VPS", revision: exported.revision }); const finished = yield* threads.getThreadSnapshot(threadId); assert.isNotNull(finished.projection.thread.archivedAt); assert.include( @@ -10416,34 +10421,35 @@ it.layer(layerThreadProjectMoveTest)("moving a thread to another project", (it) "Moved to VPS. Messages sent here stay separate from that thread.", ); - const busyId = ThreadId.make("machine-move-busy"); - yield* orchestrator.dispatch({ - type: "thread.create", - createdBy: "user", - creationSource: "web", - commandId: CommandId.make("machine-move-busy-create"), - threadId: busyId, + // A turn starts on the source after the export, from another device or a schedule. + const raced = yield* service.importThread({ projectId: targetId, - title: "Busy", - modelSelection, - runtimeMode: "full-access", - interactionMode: "default", - branch: null, - worktreePath: null, + bundle, + movedFrom: "Laptop", + leftBehind: { diffs: false, worktree: false, attachments: 0, scheduledTasks: 0 }, }); + const before = yield* service.exportThread(raced.threadId); yield* orchestrator.dispatch({ type: "message.dispatch", createdBy: "user", creationSource: "web", - commandId: CommandId.make("machine-move-busy-message"), - threadId: busyId, - messageId: MessageId.make("machine-move-busy-message"), + commandId: CommandId.make("machine-move-raced-message"), + threadId: raced.threadId, + messageId: MessageId.make("machine-move-raced-message"), text: "Keep this run active.", attachments: [], modelSelection, dispatchMode: { type: "start_immediately" }, }); - const busy = yield* service.exportThread(busyId).pipe(Effect.flip); + const refused = yield* service + .finishMove({ threadId: raced.threadId, movedTo: "VPS", revision: before.revision }) + .pipe(Effect.flip); + assert.equal( + refused.message, + "It changed after the move started, so it was left active here. Its newest messages aren't in the moved copy.", + ); + assert.isNull((yield* orchestrator.getThreadRecords(raced.threadId, [])).thread.archivedAt); + const busy = yield* service.exportThread(raced.threadId).pipe(Effect.flip); assert.equal(busy.message, "The thread still has work in progress. Finish or stop it first."); }), ); diff --git a/apps/server/src/project/ThreadProjectMove.test.ts b/apps/server/src/project/ThreadProjectMove.test.ts new file mode 100644 index 0000000000000..c422b3ccab1a0 --- /dev/null +++ b/apps/server/src/project/ThreadProjectMove.test.ts @@ -0,0 +1,61 @@ +import { type ModelSelection, ProviderInstanceId, type ThreadMoveBundle } from "@t3tools/contracts"; +import { describe, expect, it } from "vite-plus/test"; + +import { movedModelSelection, threadMoveBundleFits } from "./ThreadProjectMove.ts"; + +const source = { instanceId: ProviderInstanceId.make("source-only"), model: "s" }; +const fallback = { instanceId: ProviderInstanceId.make("codex"), model: "d" }; + +describe("movedModelSelection", () => { + it.each<{ + readonly case: string; + readonly usable: ReadonlyArray; + readonly projectDefault: ModelSelection | null; + readonly expected: ModelSelection | null; + }>([ + { + case: "the source instance exists here", + usable: ["source-only"], + projectDefault: fallback, + expected: source, + }, + { + case: "only the default is usable", + usable: ["codex"], + projectDefault: fallback, + expected: fallback, + }, + { case: "no default is set", usable: ["codex"], projectDefault: null, expected: null }, + { + case: "the default's instance is missing or disabled", + usable: [], + projectDefault: fallback, + expected: null, + }, + ])("$case", ({ usable, projectDefault, expected }) => { + expect( + movedModelSelection({ + source, + projectDefault, + usable: (instanceId) => usable.includes(instanceId), + }), + ).toEqual(expected); + }); +}); + +describe("threadMoveBundleFits", () => { + const bundle: ThreadMoveBundle = { + title: "Port the parser", + modelSelection: source, + runtimeMode: "full-access", + interactionMode: "default", + createdAt: "2026-01-01T00:00:00.000Z", + messages: [{ role: "user", text: "Port it.", createdAt: "2026-01-01T00:00:00.000Z" }], + }; + const bytes = Buffer.byteLength(JSON.stringify(bundle), "utf8"); + + it("accepts a bundle at the limit and refuses one byte over", () => { + expect(threadMoveBundleFits(bundle, bytes)).toBe(true); + expect(threadMoveBundleFits(bundle, bytes - 1)).toBe(false); + }); +}); diff --git a/apps/server/src/project/ThreadProjectMove.ts b/apps/server/src/project/ThreadProjectMove.ts index 8576f7d56bfb2..0b8f4ab0f54b1 100644 --- a/apps/server/src/project/ThreadProjectMove.ts +++ b/apps/server/src/project/ThreadProjectMove.ts @@ -2,6 +2,9 @@ import { CommandId, EventId, isRuntimeModeAbove, + type ModelSelection, + PROVIDER_SEND_TURN_MAX_FILE_BYTES, + type ProviderInstanceId, type OrchestrationV2AppThread, type OrchestrationV2DomainEvent, type ProjectExportThreadResult, @@ -10,11 +13,12 @@ import { type ProjectImportThreadInput, type ProjectImportThreadResult, type ThreadId, + type ThreadMoveBundle, TurnItemId, } from "@t3tools/contracts"; import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; import { resolveProjectSettings } from "@t3tools/shared/projectSettings"; -import { threadMoveNotice } from "@t3tools/shared/threadMove"; +import { threadMoveLeftBehindList, threadMoveNotice } from "@t3tools/shared/threadMove"; import * as Context from "effect/Context"; import * as SecureRandom from "effect/crypto/SecureRandom"; import * as DateTime from "effect/DateTime"; @@ -23,6 +27,7 @@ import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; +import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; import * as GitWorkflowService from "../git/GitWorkflowService.ts"; import * as EventSink from "../orchestration-v2/EventSink.ts"; import { threadHasUnfinishedWork } from "../orchestration-v2/Orchestrator.ts"; @@ -36,6 +41,35 @@ import * as ManagedProjectFolders from "./ManagedProjectFolders.ts"; import * as ProjectService from "./ProjectService.ts"; const MOVE_EVENT_PREFIX = "thread-machine-move"; +const TOO_LARGE = "This conversation is too large to move."; +const CHANGED = + "It changed after the move started, so it was left active here. Its newest messages aren't in the moved copy."; + +/** The source's own provider when this machine runs it, else the project default when usable. */ +export function movedModelSelection(input: { + readonly source: ModelSelection; + readonly projectDefault: ModelSelection | null; + readonly usable: (instanceId: ProviderInstanceId) => boolean; +}): ModelSelection | null { + if (input.usable(input.source.instanceId)) return input.source; + return input.projectDefault !== null && input.usable(input.projectDefault.instanceId) + ? input.projectDefault + : null; +} + +/** Imports hold bundles to the transcript export's budget, which exports already pass. */ +export function threadMoveBundleFits(bundle: ThreadMoveBundle, maxBytes: number): boolean { + return Buffer.byteLength(JSON.stringify(bundle), "utf8") <= maxBytes; +} + +/** Changes when a run starts, so finishing a move never archives work its export missed. */ +function threadRevision(runs: ReadonlyArray<{ readonly id: string; readonly ordinal: number }>) { + const last = runs.reduce<(typeof runs)[number] | undefined>( + (latest, run) => (latest === undefined || run.ordinal > latest.ordinal ? run : latest), + undefined, + ); + return `${runs.length}:${last?.id ?? ""}`; +} export class ThreadProjectMoveError extends Schema.TaggedError()( "ThreadProjectMoveError", @@ -85,6 +119,7 @@ const make = Effect.gen(function* () { const ids = yield* IdAllocator.IdAllocatorV2; const registry = yield* ProviderAdapterRegistry.ProviderAdapterRegistryV2; const settingsService = yield* ServerSettings.ServerSettingsService; + const environmentIdentity = yield* ServerEnvironment.ServerEnvironmentIdentity; const randomId = (yield* SecureRandom.SecureRandom).uuidV4(); const fail = (reason: string) => (cause: unknown) => @@ -172,12 +207,18 @@ const make = Effect.gen(function* () { reason: "The thread still has work in progress. Finish or stop it first.", }); } - const { projection } = yield* threads - .getThreadSnapshot(threadId) - .pipe(Effect.mapError(fail("Could not read the thread."))); - const thread = projection.thread; + // The transcript export's size preflight, budget and concurrency limit bound the bundle. + const transcript = yield* threads.getThreadTranscript(threadId).pipe( + Effect.provideService(ServerEnvironment.ServerEnvironmentIdentity, environmentIdentity), + Effect.mapError((cause) => + cause._tag === "ThreadTranscriptTooLargeError" + ? new ThreadProjectMoveError({ reason: TOO_LARGE, cause }) + : new ThreadProjectMoveError({ reason: "Could not read the thread.", cause }), + ), + ); + const thread = records.thread; let attachments = 0; - const messages = projection.visibleTurnItems.flatMap(({ item }) => { + const messages = transcript.items.flatMap(({ item }) => { if (item.type === "user_message") attachments += item.attachments.length; if (item.type !== "user_message" && item.type !== "assistant_message") return []; if (item.text.trim() === "") return []; @@ -204,30 +245,40 @@ const make = Effect.gen(function* () { messages, }, leftBehind: { - diffs: projection.runs.length > 0, + diffs: records.runs.length > 0, worktree: thread.worktreePath !== null, attachments, scheduledTasks: tasks.tasks.filter((task) => task.threadId === threadId).length, }, + revision: threadRevision(records.runs), }; }); const importThread: ThreadProjectMove["Service"]["importThread"] = Effect.fn( "ThreadProjectMove.importThread", )(function* (input) { + if (!threadMoveBundleFits(input.bundle, PROVIDER_SEND_TURN_MAX_FILE_BYTES)) { + return yield* new ThreadProjectMoveError({ reason: TOO_LARGE }); + } const project = yield* readTarget(input.projectId); const settings = yield* settingsService.getSettings.pipe( Effect.mapError(fail("Could not read this machine's settings.")), ); const projectSettings = resolveProjectSettings(settings, project.id, project).settings; - // Provider instances are per machine; one this machine lacks falls back to the project default. - const instanceId = input.bundle.modelSelection.instanceId; - const usable = - (yield* registry.list()).includes(instanceId) && - (yield* threads.isProviderInstanceEnabledForProject({ projectId: project.id, instanceId })); - const modelSelection = usable - ? input.bundle.modelSelection - : (projectSettings.defaultModelSelection ?? input.bundle.modelSelection); + // Provider instances are per machine, so the thread may need this project's default. + const usableIds = yield* Effect.filter(yield* registry.list(), (instanceId) => + threads.isProviderInstanceEnabledForProject({ projectId: project.id, instanceId }), + ); + const modelSelection = movedModelSelection({ + source: input.bundle.modelSelection, + projectDefault: projectSettings.defaultModelSelection, + usable: (instanceId) => usableIds.includes(instanceId), + }); + if (modelSelection === null) { + return yield* new ThreadProjectMoveError({ + reason: `This machine can't run the thread's provider (${input.bundle.modelSelection.instanceId}), and ${project.title} has no usable default model. Set up that provider here, or choose a default model for ${project.title}.`, + }); + } const ceiling = settingsService.managedPolicy?.limits?.maxRuntimeMode; const runtimeMode = ceiling !== undefined && isRuntimeModeAbove(input.bundle.runtimeMode, ceiling) @@ -298,7 +349,7 @@ const make = Effect.gen(function* () { nodeId: null, providerThreadId: null, ordinal: input.bundle.messages.length + 1, - message: `Moved from ${input.movedFrom}. Its files and diffs stayed there.`, + message: `Moved from ${input.movedFrom}. ${threadMoveLeftBehindList(input.leftBehind)} stayed there.`, }, }, ]; @@ -309,9 +360,15 @@ const make = Effect.gen(function* () { const finishMove: ThreadProjectMove["Service"]["finishMove"] = Effect.fn( "ThreadProjectMove.finishMove", )(function* (input) { - const { thread, runs } = yield* threads - .getThreadRecords(input.threadId, ["runs"]) + const records = yield* threads + .getThreadRecords(input.threadId, ["runs", "runtimeRequests"]) .pipe(Effect.mapError(fail("Could not read the thread."))); + const { thread, runs } = records; + // A run can start between this check and the archive below; that window is a few + // milliseconds, while the one this closes spans the whole confirmation and import. + if (threadRevision(runs) !== input.revision || threadHasUnfinishedWork(records)) { + return yield* new ThreadProjectMoveError({ reason: CHANGED }); + } const lastRun = runs.reduce<(typeof runs)[number] | undefined>( (latest, run) => (latest === undefined || run.ordinal > latest.ordinal ? run : latest), undefined, diff --git a/apps/web/src/hooks/useThreadActions.ts b/apps/web/src/hooks/useThreadActions.ts index 5312a33e7fa5b..8de6d2a5d5842 100644 --- a/apps/web/src/hooks/useThreadActions.ts +++ b/apps/web/src/hooks/useThreadActions.ts @@ -362,8 +362,8 @@ export async function moveThreadToMachineAndOpen( toastManager.add( stackedThreadToast({ type: "warning", - title: `Moved, but the thread is still active on ${fromMachine}`, - description: `${outcome.archiveError} Archive it there so you don't continue both.`, + title: `Moved, but the original is still active on ${fromMachine}`, + description: `${outcome.archiveError} The moved copy is on ${toMachine}.`, }), ); } diff --git a/docs/user/thread-sidebar.md b/docs/user/thread-sidebar.md index 04cccc383ccbd..c3567191cf049 100644 --- a/docs/user/thread-sidebar.md +++ b/docs/user/thread-sidebar.md @@ -72,6 +72,10 @@ session there with that history. Files, diffs, the worktree, attachments and scheduled tasks stay on the first machine, where the old thread is archived. To go back, unarchive it there, or move the new thread back the same way. +The other machine must be able to run the thread's provider, or its project needs a +default model. If the thread gets a new message while it moves, the original stays +active, because the copy doesn't have that message. + ### Start in the background In a desktop browser or the desktop app, press `Cmd+Enter` on macOS or `Ctrl+Enter` diff --git a/packages/client-runtime/src/state/models.ts b/packages/client-runtime/src/state/models.ts index 88009a242eccc..1cc0fcccf29f4 100644 --- a/packages/client-runtime/src/state/models.ts +++ b/packages/client-runtime/src/state/models.ts @@ -27,11 +27,15 @@ export interface EnvironmentProject extends OrchestrationProjectShell { } /** The live projects on `environmentId` a thread can move into: all but No project. */ -export function threadMoveProjects( - projects: ReadonlyArray, +export function threadMoveProjects< + P extends Pick & { + readonly archivedAt?: EnvironmentProject["archivedAt"]; + }, +>( + projects: ReadonlyArray

, environmentId: EnvironmentId, scratchWorkspaceRoot: string | null | undefined, -): ReadonlyArray { +): ReadonlyArray

{ return projects.filter( (project) => project.environmentId === environmentId && diff --git a/packages/client-runtime/src/state/threadMachineMove.test.ts b/packages/client-runtime/src/state/threadMachineMove.test.ts index 17a9c815864f7..f1da27a262092 100644 --- a/packages/client-runtime/src/state/threadMachineMove.test.ts +++ b/packages/client-runtime/src/state/threadMachineMove.test.ts @@ -10,7 +10,11 @@ import { AsyncResult, AtomRegistry } from "effect/reactivity"; import { describe, expect, it } from "vite-plus/test"; import type { AtomCommand } from "./runtime.ts"; -import { moveThreadToMachine, type ThreadMachineMoveCommands } from "./threadMachineMove.ts"; +import { + moveThreadToMachine, + threadMachineMoveTargets, + type ThreadMachineMoveCommands, +} from "./threadMachineMove.ts"; const source = { environmentId: EnvironmentId.make("laptop"), threadId: ThreadId.make("old") }; const target = { environmentId: EnvironmentId.make("vps"), projectId: ProjectId.make("api") }; @@ -24,11 +28,12 @@ const exported: ProjectExportThreadResult = { messages: [{ role: "user", text: "Port it.", createdAt: "2026-01-01T00:00:00.000Z" }], }, leftBehind: { diffs: true, worktree: false, attachments: 0, scheduledTasks: 0 }, + revision: "1:run", }; type Step = "export" | "import" | "finish"; -function setup(failing: ReadonlySet) { +function setup(failing: ReadonlySet, exportGate: Promise = Promise.resolve()) { const calls: Array<{ readonly step: Step; readonly environmentId: string }> = []; const command = ( step: Step, @@ -41,6 +46,7 @@ function setup(failing: ReadonlySet) { label: step, run: async (_registry, { environmentId }) => { calls.push({ step, environmentId }); + if (step === "export") await exportGate; return failing.has(step) ? AsyncResult.failure(Cause.fail(new Error(`${step} failed`))) : AsyncResult.success(value); @@ -102,4 +108,38 @@ describe("moveThreadToMachine", () => { archiveError: "finish failed", }); }); + + it("ignores a second move of the same thread while one is in flight", async () => { + let release = () => {}; + const { calls, move } = setup(new Set(), new Promise((resolve) => (release = resolve))); + const first = move(); + expect(await move()).toEqual({ _tag: "Cancelled" }); + release(); + expect((await first)._tag).toBe("Moved"); + expect(calls.filter((call) => call.step === "import")).toHaveLength(1); + }); +}); + +describe("threadMachineMoveTargets", () => { + const laptop = EnvironmentId.make("laptop"); + const vps = EnvironmentId.make("vps"); + const supported = { environment: { capabilities: { threadMoveToMachine: true } } }; + const targets = (canOperate: ReadonlySet) => + threadMachineMoveTargets({ + sourceEnvironmentId: laptop, + connectedEnvironmentIds: [laptop, vps], + serverConfigs: new Map([ + [laptop, supported], + [vps, supported], + ]), + projects: [{ id: ProjectId.make("api"), environmentId: vps, workspaceRoot: "/api" }], + labelOf: (environmentId) => environmentId, + canOperate: (environmentId) => canOperate.has(environmentId), + }).map((machine) => machine.environmentId); + + it("lists machines only when this connection can change threads on both ends", () => { + expect(targets(new Set(["laptop", "vps"]))).toEqual(["vps"]); + expect(targets(new Set(["vps"]))).toEqual([]); + expect(targets(new Set(["laptop"]))).toEqual([]); + }); }); diff --git a/packages/client-runtime/src/state/threadMachineMove.ts b/packages/client-runtime/src/state/threadMachineMove.ts index 2304cdb4cbb97..f0353cd5be3d5 100644 --- a/packages/client-runtime/src/state/threadMachineMove.ts +++ b/packages/client-runtime/src/state/threadMachineMove.ts @@ -6,11 +6,11 @@ import type { ProjectImportThreadInput, ProjectImportThreadResult, ScopedThreadRef, - ServerConfig, ThreadId, } from "@t3tools/contracts"; import type { AtomRegistry } from "effect/reactivity"; +import { scopedThreadKey } from "../environment/scoped.ts"; import { type EnvironmentProject, threadMoveProjects } from "./models.ts"; import { type AtomCommand, @@ -45,24 +45,36 @@ export type ThreadMachineMoveOutcome = readonly archiveError: string | null; }; -export interface ThreadMachineMoveTarget { +export interface ThreadMachineMoveTarget

{ readonly environmentId: EnvironmentId; readonly label: string; - readonly projects: ReadonlyArray; + readonly projects: ReadonlyArray

; } -/** The other connected machines a thread can move to, each with its projects. Both ends must support it. */ -export function threadMachineMoveTargets(input: { +interface MoveServerConfig { + readonly scratchWorkspaceRoot?: string | undefined; + readonly environment: { readonly capabilities: { readonly threadMoveToMachine?: boolean } }; +} + +/** + * The other connected machines a thread can move to, each with its projects. Both ends must + * support it, and this connection must be able to change threads on both. + */ +export function threadMachineMoveTargets< + P extends Parameters[0][number], +>(input: { readonly sourceEnvironmentId: EnvironmentId; readonly connectedEnvironmentIds: ReadonlyArray; - readonly serverConfigs: ReadonlyMap; - readonly projects: ReadonlyArray; + readonly serverConfigs: ReadonlyMap; + readonly projects: ReadonlyArray

; readonly labelOf: (environmentId: EnvironmentId) => string | undefined; readonly canOperate: (environmentId: EnvironmentId) => boolean; -}): ReadonlyArray { +}): ReadonlyArray> { const supports = (environmentId: EnvironmentId) => input.serverConfigs.get(environmentId)?.environment.capabilities.threadMoveToMachine === true; - if (!supports(input.sourceEnvironmentId)) return []; + if (!supports(input.sourceEnvironmentId) || !input.canOperate(input.sourceEnvironmentId)) { + return []; + } return input.connectedEnvironmentIds.flatMap((environmentId) => { const label = input.labelOf(environmentId); if ( @@ -88,6 +100,8 @@ function failureMessage(result: AtomCommandResult): string { return error instanceof Error && error.message !== "" ? error.message : "Try again."; } +const movesInFlight = new Set(); + /** * Copies the thread's conversation to a project on another machine, then archives it here. The * client carries the bundle over connections it already has, so the servers never trust each @@ -103,6 +117,20 @@ export async function moveThreadToMachine(input: { readonly targetLabel: string; readonly confirm: (exported: ProjectExportThreadResult) => Promise; }): Promise { + // A second pick while one runs would import the conversation twice. + const key = scopedThreadKey(input.source); + if (movesInFlight.has(key)) return { _tag: "Cancelled" }; + movesInFlight.add(key); + try { + return await moveOnce(input); + } finally { + movesInFlight.delete(key); + } +} + +async function moveOnce( + input: Parameters[0], +): Promise { const { registry, commands, source, target } = input; const settled = (result: AtomCommandResult): ThreadMachineMoveOutcome => isAtomCommandInterrupted(result) @@ -122,6 +150,7 @@ export async function moveThreadToMachine(input: { projectId: target.projectId, bundle: exported.value.bundle, movedFrom: input.sourceLabel, + leftBehind: exported.value.leftBehind, }, }); if (imported._tag !== "Success") return settled(imported); @@ -129,7 +158,11 @@ export async function moveThreadToMachine(input: { const finished = await commands.finishThreadMove.run(registry, { environmentId: source.environmentId, - input: { threadId: source.threadId, movedTo: input.targetLabel }, + input: { + threadId: source.threadId, + movedTo: input.targetLabel, + revision: exported.value.revision, + }, }); return { _tag: "Moved", diff --git a/packages/contracts/src/project.ts b/packages/contracts/src/project.ts index b9ab2200e6970..9ad1e2630efe6 100644 --- a/packages/contracts/src/project.ts +++ b/packages/contracts/src/project.ts @@ -583,15 +583,19 @@ export type ThreadMoveBundle = typeof ThreadMoveBundle.Type; export const ProjectExportThreadInput = Schema.Struct({ threadId: ThreadId }); export type ProjectExportThreadInput = typeof ProjectExportThreadInput.Type; +/** What a move leaves on the source environment, so messages name only what applies. */ +export const ThreadMoveLeftBehind = Schema.Struct({ + diffs: Schema.Boolean, + worktree: Schema.Boolean, + attachments: NonNegativeInt, + scheduledTasks: NonNegativeInt, +}); + export const ProjectExportThreadResult = Schema.Struct({ bundle: ThreadMoveBundle, - /** What stays on this environment, so the confirmation names only what applies. */ - leftBehind: Schema.Struct({ - diffs: Schema.Boolean, - worktree: Schema.Boolean, - attachments: NonNegativeInt, - scheduledTasks: NonNegativeInt, - }), + leftBehind: ThreadMoveLeftBehind, + /** The thread's runs at export; finishing the move refuses once a new one has started. */ + revision: Schema.String, }); export type ProjectExportThreadResult = typeof ProjectExportThreadResult.Type; @@ -600,6 +604,7 @@ export const ProjectImportThreadInput = Schema.Struct({ bundle: ThreadMoveBundle, /** The source machine as the user knows it, for the new thread's notice. */ movedFrom: TrimmedNonEmptyString, + leftBehind: ThreadMoveLeftBehind, }); export type ProjectImportThreadInput = typeof ProjectImportThreadInput.Type; @@ -610,6 +615,8 @@ export const ProjectFinishThreadMoveInput = Schema.Struct({ threadId: ThreadId, /** Where the conversation went, as the user knows it, for the archived thread's notice. */ movedTo: TrimmedNonEmptyString, + /** From the export the target imported, so newer work is never archived unseen. */ + revision: Schema.String, }); export type ProjectFinishThreadMoveInput = typeof ProjectFinishThreadMoveInput.Type; diff --git a/packages/shared/src/threadMove.ts b/packages/shared/src/threadMove.ts index 397498b0e8a99..3da835d59091e 100644 --- a/packages/shared/src/threadMove.ts +++ b/packages/shared/src/threadMove.ts @@ -8,19 +8,15 @@ export function threadMoveNotice(input: { : `The conversation moves with it, and the agent works in ${input.projectTitle}'s folder from the next message. Earlier diffs open while their original folder exists, and files from earlier turns can't be restored.`; } -/** What moving a thread to another machine carries and leaves behind; names only what applies. */ -export function threadMachineMoveNotice(input: { - readonly fromMachine: string; - readonly toMachine: string; - readonly projectTitle: string; - readonly leftBehind: { - readonly diffs: boolean; - readonly worktree: boolean; - readonly attachments: number; - readonly scheduledTasks: number; - }; -}): string { - const { leftBehind } = input; +interface ThreadMoveLeftBehind { + readonly diffs: boolean; + readonly worktree: boolean; + readonly attachments: number; + readonly scheduledTasks: number; +} + +/** "Files, diffs and 2 attachments": what a machine move leaves on the source, naming only what applies. */ +export function threadMoveLeftBehindList(leftBehind: ThreadMoveLeftBehind): string { const count = (n: number, noun: string) => `${n} ${noun}${n === 1 ? "" : "s"}`; const stays = [ "Files", @@ -29,7 +25,15 @@ export function threadMachineMoveNotice(input: { ...(leftBehind.attachments > 0 ? [count(leftBehind.attachments, "attachment")] : []), ...(leftBehind.scheduledTasks > 0 ? [count(leftBehind.scheduledTasks, "scheduled task")] : []), ]; - const list = - stays.length === 1 ? stays[0] : `${stays.slice(0, -1).join(", ")} and ${stays.at(-1)}`; - return `The conversation moves to ${input.projectTitle} on ${input.toMachine} and continues in a new session there. ${list} stay on ${input.fromMachine}, where this thread is archived. Unarchive it to come back.`; + return stays.length === 1 ? "Files" : `${stays.slice(0, -1).join(", ")} and ${stays.at(-1)}`; +} + +/** What moving a thread to another machine carries and leaves behind. */ +export function threadMachineMoveNotice(input: { + readonly fromMachine: string; + readonly toMachine: string; + readonly projectTitle: string; + readonly leftBehind: ThreadMoveLeftBehind; +}): string { + return `The conversation moves to ${input.projectTitle} on ${input.toMachine} and continues in a new session there. ${threadMoveLeftBehindList(input.leftBehind)} stay on ${input.fromMachine}, where this thread is archived. Unarchive it to come back.`; } From 71f0569ab914b749969b8e1b7a2e116c5e040e5c Mon Sep 17 00:00:00 2001 From: Batch Processor <46352227+batchema@users.noreply.github.com> Date: Sun, 15 Nov 2026 01:22:48 +0100 Subject: [PATCH 18/20] fix(server): a retried run that completes mid-move keeps the source active Retrying a failed preparation reuses the run's id and ordinal, so the move revision (run count and newest run) stayed the same while the retry added messages the export missed, and finish archived them. The revision now also carries the latest run completion. Co-Authored-By: Claude Opus 5.5 --- .../src/project/ThreadProjectMove.test.ts | 13 ++++++++++- apps/server/src/project/ThreadProjectMove.ts | 23 +++++++++++++------ 2 files changed, 28 insertions(+), 8 deletions(-) diff --git a/apps/server/src/project/ThreadProjectMove.test.ts b/apps/server/src/project/ThreadProjectMove.test.ts index c422b3ccab1a0..6975046951f87 100644 --- a/apps/server/src/project/ThreadProjectMove.test.ts +++ b/apps/server/src/project/ThreadProjectMove.test.ts @@ -1,7 +1,9 @@ import { type ModelSelection, ProviderInstanceId, type ThreadMoveBundle } from "@t3tools/contracts"; import { describe, expect, it } from "vite-plus/test"; -import { movedModelSelection, threadMoveBundleFits } from "./ThreadProjectMove.ts"; +import * as DateTime from "effect/DateTime"; + +import { movedModelSelection, threadMoveBundleFits, threadRevision } from "./ThreadProjectMove.ts"; const source = { instanceId: ProviderInstanceId.make("source-only"), model: "s" }; const fallback = { instanceId: ProviderInstanceId.make("codex"), model: "d" }; @@ -59,3 +61,12 @@ describe("threadMoveBundleFits", () => { expect(threadMoveBundleFits(bundle, bytes - 1)).toBe(false); }); }); + +describe("threadRevision", () => { + it("changes when a retried run completes under the same id", () => { + const run = { id: "run-1", ordinal: 1, completedAt: null }; + expect( + threadRevision([{ ...run, completedAt: DateTime.makeUnsafe("2026-01-01T00:00:00Z") }]), + ).not.toBe(threadRevision([run])); + }); +}); diff --git a/apps/server/src/project/ThreadProjectMove.ts b/apps/server/src/project/ThreadProjectMove.ts index 0b8f4ab0f54b1..d57494ea5aa3c 100644 --- a/apps/server/src/project/ThreadProjectMove.ts +++ b/apps/server/src/project/ThreadProjectMove.ts @@ -62,13 +62,22 @@ export function threadMoveBundleFits(bundle: ThreadMoveBundle, maxBytes: number) return Buffer.byteLength(JSON.stringify(bundle), "utf8") <= maxBytes; } -/** Changes when a run starts, so finishing a move never archives work its export missed. */ -function threadRevision(runs: ReadonlyArray<{ readonly id: string; readonly ordinal: number }>) { - const last = runs.reduce<(typeof runs)[number] | undefined>( - (latest, run) => (latest === undefined || run.ordinal > latest.ordinal ? run : latest), - undefined, - ); - return `${runs.length}:${last?.id ?? ""}`; +/** Changes when a run starts or any run, retries included, completes, so finish never archives work export missed. */ +export function threadRevision( + runs: ReadonlyArray<{ + readonly id: string; + readonly ordinal: number; + readonly completedAt: DateTime.Utc | null; + }>, +) { + let newest: (typeof runs)[number] | undefined; + let lastCompletedAt = 0; + for (const run of runs) { + if (newest === undefined || run.ordinal > newest.ordinal) newest = run; + if (run.completedAt !== null) + lastCompletedAt = Math.max(lastCompletedAt, DateTime.toEpochMillis(run.completedAt)); + } + return `${runs.length}:${newest?.id ?? ""}:${lastCompletedAt}`; } export class ThreadProjectMoveError extends Schema.TaggedError()( From c71ef14bf6ccb4e0c4d0c6e2cf199e93893b0d67 Mon Sep 17 00:00:00 2001 From: Batch Processor <46352227+batchema@users.noreply.github.com> Date: Sun, 15 Nov 2026 01:28:52 +0100 Subject: [PATCH 19/20] fix(server): provider subagent threads can't be moved to another machine Provider-native subagents receive messages outside runs, so the move revision can't tell when they change and finish could archive messages the export missed. They stay with the thread that started them. Co-Authored-By: Claude Opus 5.5 --- .../src/orchestration-v2/runtimeLayer.test.ts | 25 +++++++++++++++++++ apps/server/src/project/ThreadProjectMove.ts | 7 ++++++ 2 files changed, 32 insertions(+) diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index 95e0e85551433..87ad721220e64 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -10451,6 +10451,31 @@ it.layer(layerThreadProjectMoveTest)("moving a thread to another project", (it) assert.isNull((yield* orchestrator.getThreadRecords(raced.threadId, [])).thread.archivedAt); const busy = yield* service.exportThread(raced.threadId).pipe(Effect.flip); assert.equal(busy.message, "The thread still has work in progress. Finish or stop it first."); + + // Native subagents get messages outside runs, which the revision can't track. + const subagentId = ThreadId.make("machine-move-native-subagent"); + yield* (yield* EventSink.EventSinkV2).write({ + events: [ + { + id: EventId.make("machine-move-native-subagent-created"), + type: "thread.created", + threadId: subagentId, + occurredAt: yield* DateTime.now, + payload: { + ...imported, + id: subagentId, + creationSource: "provider", + lineage: { + parentThreadId: threadId, + rootThreadId: threadId, + relationshipToParent: "subagent", + }, + }, + }, + ], + }); + const subagent = yield* service.exportThread(subagentId).pipe(Effect.flip); + assert.equal(subagent.message, "Subagent threads stay with the thread that started them."); }), ); }); diff --git a/apps/server/src/project/ThreadProjectMove.ts b/apps/server/src/project/ThreadProjectMove.ts index d57494ea5aa3c..30553ecb7384f 100644 --- a/apps/server/src/project/ThreadProjectMove.ts +++ b/apps/server/src/project/ThreadProjectMove.ts @@ -1,6 +1,7 @@ import { CommandId, EventId, + isProviderNativeSubagentThread, isRuntimeModeAbove, type ModelSelection, PROVIDER_SEND_TURN_MAX_FILE_BYTES, @@ -211,6 +212,12 @@ const make = Effect.gen(function* () { const records = yield* threads .getThreadRecords(threadId, ["runs", "runtimeRequests"]) .pipe(Effect.mapError(fail("Could not read the thread."))); + // Their messages arrive outside runs, so the move revision can't see them change. + if (isProviderNativeSubagentThread(records.thread)) { + return yield* new ThreadProjectMoveError({ + reason: "Subagent threads stay with the thread that started them.", + }); + } if (threadHasUnfinishedWork(records)) { return yield* new ThreadProjectMoveError({ reason: "The thread still has work in progress. Finish or stop it first.", From 0189f6c3efa50efe02a41a2a324b78fc07a0eed3 Mon Sep 17 00:00:00 2001 From: batchema Date: Thu, 19 Nov 2026 22:58:02 -0500 Subject: [PATCH 20/20] feat(mobile): working threads show above the inbox The Working section sat at the bottom of the thread list, below every stopped, done, or blocked thread. On iOS and Android it now sits right under pinned threads. A plain Inbox label marks where the rest of the list starts, so those rows no longer read as part of Working. Folding, the inbox order, and snoozed and settled stay as they were. Closes #17 --- apps/mobile/src/features/home/HomeScreen.tsx | 4 +++ .../threads/ThreadNavigationSidebar.tsx | 3 ++ .../features/threads/thread-list-v2-items.tsx | 12 +++++++ .../src/features/threads/threadListV2.test.ts | 16 +++++++-- .../src/features/threads/threadListV2.ts | 34 +++++++++++++++---- .../src/features/threads/useThreadListV2.ts | 1 + apps/mobile/src/i18n/translations/de.json | 1 + apps/mobile/src/i18n/translations/en.json | 1 + apps/mobile/src/i18n/translations/es.json | 1 + apps/mobile/src/i18n/translations/fr.json | 1 + apps/mobile/src/i18n/translations/ja.json | 1 + apps/mobile/src/i18n/translations/ko.json | 1 + apps/mobile/src/i18n/translations/pt-BR.json | 1 + apps/mobile/src/i18n/translations/ru.json | 1 + apps/mobile/src/i18n/translations/sv.json | 1 + apps/mobile/src/i18n/translations/zh.json | 1 + docs/user/thread-sidebar.md | 5 +-- 17 files changed, 74 insertions(+), 11 deletions(-) diff --git a/apps/mobile/src/features/home/HomeScreen.tsx b/apps/mobile/src/features/home/HomeScreen.tsx index f1b6469cd7cf0..064503072d5ae 100644 --- a/apps/mobile/src/features/home/HomeScreen.tsx +++ b/apps/mobile/src/features/home/HomeScreen.tsx @@ -73,6 +73,7 @@ import { threadListEnvironmentsAtom } from "../../state/presentation"; import type { PendingNewTask } from "../../state/use-pending-new-tasks"; import { useQueuedThreadKeys } from "../../state/use-thread-outbox"; import { + ThreadListV2InboxHeader, ThreadListV2PendingRow, ThreadListV2Row, ThreadListV2SettledShelfHeader, @@ -507,6 +508,9 @@ export function HomeScreen(props: HomeScreenProps) { /> ); } + if (item.type === "v2-inbox-header") { + return ; + } if (item.type === "v2-snoozed-shelf") { return ( ); + case "v2-inbox-header": + return ; case "v2-snoozed-shelf": return ( ; }); +export const ThreadListV2InboxHeader = memo(function ThreadListV2InboxHeader(props: { + readonly pane?: "screen" | "sidebar"; +}) { + const gt = useGT(); + return ( + + ); +}); + export const ThreadListV2SnoozedShelfHeader = memo(function ThreadListV2SnoozedShelfHeader( props: ThreadListV2ShelfHeaderProps, ) { diff --git a/apps/mobile/src/features/threads/threadListV2.test.ts b/apps/mobile/src/features/threads/threadListV2.test.ts index 16ef19a32993f..c77451eaf76fd 100644 --- a/apps/mobile/src/features/threads/threadListV2.test.ts +++ b/apps/mobile/src/features/threads/threadListV2.test.ts @@ -1751,11 +1751,13 @@ describe("Working section beta", () => { "finished-early", ]); expect(layout.workingCount).toBe(1); - expect(layout.workingShelfHeaderIndex).toBe(4); + expect(layout.workingShelfHeaderIndex).toBe(1); + expect(layout.inboxHeaderIndex).toBe(1); const off = build({ workingShelfEnabled: false }); expect(ids(off)).toContain("working"); expect(off.workingCount).toBe(0); + expect(off.inboxHeaderIndex).toBeNull(); }); it("keeps an inactive row in Working during the shared grace and returns it on expiry", () => { @@ -1794,11 +1796,16 @@ describe("Working section beta", () => { expect(ids(layout).slice(1)).toEqual(["finished-early", "finished-late", "asks-approval"]); }); - it("places the shelf after queued tasks and before snoozed and settled threads", () => { + it("places the shelf above the inbox, after queued tasks and pinned threads", () => { const layout = buildThreadListV2Items({ threads: [ makeThread({ id: ThreadId.make("active"), title: "active" }), makeThread({ id: ThreadId.make("working"), title: "working", runtime: running }), + makeThread({ + id: ThreadId.make("pinned"), + title: "pinned", + pinnedAt: "2026-06-01T00:00:00.000Z", + }), makeThread({ id: ThreadId.make("snoozed"), title: "snoozed", @@ -1826,6 +1833,7 @@ describe("Working section beta", () => { workingCount: layout.workingCount, workingShelfExpanded: true, workingShelfHeaderIndex: layout.workingShelfHeaderIndex, + inboxHeaderIndex: layout.inboxHeaderIndex, snoozedCount: layout.snoozedCount, snoozedShelfExpanded: true, snoozedShelfHeaderIndex: layout.snoozedShelfHeaderIndex, @@ -1842,9 +1850,11 @@ describe("Working section beta", () => { ), ).toEqual([ "queued", - "active", + "pinned", "v2-working-shelf", "working", + "v2-inbox-header", + "active", "v2-snoozed-shelf", "snoozed", "v2-settled-shelf", diff --git a/apps/mobile/src/features/threads/threadListV2.ts b/apps/mobile/src/features/threads/threadListV2.ts index b8029d3b0b189..a2a6bdd51dfd2 100644 --- a/apps/mobile/src/features/threads/threadListV2.ts +++ b/apps/mobile/src/features/threads/threadListV2.ts @@ -424,6 +424,8 @@ export interface ThreadListV2Layout { readonly listedSettledThreads: ReadonlyArray; readonly workingCount: number; readonly workingShelfHeaderIndex: number | null; + /** Only set below the Working shelf, which would otherwise read as owning these rows. */ + readonly inboxHeaderIndex: number | null; readonly snoozedCount: number; readonly snoozedShelfHeaderIndex: number | null; readonly settledCount: number; @@ -464,6 +466,11 @@ export interface ThreadListV2WorkingShelfListItem { readonly disabled: boolean; } +export interface ThreadListV2InboxHeaderListItem { + readonly type: "v2-inbox-header"; + readonly key: "v2-inbox-header"; +} + export interface ThreadListV2SnoozedShelfListItem { readonly type: "v2-snoozed-shelf"; readonly key: "v2-snoozed-shelf"; @@ -485,6 +492,7 @@ export type ThreadListV2ListItem = | ThreadListV2ThreadListItem | ThreadListV2PendingListItem | ThreadListV2WorkingShelfListItem + | ThreadListV2InboxHeaderListItem | ThreadListV2SnoozedShelfListItem | ThreadListV2SettledShelfListItem; @@ -495,6 +503,7 @@ export function isThreadListV2ListItem(value: { value.type === "v2-thread" || value.type === "v2-pending" || value.type === "v2-working-shelf" || + value.type === "v2-inbox-header" || value.type === "v2-snoozed-shelf" || value.type === "v2-settled-shelf" ); @@ -538,6 +547,8 @@ export function threadListV2ListItemsAreEqual( previous.expanded === item.expanded && previous.disabled === item.disabled ); + case "v2-inbox-header": + return previous.type === "v2-inbox-header"; case "v2-snoozed-shelf": return ( previous.type === "v2-snoozed-shelf" && @@ -584,6 +595,7 @@ export function buildThreadListV2ListItems(input: { readonly workingCount?: number; readonly workingShelfExpanded?: boolean; readonly workingShelfHeaderIndex?: number | null; + readonly inboxHeaderIndex?: number | null; readonly snoozedCount?: number; readonly snoozedShelfExpanded?: boolean; readonly snoozedShelfHeaderIndex?: number | null; @@ -639,14 +651,16 @@ export function buildThreadListV2ListItems(input: { })); const workingCount = input.workingCount ?? 0; const workingShelfHeaderIndex = input.workingShelfHeaderIndex ?? null; + const inboxHeaderIndex = input.inboxHeaderIndex ?? null; const snoozedCount = input.snoozedCount ?? 0; const snoozedShelfHeaderIndex = input.snoozedShelfHeaderIndex ?? null; const settledCount = input.settledCount ?? 0; const settledShelfHeaderIndex = input.settledShelfHeaderIndex ?? null; const snoozedEnd = settledShelfHeaderIndex ?? threadItems.length; - const workingEnd = snoozedShelfHeaderIndex ?? snoozedEnd; - const activeEnd = workingShelfHeaderIndex ?? workingEnd; - const result: ThreadListV2ListItem[] = [...pendingItems, ...threadItems.slice(0, activeEnd)]; + const inboxEnd = snoozedShelfHeaderIndex ?? snoozedEnd; + const workingEnd = inboxHeaderIndex ?? inboxEnd; + const pinnedEnd = workingShelfHeaderIndex ?? workingEnd; + const result: ThreadListV2ListItem[] = [...pendingItems, ...threadItems.slice(0, pinnedEnd)]; const shelfDisabled = input.shelfPreferencesLoading === true; if (workingShelfHeaderIndex !== null && workingCount > 0) { result.push({ @@ -658,6 +672,10 @@ export function buildThreadListV2ListItems(input: { }); result.push(...threadItems.slice(workingShelfHeaderIndex, workingEnd)); } + if (inboxHeaderIndex !== null) { + result.push({ type: "v2-inbox-header", key: "v2-inbox-header" }); + result.push(...threadItems.slice(inboxHeaderIndex, inboxEnd)); + } if (snoozedShelfHeaderIndex !== null && snoozedCount > 0) { result.push({ type: "v2-snoozed-shelf", @@ -852,6 +870,7 @@ export function buildThreadListV2Items(input: { listedSettledThreads: [], workingCount: 0, workingShelfHeaderIndex: null, + inboxHeaderIndex: null, snoozedCount: 0, snoozedShelfHeaderIndex: null, settledCount: 0, @@ -922,7 +941,8 @@ export function buildThreadListV2Items(input: { isLast: false, }); } - for (const thread of orderedActive) { + const workingShelfHeaderIndex = orderedWorking.length > 0 ? items.length : null; + for (const thread of visibleWorking) { items.push({ thread, variant: "card", @@ -932,8 +952,9 @@ export function buildThreadListV2Items(input: { isLast: false, }); } - const workingShelfHeaderIndex = orderedWorking.length > 0 ? items.length : null; - for (const thread of visibleWorking) { + const inboxHeaderIndex = + workingShelfHeaderIndex !== null && orderedActive.length > 0 ? items.length : null; + for (const thread of orderedActive) { items.push({ thread, variant: "card", @@ -975,6 +996,7 @@ export function buildThreadListV2Items(input: { listedSettledThreads: listedSettled, workingCount: orderedWorking.length, workingShelfHeaderIndex, + inboxHeaderIndex, snoozedCount: orderedSnoozed.length, snoozedShelfHeaderIndex, settledCount: settledTotal, diff --git a/apps/mobile/src/features/threads/useThreadListV2.ts b/apps/mobile/src/features/threads/useThreadListV2.ts index 3322dd3bd7ca3..3014e0c527813 100644 --- a/apps/mobile/src/features/threads/useThreadListV2.ts +++ b/apps/mobile/src/features/threads/useThreadListV2.ts @@ -218,6 +218,7 @@ export function useThreadListV2(input: { workingCount: layout.workingCount, workingShelfExpanded: input.workingShelfExpanded, workingShelfHeaderIndex: layout.workingShelfHeaderIndex, + inboxHeaderIndex: layout.inboxHeaderIndex, snoozedCount: layout.snoozedCount, snoozedShelfExpanded: input.snoozedShelfExpanded, snoozedShelfHeaderIndex: layout.snoozedShelfHeaderIndex, diff --git a/apps/mobile/src/i18n/translations/de.json b/apps/mobile/src/i18n/translations/de.json index d24ed25c753b3..e059824849396 100644 --- a/apps/mobile/src/i18n/translations/de.json +++ b/apps/mobile/src/i18n/translations/de.json @@ -4587,6 +4587,7 @@ "905197486607072f": "Verwerfen", "02c0ae493e689f90": "Ziel", "13300e8565fbd665": "{label} ({count})", + "8327da16dcfdb504": "Eingang", "694e089caefce25f": "{count, plural, one {{count} weiteren erledigten Thread anzeigen} other {{count} weitere erledigte Threads anzeigen}}", "ece9e2869077cbb6": "{title} verwerfen", "306a6f95ad9d52f7": "Nicht gesendet", diff --git a/apps/mobile/src/i18n/translations/en.json b/apps/mobile/src/i18n/translations/en.json index 6ff441d8934e5..45228f2d24170 100644 --- a/apps/mobile/src/i18n/translations/en.json +++ b/apps/mobile/src/i18n/translations/en.json @@ -4588,6 +4588,7 @@ "905197486607072f": "Discard", "02c0ae493e689f90": "Goal", "13300e8565fbd665": "{label} ({count})", + "8327da16dcfdb504": "Inbox", "694e089caefce25f": "{count, plural, one {Show {count} more settled threads} other {Show {count} more settled threads}}", "ece9e2869077cbb6": "Discard {title}", "306a6f95ad9d52f7": "Unsent", diff --git a/apps/mobile/src/i18n/translations/es.json b/apps/mobile/src/i18n/translations/es.json index 2ff6bc42a906b..58267a00da30e 100644 --- a/apps/mobile/src/i18n/translations/es.json +++ b/apps/mobile/src/i18n/translations/es.json @@ -4580,6 +4580,7 @@ "905197486607072f": "Descartar", "02c0ae493e689f90": "Objetivo", "13300e8565fbd665": "{label} ({count})", + "8327da16dcfdb504": "Bandeja de entrada", "694e089caefce25f": "{count, plural, one {Mostrar {count} hilo resuelto más} other {Mostrar {count} hilos resueltos más}}", "ece9e2869077cbb6": "Descartar {title}", "306a6f95ad9d52f7": "Sin enviar", diff --git a/apps/mobile/src/i18n/translations/fr.json b/apps/mobile/src/i18n/translations/fr.json index d0196c74abe8f..0533235873bb2 100644 --- a/apps/mobile/src/i18n/translations/fr.json +++ b/apps/mobile/src/i18n/translations/fr.json @@ -4581,6 +4581,7 @@ "905197486607072f": "Abandonner", "02c0ae493e689f90": "Objectif", "13300e8565fbd665": "{label} ({count})", + "8327da16dcfdb504": "Réception", "694e089caefce25f": "{count, plural, one {Afficher {count} autre fil clos} other {Afficher {count} autres fils clos}}", "ece9e2869077cbb6": "Supprimer {title}", "306a6f95ad9d52f7": "Non envoyées", diff --git a/apps/mobile/src/i18n/translations/ja.json b/apps/mobile/src/i18n/translations/ja.json index 59ece0d4a7c6a..84a99597d00f7 100644 --- a/apps/mobile/src/i18n/translations/ja.json +++ b/apps/mobile/src/i18n/translations/ja.json @@ -4562,6 +4562,7 @@ "905197486607072f": "破棄", "02c0ae493e689f90": "ゴール", "13300e8565fbd665": "{label} ({count})", + "8327da16dcfdb504": "受信トレイ", "694e089caefce25f": "{count, plural, other {対応済みのスレッドをさらに {count} 件表示}}", "ece9e2869077cbb6": "{title} を破棄", "306a6f95ad9d52f7": "未送信", diff --git a/apps/mobile/src/i18n/translations/ko.json b/apps/mobile/src/i18n/translations/ko.json index 803c33c76b6fe..29bc9ad3a829d 100644 --- a/apps/mobile/src/i18n/translations/ko.json +++ b/apps/mobile/src/i18n/translations/ko.json @@ -4567,6 +4567,7 @@ "905197486607072f": "삭제", "02c0ae493e689f90": "목표", "13300e8565fbd665": "{label}({count})", + "8327da16dcfdb504": "수신함", "694e089caefce25f": "{count, plural, other {정리된 스레드 {count}개 더 보기}}", "ece9e2869077cbb6": "{title} 삭제", "306a6f95ad9d52f7": "보내지 않음", diff --git a/apps/mobile/src/i18n/translations/pt-BR.json b/apps/mobile/src/i18n/translations/pt-BR.json index 877711ada0340..83d359e9147ab 100644 --- a/apps/mobile/src/i18n/translations/pt-BR.json +++ b/apps/mobile/src/i18n/translations/pt-BR.json @@ -4581,6 +4581,7 @@ "905197486607072f": "Descartar", "02c0ae493e689f90": "Meta", "13300e8565fbd665": "{label} ({count})", + "8327da16dcfdb504": "Caixa de entrada", "694e089caefce25f": "{count, plural, one {Mostrar mais {count} thread concluída} other {Mostrar mais {count} threads concluídas}}", "ece9e2869077cbb6": "Descartar {title}", "306a6f95ad9d52f7": "Não enviadas", diff --git a/apps/mobile/src/i18n/translations/ru.json b/apps/mobile/src/i18n/translations/ru.json index 06a437480350e..a53adf1bdab91 100644 --- a/apps/mobile/src/i18n/translations/ru.json +++ b/apps/mobile/src/i18n/translations/ru.json @@ -4659,6 +4659,7 @@ "905197486607072f": "Отбросить", "02c0ae493e689f90": "Цель", "13300e8565fbd665": "{label} ({count})", + "8327da16dcfdb504": "Входящие", "694e089caefce25f": "{count, plural, one {Показать ещё {count} разобранный тред} few {Показать ещё {count} разобранных треда} many {Показать ещё {count} разобранных тредов} other {Показать ещё {count} разобранного треда}}", "ece9e2869077cbb6": "Удалить {title}", "306a6f95ad9d52f7": "Неотправленные", diff --git a/apps/mobile/src/i18n/translations/sv.json b/apps/mobile/src/i18n/translations/sv.json index 4022912f950f2..6ec8f0d4259aa 100644 --- a/apps/mobile/src/i18n/translations/sv.json +++ b/apps/mobile/src/i18n/translations/sv.json @@ -4587,6 +4587,7 @@ "905197486607072f": "Kasta", "02c0ae493e689f90": "Mål", "13300e8565fbd665": "{label} ({count})", + "8327da16dcfdb504": "Inkorg", "694e089caefce25f": "{count, plural, one {Visa {count} klar tråd till} other {Visa {count} klara trådar till}}", "ece9e2869077cbb6": "Kasta {title}", "306a6f95ad9d52f7": "Ej skickade", diff --git a/apps/mobile/src/i18n/translations/zh.json b/apps/mobile/src/i18n/translations/zh.json index 319bcec573f67..55f99cb40c6ab 100644 --- a/apps/mobile/src/i18n/translations/zh.json +++ b/apps/mobile/src/i18n/translations/zh.json @@ -4570,6 +4570,7 @@ "905197486607072f": "放弃", "02c0ae493e689f90": "目标", "13300e8565fbd665": "{label}({count})", + "8327da16dcfdb504": "收件箱", "694e089caefce25f": "{count, plural, other {再显示 {count} 个已收尾的会话}}", "ece9e2869077cbb6": "丢弃 {title}", "306a6f95ad9d52f7": "未发送", diff --git a/docs/user/thread-sidebar.md b/docs/user/thread-sidebar.md index 000c71ec10556..4ab0e0a1b478d 100644 --- a/docs/user/thread-sidebar.md +++ b/docs/user/thread-sidebar.md @@ -164,10 +164,11 @@ open. ### Fold working threads (beta) Threads that are working or waiting on work they will resume from move into a collapsed -**Working** section below the active list. +**Working** section. That includes subagents, watched pull requests with checks still running, Claude monitors, and background commands or other monitors the agent says it is waiting on. A dev server or other process an agent leaves running does not keep a thread -there. A thread returns to the top of the active list when it finishes, fails, or needs an approval or +there. On web and desktop the section sits below the active list. On iOS and Android it sits above +it, under pinned threads, and the active list below it is labeled **Inbox**. A thread returns to the top of the active list when it finishes, fails, or needs an approval or answer. The Working section lists the thread you last sent work to first. Pinned threads stay in the pinned section.