From d38dcccef8e3d0fac83e73336f77485b515b2c76 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 25 Nov 2026 01:14:56 -0800 Subject: [PATCH 001/238] fix(web): project actions menu re-reads t3.json each time it opens (#42707) --- .../src/components/ProjectScriptsControl.tsx | 24 ++++--- .../chat/ThreadDetailsPanel.browser.test.tsx | 66 ++++++++++++++++++- .../components/chat/ThreadDetailsPanel.tsx | 7 +- apps/web/src/hooks/useT3ProjectFileScripts.ts | 14 ++-- 4 files changed, 85 insertions(+), 26 deletions(-) diff --git a/apps/web/src/components/ProjectScriptsControl.tsx b/apps/web/src/components/ProjectScriptsControl.tsx index 210762bfdebf9..870a165912a81 100644 --- a/apps/web/src/components/ProjectScriptsControl.tsx +++ b/apps/web/src/components/ProjectScriptsControl.tsx @@ -69,6 +69,7 @@ interface ProjectScriptsControlProps { environmentId: EnvironmentId; scripts: ReadonlyArray; fileScripts?: ReadonlyArray; + onActionsMenuOpen?: () => void; preferredScriptId?: string | null; onRunScript?: ((script: ProjectScript) => void) | undefined; onAddScript: (input: NewProjectScriptInput) => Promise; @@ -86,6 +87,7 @@ export default function ProjectScriptsControl({ environmentId, scripts, fileScripts = NO_FILE_SCRIPTS, + onActionsMenuOpen, preferredScriptId = null, onRunScript, onAddScript, @@ -108,6 +110,10 @@ export default function ProjectScriptsControl({ if (actionsMenuOpen.presentation !== presentation) { setActionsMenuOpen({ presentation, scripts: false, imports: false }); } + const openActionsMenu = (menus: { scripts: boolean; imports: boolean }) => { + if (menus.scripts || menus.imports) onActionsMenuOpen?.(); + setActionsMenuOpen({ presentation, ...menus }); + }; const [editorRequest, setEditorRequest] = useState(null); const editorRequestIdRef = React.useRef(0); @@ -286,9 +292,7 @@ export default function ProjectScriptsControl({ {scripts.length > 0 || importableScripts.length > 0 ? ( - setActionsMenuOpen({ presentation, scripts: open, imports: false }) - } + onOpenChange={(open) => openActionsMenu({ scripts: open, imports: false })} > @@ -361,9 +365,7 @@ export default function ProjectScriptsControl({ )} - setActionsMenuOpen({ presentation, scripts: open, imports: false }) - } + onOpenChange={(open) => openActionsMenu({ scripts: open, imports: false })} > setActionsMenuOpen({ presentation, scripts: false, imports: true })} + onClick={() => openActionsMenu({ scripts: false, imports: true })} > @@ -423,9 +425,7 @@ export default function ProjectScriptsControl({ - setActionsMenuOpen({ presentation, scripts: false, imports: open }) - } + onOpenChange={(open) => openActionsMenu({ scripts: false, imports: open })} > - setActionsMenuOpen({ presentation, scripts: false, imports: open }) - } + onOpenChange={(open) => openActionsMenu({ scripts: false, imports: open })} > } diff --git a/apps/web/src/components/chat/ThreadDetailsPanel.browser.test.tsx b/apps/web/src/components/chat/ThreadDetailsPanel.browser.test.tsx index b5fb3de136f59..2ca6982d24580 100644 --- a/apps/web/src/components/chat/ThreadDetailsPanel.browser.test.tsx +++ b/apps/web/src/components/chat/ThreadDetailsPanel.browser.test.tsx @@ -18,6 +18,47 @@ const state = vi.hoisted(() => ({ configLoaded: true, })); +// The read of t3.json is a cache: a re-read is the only way to see what is on disk now. +const t3File = vi.hoisted(() => ({ + disk: "", + cached: "", + listeners: new Set<() => void>(), +})); + +vi.mock(import("~/components/files/projectFilesQueryState"), async (importOriginal) => { + const actual = await importOriginal(); + const { useSyncExternalStore } = await import("react"); + return { + ...actual, + useProjectFileQuery: ((_environmentId: unknown, _cwd: string, relativePath: string | null) => { + const contents = useSyncExternalStore( + (listener) => { + t3File.listeners.add(listener); + return () => t3File.listeners.delete(listener); + }, + () => t3File.cached, + ); + const refresh = () => { + t3File.cached = t3File.disk; + for (const listener of t3File.listeners) listener(); + }; + const data = + relativePath === "t3.json" && contents !== "" + ? { relativePath, contents, byteLength: contents.length, truncated: false } + : null; + return { + data, + error: null, + isPending: false, + readError: null, + isNotFile: false, + isFile: data !== null, + refresh, + }; + }) as never, + }; +}); + vi.mock(import("~/state/entities"), async (importOriginal) => ({ ...(await importOriginal()), useProject: ((ref: unknown) => @@ -137,11 +178,13 @@ function Panel({ fixture, draftEnvMode, onMachines = false, + withScripts = false, }: { fixture: ReturnType; /** Renders an unsent draft in this mode instead of a started thread. */ draftEnvMode?: "local" | "worktree"; onMachines?: boolean; + withScripts?: boolean; }) { const noop = () => {}; const scriptResult = async () => ({ ok: true }) as never; @@ -169,7 +212,7 @@ function Panel({ worktreePath={draftEnvMode === undefined ? state.folder : null} isServerThread={draftEnvMode === undefined} activeProjectName={state.workspaceRoot === SCRATCH_ROOT ? "No project" : "plain"} - activeProjectScripts={undefined} + activeProjectScripts={withScripts ? [] : undefined} preferredScriptId={null} keybindings={[]} availableEditors={[]} @@ -251,3 +294,24 @@ it("offers no Initialize Git before the server config says where No project live .element(page.getByRole("button", { name: "Initialize Git" })) .not.toBeInTheDocument(); }); + +it("lists the t3.json actions on disk when the actions menu opens again after the file changed", async () => { + using fixture = setup({ workspaceRoot: "/work/plain", folder: "/work/plain" }); + const t3Json = (name: string) => + JSON.stringify({ scripts: [{ name, command: `npm run dev -- --port ${name.slice(-4)}` }] }); + t3File.disk = t3Json("Dev 4100"); + t3File.cached = t3File.disk; + await using _screen = await render(); + + const chooser = page.getByRole("button", { name: "Choose project action" }); + await chooser.click(); + await expect.element(page.getByRole("menuitem", { name: /Dev 4100/ })).toBeVisible(); + await chooser.click(); + await expect.element(page.getByRole("menu")).not.toBeInTheDocument(); + + // A setup hook rewrites this checkout's t3.json outside T3 Code. + t3File.disk = t3Json("Dev 4200"); + + await chooser.click(); + await expect.element(page.getByRole("menuitem", { name: /Dev 4200/ })).toBeVisible(); +}); diff --git a/apps/web/src/components/chat/ThreadDetailsPanel.tsx b/apps/web/src/components/chat/ThreadDetailsPanel.tsx index 69c3cd7133aff..32de434760a45 100644 --- a/apps/web/src/components/chat/ThreadDetailsPanel.tsx +++ b/apps/web/src/components/chat/ThreadDetailsPanel.tsx @@ -11,7 +11,7 @@ import { scopeProjectRef } from "@t3tools/client-runtime/environment"; import { isScratchProject } from "@t3tools/client-runtime/state/projects"; import type { ComposerThreadTarget, DraftId } from "../../composerDraftStore"; -import { useT3ProjectFileScripts } from "../../hooks/useT3ProjectFileScripts"; +import { useT3ProjectFileState } from "../../hooks/useT3ProjectFileScripts"; import { type EnvMode, type EnvironmentOption } from "../BranchToolbar.logic"; import { BranchToolbar } from "../BranchToolbar"; import GitActionsControl from "../GitActionsControl"; @@ -101,7 +101,7 @@ export function ThreadDetailsPanel(props: ThreadDetailsPanelProps) { const visible = useClientSettings(resolveThreadDetailsVisibility); const gt = useGT(); const [menuPosition, setMenuPosition] = useState<{ x: number; y: number } | null>(null); - const fileScripts = useT3ProjectFileScripts( + const t3File = useT3ProjectFileState( props.environmentId, props.activeProjectScripts && visible.scripts ? props.gitCwd : null, ); @@ -243,7 +243,8 @@ export function ThreadDetailsPanel(props: ThreadDetailsPanelProps) { environmentId={props.environmentId} displayMode="panel" scripts={props.activeProjectScripts} - fileScripts={fileScripts} + fileScripts={t3File.scripts} + onActionsMenuOpen={t3File.refresh} preferredScriptId={props.preferredScriptId} onRunScript={props.onRunProjectScript} onAddScript={props.onAddProjectScript} diff --git a/apps/web/src/hooks/useT3ProjectFileScripts.ts b/apps/web/src/hooks/useT3ProjectFileScripts.ts index 5ccef54144b66..bb5ac9aa8d878 100644 --- a/apps/web/src/hooks/useT3ProjectFileScripts.ts +++ b/apps/web/src/hooks/useT3ProjectFileScripts.ts @@ -14,6 +14,7 @@ export interface T3ProjectFileState { status: "loading" | "missing" | "invalid" | "valid"; file: T3ProjectFile | null; scripts: ReadonlyArray; + refresh: () => void; } export function useT3ProjectFileState( @@ -23,23 +24,18 @@ export function useT3ProjectFileState( const query = useProjectFileQuery(environmentId, cwd ?? "", T3_PROJECT_FILE_NAME, cwd !== null); const contents = query.data && !query.data.truncated ? query.data.contents : null; const isPending = query.isPending; + const refresh = query.refresh; if (contents === null) { return { status: isPending ? "loading" : "missing", file: null, scripts: NO_SCRIPTS, + refresh, } as const; } const file = parseT3ProjectFile(contents); if (file === null) { - return { status: "invalid", file: null, scripts: NO_SCRIPTS } as const; + return { status: "invalid", file: null, scripts: NO_SCRIPTS, refresh } as const; } - return { status: "valid", file, scripts: file.scripts ?? NO_SCRIPTS } as const; -} - -export function useT3ProjectFileScripts( - environmentId: EnvironmentId, - cwd: string | null, -): ReadonlyArray { - return useT3ProjectFileState(environmentId, cwd).scripts; + return { status: "valid", file, scripts: file.scripts ?? NO_SCRIPTS, refresh } as const; } From 226113fee0682579155702b9e182c5a893aabbcf Mon Sep 17 00:00:00 2001 From: Victor Date: Wed, 25 Nov 2026 03:17:50 -0600 Subject: [PATCH 002/238] fix(desktop): picked element preview no longer ends in a split surrogate (#42642) Co-authored-by: Julius Marminge --- apps/desktop/src/preview/PickPreload.test.ts | 64 ++++++++++++-------- apps/desktop/src/preview/PickPreload.ts | 6 +- 2 files changed, 43 insertions(+), 27 deletions(-) diff --git a/apps/desktop/src/preview/PickPreload.test.ts b/apps/desktop/src/preview/PickPreload.test.ts index d250d726e43e0..527f770fcdfdc 100644 --- a/apps/desktop/src/preview/PickPreload.test.ts +++ b/apps/desktop/src/preview/PickPreload.test.ts @@ -1,3 +1,4 @@ +import type { PreviewAnnotationPayload } from "@t3tools/contracts"; import { expect, it, vi } from "vite-plus/test"; import { ELEMENT_PICKED_CHANNEL, START_PICK_CHANNEL } from "./GuestProtocol.ts"; @@ -46,6 +47,33 @@ const startAnnotation = (): ShadowRoot => { return shadowRoot; }; +const pickAndAttach = async (element: Element) => { + ipcSend.calls.length = 0; + document.elementsFromPoint = () => [element]; + using listeners = vi.spyOn(HTMLButtonElement.prototype, "addEventListener"); + const shadowRoot = startAnnotation(); + element.dispatchEvent( + new PointerEvent("pointerdown", { button: 0, clientX: 100, clientY: 100, bubbles: true }), + ); + const attach = Array.from(shadowRoot.querySelectorAll("button")).find( + (button) => button.textContent === "Attach", + ); + const listenerIndex = listeners.mock.contexts.findIndex( + (target, index) => target === attach && listeners.mock.calls[index]?.[0] === "click", + ); + const listener = listeners.mock.calls[listenerIndex]?.[1]; + if (!attach || typeof listener !== "function") throw new Error("Attach listener not found"); + // The DOM test environment has no native input source. + listener.call(attach, { isTrusted: true } as MouseEvent); + + await vi.waitFor(() => + expect(ipcSend.calls.some(([channel]) => channel === ELEMENT_PICKED_CHANNEL)).toBe(true), + ); + const [, annotation] = + ipcSend.calls.find(([channel]) => channel === ELEMENT_PICKED_CHANNEL) ?? []; + return (annotation as PreviewAnnotationPayload | undefined)?.elements[0]?.element; +}; + it("switches tools from the keyboard after a toolbar button is clicked", () => { const shadowRoot = startAnnotation(); const region = Array.from(shadowRoot.querySelectorAll("button")).find( @@ -168,7 +196,6 @@ it.each([ ); it("keeps only the well-typed fields of what the page reports about an element", async () => { - ipcSend.calls.length = 0; pageElementContext.mockResolvedValueOnce({ selector: { toString: () => "#object" }, htmlPreview: "", @@ -177,32 +204,9 @@ it("keeps only the well-typed fields of what the page reports about an element", stack: [{ functionName: "Checkout", fileName: ["x"], lineNumber: "12", columnNumber: 4 }, 3], }); const card = document.body.appendChild(document.createElement("div")); - document.elementsFromPoint = () => [card]; - using listeners = vi.spyOn(HTMLButtonElement.prototype, "addEventListener"); - const shadowRoot = startAnnotation(); - card.dispatchEvent( - new PointerEvent("pointerdown", { button: 0, clientX: 100, clientY: 100, bubbles: true }), - ); - const attach = Array.from(shadowRoot.querySelectorAll("button")).find( - (button) => button.textContent === "Attach", - ); - const listenerIndex = listeners.mock.contexts.findIndex( - (target, index) => target === attach && listeners.mock.calls[index]?.[0] === "click", - ); - const listener = listeners.mock.calls[listenerIndex]?.[1]; - if (!attach || typeof listener !== "function") throw new Error("Attach listener not found"); - // The DOM test environment has no native input source. - listener.call(attach, { isTrusted: true } as MouseEvent); - - await vi.waitFor(() => - expect(ipcSend.calls.some(([channel]) => channel === ELEMENT_PICKED_CHANNEL)).toBe(true), - ); - const [, annotation] = - ipcSend.calls.find(([channel]) => channel === ELEMENT_PICKED_CHANNEL) ?? []; + const element = await pickAndAttach(card); const frame = { functionName: "Checkout", fileName: null, lineNumber: null, columnNumber: 4 }; - expect( - (annotation as { elements: Array<{ element: unknown }> }).elements[0]?.element, - ).toMatchObject({ + expect(element).toMatchObject({ selector: null, htmlPreview: "", componentName: null, @@ -211,3 +215,11 @@ it("keeps only the well-typed fields of what the page reports about an element", stack: [frame, { functionName: null, fileName: null, lineNumber: null, columnNumber: null }], }); }); + +it("drops a straddling surrogate pair when falling back to outerHTML preview", async () => { + pageElementContext.mockRejectedValueOnce(new Error("page lookup failed")); + const card = document.body.appendChild(document.createElement("div")); + card.textContent = `${"a".repeat(494)}🚀tail`; + expect(card.outerHTML.charCodeAt(499)).toBe(0xd83d); + expect((await pickAndAttach(card))?.htmlPreview).toBe(card.outerHTML.slice(0, 499)); +}); diff --git a/apps/desktop/src/preview/PickPreload.ts b/apps/desktop/src/preview/PickPreload.ts index a227d5136b6c6..61e3c8070d722 100644 --- a/apps/desktop/src/preview/PickPreload.ts +++ b/apps/desktop/src/preview/PickPreload.ts @@ -494,10 +494,14 @@ async function captureElement(element: Element): Promise { }; } } catch {} + const html = element.outerHTML; + const before = html.charCodeAt(HTML_PREVIEW_MAX_CHARS - 1); + const after = html.charCodeAt(HTML_PREVIEW_MAX_CHARS); + const splitPair = before >= 0xd800 && before <= 0xdbff && after >= 0xdc00 && after <= 0xdfff; return { ...base, selector: null, - htmlPreview: element.outerHTML.slice(0, HTML_PREVIEW_MAX_CHARS), + htmlPreview: html.slice(0, splitPair ? HTML_PREVIEW_MAX_CHARS - 1 : HTML_PREVIEW_MAX_CHARS), componentName: null, source: null, stack: [], From b125918f4b4147f45749e97872b93b5676f031e4 Mon Sep 17 00:00:00 2001 From: Victor Date: Wed, 25 Nov 2026 03:48:40 -0600 Subject: [PATCH 003/238] fix(web): xlsx previews no longer fail on cells truncated mid-emoji (#42718) Co-authored-by: Julius Marminge --- .../components/files/officeArchive.test.ts | 24 ++++++++++++++++++- .../web/src/components/files/officeArchive.ts | 6 ++++- 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/apps/web/src/components/files/officeArchive.test.ts b/apps/web/src/components/files/officeArchive.test.ts index fd8718e21fdcf..a1d7912265a8e 100644 --- a/apps/web/src/components/files/officeArchive.test.ts +++ b/apps/web/src/components/files/officeArchive.test.ts @@ -170,6 +170,7 @@ async function workbookFile( sheetPath: string, extraRels = "", targetMode = "Internal", + sheetData = `42`, ) { const zip = new JSZip(); zip.file( @@ -190,7 +191,7 @@ async function workbookFile( ); zip.file( sheetPath, - `42`, + `${sheetData}`, ); return zip.generateAsync({ type: "arraybuffer" }); } @@ -232,3 +233,24 @@ describe("Workbook relationship targets", () => { expect(await zip.file("xl/worksheets/sheet1.xml")?.async("string")).toContain("42"); }); }); + +describe("Workbook preview limits", () => { + it("does not split a surrogate pair when truncating cell text", async () => { + const prefix = "a".repeat(4095); + const result = await prepareOffice( + await workbookFile( + "worksheets/sheet1.xml", + "xl/worksheets/sheet1.xml", + "", + "Internal", + `${prefix}🚀tail`, + ), + "xlsx", + ); + const zip = await JSZip.loadAsync(result.bytes); + const sheet = await zip.file("xl/worksheets/sheet1.xml")?.async("string"); + expect(result.truncated).toBe(true); + expect(sheet).toContain(`${prefix}`); + expect(sheet).not.toContain("\ufffd"); + }); +}); diff --git a/apps/web/src/components/files/officeArchive.ts b/apps/web/src/components/files/officeArchive.ts index 0e9b59ab8e9eb..b9b08801e5300 100644 --- a/apps/web/src/components/files/officeArchive.ts +++ b/apps/web/src/components/files/officeArchive.ts @@ -411,7 +411,11 @@ function boundedWorksheet( const end = cell.selfClosing ? cell.start : xml.lastIndexOf("<", parser.position - 1); const raw = cell.opening + xml.slice(cell.start, end) + ``; const shown = cell.shared ? (strings[Number(cell.value)] ?? "") : cell.text || cell.value; - const kept = shown.slice(0, Math.min(4096, budget.remaining)); + let limit = Math.min(4096, budget.remaining); + const before = shown.charCodeAt(limit - 1); + const after = shown.charCodeAt(limit); + if (before >= 0xd800 && before <= 0xdbff && after >= 0xdc00 && after <= 0xdfff) limit--; + const kept = shown.slice(0, limit); budget.remaining -= kept.length; if (kept.length < shown.length) { truncated = true; From 341864854bea1dc891805d64915ffdeb6d4011e2 Mon Sep 17 00:00:00 2001 From: Alex Hatzenbuhler Date: Wed, 25 Nov 2026 03:52:29 -0600 Subject: [PATCH 004/238] fix(server): report stopped and disabled launch agents in macOS service status (#42715) Co-authored-by: Julius Marminge --- apps/server/src/cloud/bootService.test.ts | 47 ++++++++++++++++++----- apps/server/src/cloud/bootService.ts | 28 ++++++++++++-- 2 files changed, 61 insertions(+), 14 deletions(-) diff --git a/apps/server/src/cloud/bootService.test.ts b/apps/server/src/cloud/bootService.test.ts index 535e2cfed313f..d8ad4f281933b 100644 --- a/apps/server/src/cloud/bootService.test.ts +++ b/apps/server/src/cloud/bootService.test.ts @@ -276,7 +276,13 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* ( control.linger = "yes"; control.managerReachable ||= control.lingerStartsManager; } - if (!failed && command === "systemctl --user enable t3code.service") control.enabled = true; + if ( + !failed && + (command === "systemctl --user enable t3code.service" || + command.startsWith("launchctl enable ")) + ) { + control.enabled = true; + } const taskMissing = input.command === SCHTASKS && input.args[0] !== "/Create" && control.task === undefined; if (input.command === SCHTASKS && !failed) { @@ -290,14 +296,25 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* ( if (input.args[0] === "/Delete") delete control.task; if (input.args[0] === "/End") control.launcher?.close(); } - if (!refusedStart && !failed && command.startsWith("systemctl --user restart ")) + if ( + !refusedStart && + !failed && + (command.startsWith("systemctl --user restart ") || + command.startsWith("launchctl bootstrap ")) + ) { control.active = true; + } // The manager loads units only from its own unit directory. const unitOutsideManager = command === "systemctl --user enable t3code.service" && !(yield* fs.exists(path.join(managerUnitDir, "t3code.service"))); // A timed-out stop may still stop the service. - if (command === "systemctl --user stop t3code.service") control.active = false; + if ( + command === "systemctl --user stop t3code.service" || + command.startsWith("launchctl bootout --wait ") + ) { + control.active = false; + } if ( control.stateAfterStop !== undefined && (command === "systemctl --user stop t3code.service" || @@ -326,11 +343,13 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* ( : (control.task?.xml ?? "") : input.command === "loginctl" && input.args[0] === "show-user" ? `${control.linger ?? ""}\n` - : input.args[1] === "is-enabled" - ? control.enabled - ? "enabled\n" - : "disabled\n" - : "", + : input.command === "launchctl" && input.args[0] === "print-disabled" + ? `disabled services = {\n\t"${BootService.BOOT_SERVICE_LAUNCHD_LABEL}" => ${control.enabled ? "enabled" : "disabled"}\n}\n` + : input.args[1] === "is-enabled" + ? control.enabled + ? "enabled\n" + : "disabled\n" + : "", stderr: "", code: ChildProcessSpawner.ExitCode( taskMissing && input.args.includes("/HRESULT") @@ -345,6 +364,7 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* ( input.args[0] === "show-user" && control.linger === undefined) || (input.args[1] === "is-active" && !control.active) || + (input.command === "launchctl" && input.args[0] === "print" && !control.active) || (input.args[1] === "is-enabled" && !control.enabled) ? 1 : 0, @@ -1524,7 +1544,7 @@ process.disconnect(); it.effect("installs, reports current state, and uninstalls on macOS", () => Effect.gen(function* () { - const { service, fs, statePath, commands, timeouts, runtime, markersAtStop } = + const { service, fs, statePath, commands, timeouts, runtime, markersAtStop, control } = yield* makeHarness("darwin"); const path = yield* Path.Path; const plan = yield* service.install(); @@ -1547,6 +1567,13 @@ process.disconnect(); expect(yield* service.status).toMatchObject({ current: true, installedVersion: "1.2.3", + problems: [], + }); + control.active = false; + control.enabled = false; + expect(yield* service.status).toMatchObject({ + current: false, + problems: ["service-disabled", "service-stopped"], }); const relayMarker = path.join(plan.baseDir, "runtime", DESKTOP_UPDATE_RESTART_MARKER_FILE); expect(yield* service.restart).toBe("restarted"); @@ -1802,7 +1829,7 @@ process.disconnect(); expect((yield* service.install().pipe(Effect.flip))._tag).toBe("BootServiceCommandError"); expect(yield* service.status).toMatchObject({ current: false, - problems: ["restart-pending"], + problems: ["service-stopped", "restart-pending"], }); expect(yield* fs.readFileString(markerPath)).toBe("1.2.3\n"); diff --git a/apps/server/src/cloud/bootService.ts b/apps/server/src/cloud/bootService.ts index 11a1978b01830..6d11d575e97a0 100644 --- a/apps/server/src/cloud/bootService.ts +++ b/apps/server/src/cloud/bootService.ts @@ -1129,6 +1129,28 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { runner.run({ command, args, timeout: Duration.seconds(5) }).pipe(Effect.option); const succeeded = (result: Option.Option) => Option.isSome(result) && result.value.code === 0; + const launchdJobLoaded = probe("launchctl", [ + "print", + `gui/${uid}/${BOOT_SERVICE_LAUNCHD_LABEL}`, + ]).pipe(Effect.map(succeeded)); + const readLaunchdProblems = Effect.fn("cloud.boot_service.read_launchd_problems")(function* () { + const [loaded, disabled] = yield* Effect.all( + [launchdJobLoaded, probe("launchctl", ["print-disabled", `gui/${uid}`])], + { concurrency: "unbounded" }, + ); + const problems: BootServiceProblem[] = []; + if ( + Option.isSome(disabled) && + disabled.value.code === 0 && + // Older macOS versions print `true` instead of `disabled`. + (disabled.value.stdout.includes(`"${BOOT_SERVICE_LAUNCHD_LABEL}" => disabled`) || + disabled.value.stdout.includes(`"${BOOT_SERVICE_LAUNCHD_LABEL}" => true`)) + ) { + problems.push("service-disabled"); + } + if (!loaded) problems.push("service-stopped"); + return problems; + }); const lingerArgs = [ "show-user", ...(uid === undefined ? [] : [String(uid)]), @@ -1554,9 +1576,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { (problems) => !problems.includes("service-disabled") || !problems.includes("service-stopped"), ) - : succeeded( - yield* probe("launchctl", ["print", `gui/${uid}/${BOOT_SERVICE_LAUNCHD_LABEL}`]), - ); + : yield* launchdJobLoaded; return yield* Effect.acquireUseRelease( // Require every stop before repair when restoring, so the server releases the database. // Otherwise stops are best-effort; launchd rejects bootout of an unloaded job. @@ -1624,7 +1644,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { ? [...(yield* readSystemdProblems(true))] : manager.kind === "schtasks" ? [...(yield* readSchtasksProblems(Option.some(unit)))] - : []; + : [...(yield* readLaunchdProblems())]; if (yield* fs.exists(restartPendingPath)) problems.push("restart-pending"); return { supported: true, From c8b4a49b2bcb75dcc7d933f1a09713362f55d4d4 Mon Sep 17 00:00:00 2001 From: 2SinceJuly <2929362966@qq.com> Date: Wed, 25 Nov 2026 19:03:16 +0900 Subject: [PATCH 005/238] fix(provider-core): keep a killed npm view from leaking into the user's npm cache (#42693) Co-authored-by: Julius Marminge --- .../src/provider/Drivers/ClaudeDriver.ts | 2 + .../src/provider/Drivers/CodexDriver.ts | 2 + .../src/server/maintenanceResolver.test.ts | 65 +++++++++++ .../src/server/maintenanceResolver.ts | 104 +++++++++++------- packages/provider-fx/src/server/driver.ts | 9 +- packages/provider-grok/src/server/driver.ts | 1 + packages/provider-muse/src/server/driver.ts | 1 + .../provider-opencode/src/server/driver.ts | 1 + packages/provider-pi/src/server/driver.ts | 1 + 9 files changed, 146 insertions(+), 40 deletions(-) diff --git a/apps/server/src/provider/Drivers/ClaudeDriver.ts b/apps/server/src/provider/Drivers/ClaudeDriver.ts index a03c72c7de458..83a63f04392b9 100644 --- a/apps/server/src/provider/Drivers/ClaudeDriver.ts +++ b/apps/server/src/provider/Drivers/ClaudeDriver.ts @@ -111,6 +111,7 @@ export const ClaudeDriver: ProviderDriver + Effect.gen(function* () { + const tempDir = yield* makeTempDir("t3-npm-view-cache"); + yield* Effect.addFinalizer(() => + Effect.sync(() => NodeFS.rmSync(tempDir, { recursive: true, force: true })), + ); + const npmBinDir = NodePath.join(tempDir, "npm-bin"); + writeExecutable(NodePath.join(npmBinDir, "npm")); + const binaryPath = NodePath.join(tempDir, ".local/bin/native-package-tool"); + writeExecutable(binaryPath); + const npmCacheDir = NodePath.join(tempDir, "t3-caches", "npm"); + const cacheDirs: Array = []; + const viewStarted = yield* Deferred.make(); + const spawner = ChildProcessSpawner.make((command) => { + const { options } = command as unknown as { + readonly options: { readonly env: Record }; + }; + const cacheDir = options.env.npm_config_cache; + cacheDirs.push(cacheDir); + if (typeof cacheDir === "string") { + NodeFS.mkdirSync(NodePath.join(cacheDir, "_cacache", "tmp"), { recursive: true }); + NodeFS.writeFileSync(NodePath.join(cacheDir, "_cacache", "index"), ""); + NodeFS.writeFileSync( + NodePath.join(cacheDir, "_cacache", "tmp", "partial-packument"), + '{"name":"@example/native-package-tool"', + ); + } + return Effect.succeed( + ChildProcessSpawner.makeHandle({ + pid: ChildProcessSpawner.ProcessId(1), + exitCode: Effect.never, + isRunning: Effect.succeed(true), + kill: () => Effect.void, + unref: Effect.succeed(Effect.void), + stdin: Sink.drain, + stdout: Stream.fromEffect(Deferred.succeed(viewStarted, undefined)).pipe( + Stream.flatMap(() => Stream.never), + ), + stderr: Stream.empty, + all: Stream.empty, + getInputFd: () => Sink.drain, + getOutputFd: () => Stream.empty, + }), + ); + }); + const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect( + nativePackageToolUpdate, + { binaryPath, env: { PATH: "" }, npmCacheDir }, + ).pipe( + Effect.provideService(HostProcess.Environment, { PATH: npmBinDir }), + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + ); + const fiber = yield* Effect.forkChild(capabilities.lookupLatestVersion!); + yield* Deferred.await(viewStarted); + yield* Fiber.interrupt(fiber); + expect(cacheDirs).toHaveLength(1); + const cacheDir = cacheDirs[0] as string; + expect(cacheDir.startsWith(npmCacheDir)).toBe(true); + expect(NodeFS.existsSync(NodePath.join(cacheDir, "_cacache", "tmp"))).toBe(false); + expect(NodeFS.existsSync(NodePath.join(cacheDir, "_cacache", "index"))).toBe(true); + }), + ); + it.effect.skipIf(!symlinksSupported || windowsHost)( "keeps configured npm registries' latest versions apart for one install", () => diff --git a/packages/provider-core/src/server/maintenanceResolver.ts b/packages/provider-core/src/server/maintenanceResolver.ts index 18f18da5f63ea..9a422122c27ae 100644 --- a/packages/provider-core/src/server/maintenanceResolver.ts +++ b/packages/provider-core/src/server/maintenanceResolver.ts @@ -1312,6 +1312,7 @@ function environmentCacheKey(env: NodeJS.ProcessEnv): string { const withConfiguredNpmVersionLookup = Effect.fn("withConfiguredNpmVersionLookup")(function* ( capabilities: ProviderMaintenanceCapabilities, + npmCacheDir: string | undefined, ) { const packageName = capabilities.packageName; if (!packageName || capabilities.latestVersion !== undefined) { @@ -1321,13 +1322,32 @@ const withConfiguredNpmVersionLookup = Effect.fn("withConfiguredNpmVersionLookup const npmPath = yield* resolveCommandPath("npm", { env }); if (!npmPath) return capabilities; const services = yield* Effect.context(); - const lookup = runProbe( - npmPath, - ["view", "--global", "--json", `${packageName}@latest`, "version"], - env, - [0], - NPM_REGISTRY_PROBE_TIMEOUT, - ).pipe( + const path = yield* Path.Path; + // `npm view` downloads the whole packument into its cache's tmp directory and a killed npm + // leaves it there. A cache only T3 writes to can drop that directory without touching another + // npm run's files, and lasting across lookups lets npm revalidate instead of re-downloading. + const cacheDir = npmCacheDir && path.join(npmCacheDir, encodeURIComponent(packageName)); + const lookup = Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + return yield* runProbe( + npmPath, + ["view", "--global", "--json", `${packageName}@latest`, "version"], + cacheDir ? { ...env, npm_config_cache: cacheDir } : env, + [0], + NPM_REGISTRY_PROBE_TIMEOUT, + ).pipe( + Effect.onInterrupt(() => + cacheDir + ? Effect.ignore( + fileSystem.remove(path.join(cacheDir, "_cacache", "tmp"), { + recursive: true, + force: true, + }), + ) + : Effect.void, + ), + ); + }).pipe( Effect.map((stdout) => { const value = stdout ? Option.getOrNull(decodeNpmViewVersion(stdout.trim())) : null; return nonEmptyString(typeof value === "string" ? value : value?.[0]); @@ -1363,39 +1383,47 @@ const withConfiguredNpmVersionLookup = Effect.fn("withConfiguredNpmVersionLookup export const resolveProviderMaintenanceCapabilitiesEffect = Effect.fn( "resolveProviderMaintenanceCapabilitiesEffect", -)(function* ( - resolver: ProviderMaintenanceCapabilitiesResolver, - options?: { - readonly binaryPath?: string | null; - readonly env?: NodeJS.ProcessEnv; - }, -) { - const binaryPath = nonEmptyString(options?.binaryPath); - if (!binaryPath) { - return yield* resolver.resolve(null); - } +)( + function* ( + resolver: ProviderMaintenanceCapabilitiesResolver, + options?: { + readonly binaryPath?: string | null; + readonly env?: NodeJS.ProcessEnv; + /** Where configured npm lookups keep their npm cache, apart from the user's. */ + readonly npmCacheDir?: string; + }, + ) { + const binaryPath = nonEmptyString(options?.binaryPath); + if (!binaryPath) { + return yield* resolver.resolve(null); + } - const env = options?.env ?? (yield* readCommandLookupEnv); - const resolvedCommandPath = yield* resolveCommandPath(binaryPath, { env }); - if (!resolvedCommandPath) { - return yield* resolver.resolve(null); - } + const env = options?.env ?? (yield* readCommandLookupEnv); + const resolvedCommandPath = yield* resolveCommandPath(binaryPath, { env }); + if (!resolvedCommandPath) { + return yield* resolver.resolve(null); + } - const fileSystem = yield* FileSystem.FileSystem; - const realCommandPath = yield* fileSystem - .realPath(resolvedCommandPath) - .pipe(Effect.orElseSucceed(() => null)); - if (!realCommandPath) { - return yield* resolver.resolve(null); - } - return yield* resolver.resolve({ - binaryPath, - resolvedCommandPath, - realCommandPath, - env, - platform: yield* HostProcess.Platform, - }); -}, Effect.flatMap(withConfiguredNpmVersionLookup)); + const fileSystem = yield* FileSystem.FileSystem; + const realCommandPath = yield* fileSystem + .realPath(resolvedCommandPath) + .pipe(Effect.orElseSucceed(() => null)); + if (!realCommandPath) { + return yield* resolver.resolve(null); + } + return yield* resolver.resolve({ + binaryPath, + resolvedCommandPath, + realCommandPath, + env, + platform: yield* HostProcess.Platform, + }); + }, + (effect, _resolver, options) => + Effect.flatMap(effect, (capabilities) => + withConfiguredNpmVersionLookup(capabilities, options?.npmCacheDir), + ), +); export const makeCachedProviderMaintenanceResolution = Effect.fn( "makeCachedProviderMaintenanceResolution", diff --git a/packages/provider-fx/src/server/driver.ts b/packages/provider-fx/src/server/driver.ts index b069b12a4de7d..05437e78eaebd 100644 --- a/packages/provider-fx/src/server/driver.ts +++ b/packages/provider-fx/src/server/driver.ts @@ -9,7 +9,7 @@ import * as Schema from "effect/Schema"; import * as HttpClient from "effect/http/HttpClient"; import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; -import type * as ProviderHost from "@t3tools/provider-core/server/ProviderHost"; +import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost"; import * as ProviderLatestVersions from "@t3tools/provider-core/server/ProviderLatestVersions"; import { type FxAdapterV2DriverEnv, makeFxAdapterV2Driver } from "./adapter.ts"; import { ProviderDriverError } from "@t3tools/provider-core/server/errors"; @@ -92,6 +92,7 @@ export const FxDriver: ProviderDriver = { const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; + const host = yield* ProviderHost.ProviderHost; const httpClient = yield* HttpClient.HttpClient; const latestVersions = yield* ProviderLatestVersions.ProviderLatestVersions; const processEnv = yield* mergeProviderInstanceEnvironment( @@ -119,7 +120,11 @@ export const FxDriver: ProviderDriver = { makeFxMaintenance( fetchLatestFxVersion().pipe(Effect.provideService(HttpClient.HttpClient, httpClient)), ), - { binaryPath: effectiveConfig.binaryPath, env: processEnv }, + { + binaryPath: effectiveConfig.binaryPath, + env: processEnv, + npmCacheDir: path.join(host.paths.providerStatusCacheDir, "npm"), + }, ).pipe( Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), Effect.provideService(FileSystem.FileSystem, fileSystem), diff --git a/packages/provider-grok/src/server/driver.ts b/packages/provider-grok/src/server/driver.ts index 660324d4f1d0a..68855df8d0964 100644 --- a/packages/provider-grok/src/server/driver.ts +++ b/packages/provider-grok/src/server/driver.ts @@ -181,6 +181,7 @@ export const GrokDriver: ProviderDriver resolveProviderMaintenanceCapabilitiesEffect(UPDATE, { binaryPath: effectiveConfig.binaryPath, env: processEnv, + npmCacheDir: path.join(host.paths.providerStatusCacheDir, "npm"), }).pipe( Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), Effect.provideService(FileSystem.FileSystem, fileSystem), diff --git a/packages/provider-muse/src/server/driver.ts b/packages/provider-muse/src/server/driver.ts index 197a219e54ecb..96e923a288f06 100644 --- a/packages/provider-muse/src/server/driver.ts +++ b/packages/provider-muse/src/server/driver.ts @@ -133,6 +133,7 @@ export const MuseDriver: ProviderDriver< resolveProviderMaintenanceCapabilitiesEffect(museMaintenance, { binaryPath: effectiveConfig.binaryPath, env: processEnvironment, + npmCacheDir: path.join(host.paths.providerStatusCacheDir, "npm"), }).pipe( Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), Effect.provideService(FileSystem.FileSystem, fileSystem), diff --git a/packages/provider-opencode/src/server/driver.ts b/packages/provider-opencode/src/server/driver.ts index cc1977325c0ea..b198080f34b5c 100644 --- a/packages/provider-opencode/src/server/driver.ts +++ b/packages/provider-opencode/src/server/driver.ts @@ -335,6 +335,7 @@ export const OpenCodeDriver: ProviderDriver< : resolveProviderMaintenanceCapabilitiesEffect(openCodeUpdateFor(generation.value), { binaryPath: effectiveConfig.binaryPath, env: processEnv, + npmCacheDir: pathService.join(host.paths.providerStatusCacheDir, "npm"), }), ), Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), diff --git a/packages/provider-pi/src/server/driver.ts b/packages/provider-pi/src/server/driver.ts index 6a9e07bc60fc2..d22ea6d02b34f 100644 --- a/packages/provider-pi/src/server/driver.ts +++ b/packages/provider-pi/src/server/driver.ts @@ -115,6 +115,7 @@ export const PiDriver: ProviderDriver = { resolveProviderMaintenanceCapabilitiesEffect(UPDATE, { binaryPath: effectiveConfig.binaryPath, env: processEnv, + npmCacheDir: pathService.join(host.paths.providerStatusCacheDir, "npm"), }).pipe( Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), Effect.provideService(FileSystem.FileSystem, fileSystem), From b042e4ee757947ca1cd47bb217c94296f9c695cf Mon Sep 17 00:00:00 2001 From: AymanKhan9 Date: Wed, 25 Nov 2026 15:38:19 +0530 Subject: [PATCH 006/238] fix(web): hide the right panel add-surface menu when no surfaces are available (#42722) Co-authored-by: Julius Marminge --- .../RightPanelTabs.browser.test.tsx | 62 ++++++++++++++- apps/web/src/components/RightPanelTabs.tsx | 75 ++++++++++--------- 2 files changed, 98 insertions(+), 39 deletions(-) diff --git a/apps/web/src/components/RightPanelTabs.browser.test.tsx b/apps/web/src/components/RightPanelTabs.browser.test.tsx index 347971993c7c3..4306d6bc1a219 100644 --- a/apps/web/src/components/RightPanelTabs.browser.test.tsx +++ b/apps/web/src/components/RightPanelTabs.browser.test.tsx @@ -1,12 +1,13 @@ import "~/index.css"; import { EnvironmentId } from "@t3tools/contracts"; +import { DEFAULT_RESOLVED_KEYBINDINGS } from "@t3tools/shared/keybindings"; import { describe, expect, it, vi } from "vite-plus/test"; -import { userEvent } from "vite-plus/test/browser"; +import { page, userEvent } from "vite-plus/test/browser"; import { InputGroup, InputGroupAddon, InputGroupInput } from "~/components/ui/input-group"; import type { RightPanelSurface } from "~/rightPanelStore"; -import { render, stubGlobal } from "../../test/render"; +import { act, render, stubGlobal } from "../../test/render"; import { HistorySwipeNavigation } from "./HistorySwipeNavigation"; import { RightPanelTabs, type RightPanelTabsProps } from "./RightPanelTabs"; import { subscribePreviewAction } from "./preview/previewActionBus"; @@ -292,3 +293,60 @@ describe("device tab rename", () => { expect(onRenameDevice).toHaveBeenCalledExactlyOnceWith(DEVICE_SURFACE.id, "日本語"); }); }); + +describe("add surface launcher", () => { + it("hides the button, closes the open menu and stops taking Mod+T and the desktop menu action once no surface can be added", async () => { + const menuListeners = new Set<(action: string) => void>(); + using _bridge = stubGlobal("desktopBridge", { + onMenuAction: (listener: (action: string) => void) => { + menuListeners.add(listener); + return () => menuListeners.delete(listener); + }, + }); + using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("Linux x86_64"); + const tabs = (sideChatAvailable: boolean) => ( + {}} + sideChatAvailable={sideChatAvailable} + > + {null} + + ); + const pressModT = async () => { + const event = new KeyboardEvent("keydown", { + key: "t", + ctrlKey: true, + bubbles: true, + cancelable: true, + }); + await act(() => { + document.body.dispatchEvent(event); + }); + return event.defaultPrevented; + }; + await using screen = await render(tabs(true)); + const addButton = screen.getByRole("button", { name: "Add panel surface" }); + + await expect.element(addButton).toBeInTheDocument(); + expect(menuListeners.size).toBe(1); + expect(await pressModT()).toBe(true); + await expect.element(page.getByRole("menu")).toBeVisible(); + + await screen.rerender(tabs(false)); + expect(addButton.query()).toBeNull(); + expect(page.getByRole("menu").query()).toBeNull(); + expect(menuListeners.size).toBe(0); + expect(await pressModT()).toBe(false); + expect(page.getByRole("menu").query()).toBeNull(); + }); +}); diff --git a/apps/web/src/components/RightPanelTabs.tsx b/apps/web/src/components/RightPanelTabs.tsx index f167d82b776da..b6b3590f996da 100644 --- a/apps/web/src/components/RightPanelTabs.tsx +++ b/apps/web/src/components/RightPanelTabs.tsx @@ -1139,42 +1139,6 @@ export function RightPanelTabs(props: RightPanelTabsProps) { canScrollRight: false, }); - if (props.open === false && addSurfaceMenuOpen) setAddSurfaceMenuOpen(false); - - const addSurfaceMenuBlocked = () => - !addSurfaceMenuOpen && document.querySelector(LAUNCHER_SHORTCUT_BLOCKING_LAYERS) !== null; - const onNewSurfaceKeyDown = useEffectEvent((event: KeyboardEvent) => { - if (event.defaultPrevented || event.isComposing) return; - if ( - resolveShortcutCommand(event, props.keybindings, { - context: { ...props.getShortcutContext(), rightPanelOpen: true }, - }) !== "rightPanel.new" - ) - return; - if (addSurfaceMenuBlocked()) return; - event.preventDefault(); - event.stopPropagation(); - if (!event.repeat) { - addSurfaceTriggerRef.current?.focus(); - setAddSurfaceMenuOpen(true); - } - }); - // Forwarded from a focused browser page. Focusing the trigger here would let ChatView's - // window-focus handler see a plain button and refocus the composer, closing the menu. - const onMenuAction = useEffectEvent((action: string) => { - if (action === "rightPanel.new" && !addSurfaceMenuBlocked()) setAddSurfaceMenuOpen(true); - }); - // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes document keydown and the desktop menu action (forwarded from a focused browser page) for the new surface shortcut while the panel is open - useEffect(() => { - if (props.open === false) return; - document.addEventListener("keydown", onNewSurfaceKeyDown, true); - const unsubscribe = window.desktopBridge?.onMenuAction(onMenuAction); - return () => { - document.removeEventListener("keydown", onNewSurfaceKeyDown, true); - unsubscribe?.(); - }; - }, [props.open]); - const updateTabScrollState = (viewport: HTMLDivElement) => { const hasOverflow = viewport.scrollWidth - viewport.clientWidth > TAB_SCROLL_EDGE_TOLERANCE; const canScrollLeft = hasOverflow && viewport.scrollLeft > TAB_SCROLL_EDGE_TOLERANCE; @@ -1274,6 +1238,43 @@ export function RightPanelTabs(props: RightPanelTabsProps) { ] : []), ] as const; + const canAddSurface = addSurfaceActions.some((action) => action.available); + + if ((props.open === false || !canAddSurface) && addSurfaceMenuOpen) setAddSurfaceMenuOpen(false); + + const addSurfaceMenuBlocked = () => + !addSurfaceMenuOpen && document.querySelector(LAUNCHER_SHORTCUT_BLOCKING_LAYERS) !== null; + const onNewSurfaceKeyDown = useEffectEvent((event: KeyboardEvent) => { + if (event.defaultPrevented || event.isComposing) return; + if ( + resolveShortcutCommand(event, props.keybindings, { + context: { ...props.getShortcutContext(), rightPanelOpen: true }, + }) !== "rightPanel.new" + ) + return; + if (addSurfaceMenuBlocked()) return; + event.preventDefault(); + event.stopPropagation(); + if (!event.repeat) { + addSurfaceTriggerRef.current?.focus(); + setAddSurfaceMenuOpen(true); + } + }); + // Forwarded from a focused browser page. Focusing the trigger here would let ChatView's + // window-focus handler see a plain button and refocus the composer, closing the menu. + const onMenuAction = useEffectEvent((action: string) => { + if (action === "rightPanel.new" && !addSurfaceMenuBlocked()) setAddSurfaceMenuOpen(true); + }); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes document keydown and the desktop menu action (forwarded from a focused browser page) for the new surface shortcut while the panel is open and can add a surface + useEffect(() => { + if (props.open === false || !canAddSurface) return; + document.addEventListener("keydown", onNewSurfaceKeyDown, true); + const unsubscribe = window.desktopBridge?.onMenuAction(onMenuAction); + return () => { + document.removeEventListener("keydown", onNewSurfaceKeyDown, true); + unsubscribe?.(); + }; + }, [props.open, canAddSurface]); const handleAddSurfaceMenuKeyDown = (event: ReactKeyboardEvent) => { const action = surfaceShortcutActionForKey(addSurfaceActions, event.nativeEvent); @@ -1550,7 +1551,7 @@ export function RightPanelTabs(props: RightPanelTabsProps) { ); })} - {props.open !== false ? ( + {props.open !== false && canAddSurface ? ( Date: Wed, 25 Nov 2026 04:15:30 -0600 Subject: [PATCH 007/238] fix(web): EPUB chapter titles no longer end in a broken emoji (#42725) Co-authored-by: Julius Marminge --- apps/web/src/components/files/FilePreviewPanel.test.ts | 4 ++-- apps/web/src/components/files/extendedDocumentPreview.ts | 7 +++---- 2 files changed, 5 insertions(+), 6 deletions(-) diff --git a/apps/web/src/components/files/FilePreviewPanel.test.ts b/apps/web/src/components/files/FilePreviewPanel.test.ts index 6de12a7863475..8ec04ee1cabe4 100644 --- a/apps/web/src/components/files/FilePreviewPanel.test.ts +++ b/apps/web/src/components/files/FilePreviewPanel.test.ts @@ -694,7 +694,7 @@ Third}`; ) .file( "Book/one.xhtml", - 'First

First chapter

Cover', + `${"a".repeat(119)}🚀

First chapter

Cover`, ) .file( "Book/two&&&.xhtml", @@ -710,7 +710,7 @@ Third}`; const result = await openEpub(archive); expect(result.type).toBe("document"); if (result.type !== "document") throw new Error("Expected document"); - expect(result.pages.map((page) => page.title)).toEqual(["Second", "First"]); + expect(result.pages.map((page) => page.title)).toEqual(["Second", "a".repeat(119)]); expect(result.pages[0]!.html).toContain("A\u00a0B © — ≂̸ &lt;"); expect(result.pages[0]!.html).toContain("
Use &amp; and &lt; literally
"); expect(result.pages[0]!.html).toContain( diff --git a/apps/web/src/components/files/extendedDocumentPreview.ts b/apps/web/src/components/files/extendedDocumentPreview.ts index db744de3cf48a..517e404f0a8c2 100644 --- a/apps/web/src/components/files/extendedDocumentPreview.ts +++ b/apps/web/src/components/files/extendedDocumentPreview.ts @@ -465,11 +465,10 @@ export async function openEpub(archive: JSZip): Promise { const entry = path ? archive.file(path) : null; if (!entry || !path) continue; const chapter = parseXml(await entry.async("string")); + const title = text(find(chapter, "title")[0] ?? find(chapter, "h1")[0] ?? chapter).trim(); + const last = title.charCodeAt(119); pages.push({ - title: - text(find(chapter, "title")[0] ?? find(chapter, "h1")[0] ?? chapter) - .trim() - .slice(0, 120) || undefined, + title: title.slice(0, last >= 0xd800 && last <= 0xdbff ? 119 : 120) || undefined, html: await epubHtml(chapter, archive, path), }); } From 009ae578d0b6ce3d1af317b9e259e25929680941 Mon Sep 17 00:00:00 2001 From: Victor Date: Wed, 25 Nov 2026 04:24:02 -0600 Subject: [PATCH 008/238] fix(web): long thread titles no longer break dropped thread attachment names (#42727) Co-authored-by: Julius Marminge --- apps/web/src/lib/threadContextAttachment.test.ts | 11 +++++++++++ apps/web/src/lib/threadContextAttachment.ts | 4 +++- 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/apps/web/src/lib/threadContextAttachment.test.ts b/apps/web/src/lib/threadContextAttachment.test.ts index 3d0fddd2b787f..b634c0934649f 100644 --- a/apps/web/src/lib/threadContextAttachment.test.ts +++ b/apps/web/src/lib/threadContextAttachment.test.ts @@ -84,4 +84,15 @@ describe("threadContextAttachment", () => { expect(first.name).toMatch(/^Same _ title_ notes-[a-f0-9]+\.jsonl$/); expect(first.name.length).toBeLessThan(255); }); + + it("does not split a surrogate pair when truncating long titles", () => { + const source = EnvironmentId.make("source"); + const threadId = ThreadId.make("surrogate-thread"); + const updatedAt = DateTime.makeUnsafe("2026-09-29T00:00:00.000Z"); + const title = `${"a".repeat(63)}𠀀`; + + const file = threadContextAttachment(source, { threadId, title, updatedAt, items: [] }); + + expect(file.name).toMatch(/^a{63}-[a-f0-9]+\.jsonl$/); + }); }); diff --git a/apps/web/src/lib/threadContextAttachment.ts b/apps/web/src/lib/threadContextAttachment.ts index 996b444d7f766..c8bfc5a9b5db3 100644 --- a/apps/web/src/lib/threadContextAttachment.ts +++ b/apps/web/src/lib/threadContextAttachment.ts @@ -1,4 +1,5 @@ import type { EnvironmentId, OrchestrationV2ThreadTranscript } from "@t3tools/contracts"; +import { splitsSurrogatePair } from "@t3tools/shared/assistantCitations"; import { toKindScopedComposerContextId } from "@t3tools/shared/composerContextReferences"; import { threadTranscriptHeader } from "@t3tools/shared/threadTranscript"; import * as DateTime from "effect/DateTime"; @@ -12,7 +13,8 @@ export function threadContextAttachment( "thread", `${environmentId}:${transcript.threadId}:${updatedAt}`, ); - const title = transcript.title.replace(/[^\p{L}\p{N}._ -]/gu, "_").slice(0, 64) || "Thread"; + const sanitized = transcript.title.replace(/[^\p{L}\p{N}._ -]/gu, "_"); + const title = sanitized.slice(0, splitsSurrogatePair(sanitized, 64) ? 63 : 64) || "Thread"; return new File( [ threadTranscriptHeader(environmentId, transcript), From f9da246cd5cbbf5c09b045dfcde6c76435608528 Mon Sep 17 00:00:00 2001 From: Stanislav Zmiev Date: Wed, 25 Nov 2026 14:27:27 +0400 Subject: [PATCH 009/238] fix(server): tasks delegated to an older linked machine report back when they finish (#42717) Co-authored-by: Julius Marminge --- apps/server/src/peer/RemoteDelegation.test.ts | 13 ++++++++----- apps/server/src/peer/RemoteDelegation.ts | 6 ++++-- 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/apps/server/src/peer/RemoteDelegation.test.ts b/apps/server/src/peer/RemoteDelegation.test.ts index d075c44ef9ff2..f925f65b48b09 100644 --- a/apps/server/src/peer/RemoteDelegation.test.ts +++ b/apps/server/src/peer/RemoteDelegation.test.ts @@ -451,7 +451,9 @@ const boxToolkitLayer = (thread: BoxThread) => { }, ]), ] - ).map((entry, position) => ({ ...entry, position })); + ) + // Position 0 is the task's prompt, which the follower reads past. + .map((entry, index) => ({ ...entry, position: index + 1 })); const visible = options.itemId === undefined ? replies.filter( @@ -492,7 +494,7 @@ const boxToolkitLayer = (thread: BoxThread) => { }), } as never, })), - totalItems: replies.length, + totalItems: replies.length + 1, hasMore: options.itemId === undefined && matching.length > 0 && @@ -1714,7 +1716,7 @@ it.effect.each(["tail-error", "middle-error", "reply-fallback", "cancel-refill"] const pages = reads.filter((read) => read.itemId === undefined && read.limit === 100); // A page moves on by however many items the response budget left it. const remaining = (read: OrchestratorMcpThreadReadInput) => - timeline.length - 1 - (read.afterPosition ?? -1); + timeline.length - (read.afterPosition ?? 0); expect(pages[0]).toMatchObject({ view: "activity", limit: 100, @@ -1832,8 +1834,9 @@ it.effect.each([ } const pages = reads.filter((read) => read.itemId === undefined && read.limit === 100); // The thread's final page starts at its canonical 100-item boundary. - const tailPosition = Math.floor((timeline.length - 1) / 100) * 100 - 1; - expect(pages.at(0)?.afterPosition).toBe(-1); + const tailPosition = Math.floor(timeline.length / 100) * 100 - 1; + // Starts after the prompt, a cursor every peer accepts. + expect(pages.at(0)?.afterPosition).toBe(0); expect( pages.every( (read) => diff --git a/apps/server/src/peer/RemoteDelegation.ts b/apps/server/src/peer/RemoteDelegation.ts index 5ed03b795b686..07033bf8f38f9 100644 --- a/apps/server/src/peer/RemoteDelegation.ts +++ b/apps/server/src/peer/RemoteDelegation.ts @@ -619,8 +619,10 @@ const make = Effect.gen(function* () { ) { let reply: OrchestratorMcpThreadTimelineItem | undefined; let error: OrchestratorMcpThreadTimelineItem | undefined; - // Linked peers read newest first without a cursor; this scan runs forward. - let afterPosition = -1; + // Linked peers read newest first without a cursor, so this scan runs forward. It starts + // after position 0, the message that started the thread, which no run's reply can precede; + // older peers refuse -1. + let afterPosition = 0; let run: OrchestratorMcpThreadRun | undefined; let remainingItems = 0; let tailProbed = false; From 4a34889e286344a519163482a8fa561123e5901f Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 25 Nov 2026 02:30:37 -0800 Subject: [PATCH 010/238] fix(server): diff panel reads GBK/GB18030 files instead of showing mojibake (#42735) --- apps/server/src/vcs/GitVcsDriverCore.test.ts | 85 ++++++++++++++++++++ apps/server/src/vcs/GitVcsDriverCore.ts | 64 ++++++++++++--- 2 files changed, 139 insertions(+), 10 deletions(-) diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.ts index 29484e835fed7..e715f10a7f642 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.test.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts @@ -4777,6 +4777,91 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); + it.effect("shows GBK-encoded files as readable text in the review diff and expansion", () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + yield* initRepoWithCommit(cwd); + const before = "// 初始中文注释\nint a = 1;\n"; + const after = "// 修改后的中文注释\nint a = 2;\n"; + // GBK bytes of `before` and `after`. + const writeMain = (hex: string) => + Effect.sync(() => + NodeFS.writeFileSync(NodePath.join(cwd, "main.c"), Buffer.from(hex, "hex")), + ); + yield* writeMain("2f2f20b3f5cabcd6d0cec4d7a2cacd0a696e742061203d20313b0a"); + yield* git(cwd, ["add", "main.c"]); + yield* git(cwd, ["commit", "-m", "add GBK file"]); + yield* writeMain("2f2f20d0deb8c4baf3b5c4d6d0cec4d7a2cacd0a696e742061203d20323b0a"); + const driver = yield* GitVcsDriver.GitVcsDriver; + + const preview = yield* driver.getReviewDiffPreview({ cwd }); + const diff = preview.sources.map((source) => source.diff).join("\n"); + assert.include(diff, "-// 初始中文注释"); + assert.include(diff, "+// 修改后的中文注释"); + + const contents = yield* driver.getReviewDiffFileContents( + makeReviewDiffFileContentsInput(cwd, { oldPath: "main.c", newPath: "main.c" }), + ); + assert.deepStrictEqual(contents, { oldContents: before, newContents: after }); + }), + ); + + // macOS and Windows filesystems reject file names that are not valid UTF-8. + it.effect.skipIf(HostProcess.Platform.defaultValue() !== "linux")( + "keeps UTF-8 paths intact next to a non-UTF-8 path in NUL-separated output", + () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + yield* initRepoWithCommit(cwd); + for (const name of ["文档.md", "café.md"]) { + NodeFS.writeFileSync(NodePath.join(cwd, name), "x\n"); + } + NodeFS.writeFileSync( + Buffer.concat([ + Buffer.from(`${cwd}/Gro`), + Buffer.from([0xf6, 0xdf]), + Buffer.from("e.c"), + ]), + "x\n", + ); + const driver = yield* GitVcsDriver.GitVcsDriver; + + const result = yield* driver.execute({ + operation: "test.lsFilesOthers", + cwd, + args: ["ls-files", "-z", "--others"], + }); + const paths = result.stdout.split("\0"); + assert.include(paths, "文档.md"); + assert.include(paths, "café.md"); + }), + ); + + it.effect("keeps truncated UTF-8 output as UTF-8 when the cap cuts a character", () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + yield* initRepoWithCommit(cwd); + const driver = yield* GitVcsDriver.GitVcsDriver; + const blob = yield* driver.execute({ + operation: "test.hashObject", + cwd, + args: ["hash-object", "-w", "--stdin"], + stdin: "a中文中文\n", + }); + + // "a" + "中" + the first byte of "文": the cap lands inside a UTF-8 character. + const result = yield* driver.execute({ + operation: "test.catFile", + cwd, + args: ["cat-file", "-p", blob.stdout.trim()], + maxOutputBytes: 5, + appendTruncationMarker: true, + }); + assert.isTrue(result.stdoutTruncated); + assert.strictEqual(result.stdout, "a中\uFFFD"); + }), + ); + it.effect("reads a base ref that looks like an option as a revision", () => Effect.gen(function* () { const cwd = yield* makeTmpDir(); diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index 5fcddc70e144a..dd0fe8796e1ef 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -932,6 +932,51 @@ export function parseGitCheckoutProgressLine( const OUTPUT_LINE_SEPARATOR = /\r\n|\r|\n/; +const strictUtf8Decoder = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }); +const lenientUtf8Decoder = new TextDecoder("utf-8", { ignoreBOM: true }); +const gb18030Decoder = new TextDecoder("gb18030", { ignoreBOM: true }); + +// A byte cap can cut the last UTF-8 character; that tail is not evidence of another encoding. +const decodeStrictUtf8 = (bytes: Uint8Array, truncated: boolean): string => { + if (!truncated) return strictUtf8Decoder.decode(bytes); + const decoder = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }); + const text = decoder.decode(bytes, { stream: true }); + try { + return text + decoder.decode(); + } catch { + return `${text}\uFFFD`; + } +}; + +const decodeUtf8OrGb18030 = (bytes: Uint8Array, truncated: boolean): string => { + try { + return decodeStrictUtf8(bytes, truncated); + } catch { + const fallback = gb18030Decoder.decode(bytes); + return fallback.includes("\uFFFD") ? lenientUtf8Decoder.decode(bytes) : fallback; + } +}; + +// Git emits file bytes as stored; without a working-tree-encoding attribute, GBK/GB18030 +// sources are not UTF-8. Decode per LF line or NUL record (`-z` output) so one such file or +// path does not garble UTF-8 neighbours. +const decodeGitText = (bytes: Uint8Array, truncated = false): string => { + try { + return decodeStrictUtf8(bytes, truncated); + } catch { + let text = ""; + let start = 0; + while (start < bytes.length) { + let end = start; + while (end < bytes.length && bytes[end] !== 0x0a && bytes[end] !== 0x00) end += 1; + end = Math.min(end + 1, bytes.length); + text += decodeUtf8OrGb18030(bytes.subarray(start, end), truncated && end === bytes.length); + start = end; + } + return text; + } +}; + const collectOutput = Effect.fnUntraced(function* ( input: Pick, stream: Stream.Stream, @@ -940,10 +985,10 @@ const collectOutput = Effect.fnUntraced(function* ( onLine: ((line: string) => Effect.Effect) | undefined, keepLineCallbacksAfterTruncation = false, ): Effect.fn.Return<{ readonly text: string; readonly truncated: boolean }, GitCommandError> { - const decoder = new TextDecoder("utf-8", { ignoreBOM: true }); const lineDecoder = keepLineCallbacksAfterTruncation && onLine ? new TextDecoder() : null; + const lineStreamDecoder = new TextDecoder("utf-8", { ignoreBOM: true }); + const chunks: Array = []; let bytes = 0; - let text = ""; let lineBuffer = ""; let truncated = false; // Bound newline-free output; oversized lines are not useful to callbacks. @@ -995,10 +1040,11 @@ const collectOutput = Effect.fnUntraced(function* ( bytes += chunkToDecode.byteLength; truncated = appendTruncationMarker && nextBytes > maxOutputBytes; - const decoded = decoder.decode(chunkToDecode, { stream: !truncated }); - text += decoded; + chunks.push(chunkToDecode); if (onLine) { - lineBuffer += lineDecoder ? lineDecoder.decode(chunk, { stream: true }) : decoded; + lineBuffer += lineDecoder + ? lineDecoder.decode(chunk, { stream: true }) + : lineStreamDecoder.decode(chunkToDecode, { stream: !truncated }); yield* emitCompleteLines(false); } }); @@ -1014,15 +1060,13 @@ const collectOutput = Effect.fnUntraced(function* ( }), ); - const remainder = truncated ? "" : decoder.decode(); - text += remainder; if (onLine) { - lineBuffer += remainder; + if (!truncated && !lineDecoder) lineBuffer += lineStreamDecoder.decode(); if (lineDecoder) lineBuffer += lineDecoder.decode(); yield* emitCompleteLines(true); } return { - text, + text: decodeGitText(Buffer.concat(chunks), truncated), truncated, }; }); @@ -5184,7 +5228,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* if (bytes.includes(0)) { return yield* fileError("fs.readFile", `Cannot expand binary file '${input.newPath}'.`); } - const contents = new TextDecoder("utf-8", { ignoreBOM: true }).decode(bytes); + const contents = decodeGitText(bytes); if (!contents.includes("$Id:")) return contents; const collapsed = contents.replace(GIT_IDENT_KEYWORD, () => "$Id$"); if (collapsed === contents) return contents; From e8fb0a0d4364e8a17689fb4f7db554e036cacc36 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 25 Nov 2026 02:54:06 -0800 Subject: [PATCH 011/238] fix(server): Claude skill picker lists only the skills a marketplace entry declares (#42743) --- .../src/provider/Drivers/ClaudeSkills.test.ts | 59 +++++++++ .../src/provider/Drivers/ClaudeSkills.ts | 124 ++++++++++++++---- 2 files changed, 161 insertions(+), 22 deletions(-) diff --git a/apps/server/src/provider/Drivers/ClaudeSkills.test.ts b/apps/server/src/provider/Drivers/ClaudeSkills.test.ts index f9112247cab81..bb2b8ecc9a690 100644 --- a/apps/server/src/provider/Drivers/ClaudeSkills.test.ts +++ b/apps/server/src/provider/Drivers/ClaudeSkills.test.ts @@ -85,6 +85,65 @@ it.layer(NodeServices.layer)("discoverClaudeSkills", (it) => { }), ); + it.effect("loads only the skills a non-strict marketplace entry declares", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-claude-skills-" }); + const configDir = path.join(tempDir, "claude-home"); + const marketplace = path.join(tempDir, "marketplace"); + const marketplaceJson = JSON.stringify({ + name: "shared-root", + plugins: [ + { name: "collection-a", source: "./", strict: false, skills: ["./skills/skill-one"] }, + { name: "collection-b", source: "./", strict: false, skills: ["./skills/skill-two"] }, + ], + }); + // `claude plugin install` copies the whole repository into each plugin's cache folder. + const installs = ["collection-a", "collection-b"].map((name) => + path.join(configDir, "plugins", "cache", "shared-root", name, "abc123"), + ); + for (const root of [marketplace, ...installs]) { + yield* writeSkill(path.join(root, "skills"), "skill-one", "# One"); + yield* writeSkill(path.join(root, "skills"), "skill-two", "# Two"); + yield* fs.makeDirectory(path.join(root, ".claude-plugin"), { recursive: true }); + yield* fs.writeFileString( + path.join(root, ".claude-plugin", "marketplace.json"), + marketplaceJson, + ); + } + yield* fs.writeFileString( + path.join(configDir, "plugins", "known_marketplaces.json"), + JSON.stringify({ + "shared-root": { + source: { source: "directory", path: marketplace }, + installLocation: marketplace, + }, + }), + ); + yield* fs.writeFileString( + path.join(configDir, "plugins", "installed_plugins.json"), + JSON.stringify({ + version: 2, + plugins: { + "collection-a@shared-root": [{ scope: "user", installPath: installs[0] }], + "collection-b@shared-root": [{ scope: "user", installPath: installs[1] }], + }, + }), + ); + yield* fs.writeFileString( + path.join(configDir, "settings.json"), + '{"enabledPlugins":{"collection-a@shared-root":true,"collection-b@shared-root":true}}', + ); + + const skills = yield* discoverClaudeSkills({ homePath: configDir }); + assert.deepEqual( + skills.map((skill) => skill.name), + ["collection-a:skill-one", "collection-b:skill-two"], + ); + }), + ); + it.effect("merges plugin enablement and selects installs in native registry order", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; diff --git a/apps/server/src/provider/Drivers/ClaudeSkills.ts b/apps/server/src/provider/Drivers/ClaudeSkills.ts index 05bb7f197c80f..a6c196bd9085d 100644 --- a/apps/server/src/provider/Drivers/ClaudeSkills.ts +++ b/apps/server/src/provider/Drivers/ClaudeSkills.ts @@ -347,6 +347,20 @@ const PluginManifest = Schema.fromJsonString( defaultEnabled: Schema.optional(Schema.Unknown), }), ); +const KnownMarketplaces = Schema.fromJsonString(Schema.Record(Schema.String, Schema.Unknown)); +const decodeKnownMarketplace = Schema.decodeUnknownOption( + Schema.Struct({ installLocation: Schema.NonEmptyString }), +); +const MarketplaceManifest = Schema.fromJsonString( + Schema.Struct({ plugins: Schema.Array(Schema.Unknown) }), +); +const decodeMarketplaceEntry = Schema.decodeUnknownOption( + Schema.Struct({ + name: Schema.String, + source: Schema.Unknown, + skills: Schema.optional(Schema.Union([Schema.String, Schema.Array(Schema.String)])), + }), +); const SyncedPlugins = Schema.fromJsonString( Schema.Struct({ plugins: Schema.Array(Schema.Unknown) }), @@ -389,32 +403,18 @@ const readPluginManifest = Effect.fn("readPluginManifest")(function* (pluginPath ); }); -const pluginSkillRoots = Effect.fn("pluginSkillRoots")(function* ( +/** Declared skill folders that exist inside the install, through symlinks too, as the native loader requires. */ +const containedSkillDirectories = Effect.fn("containedSkillDirectories")(function* ( installPath: string, - scope: ClaudeSkillScope, - prefix: string, - manifest: typeof PluginManifest.Type | undefined, + declared: ReadonlyArray, ) { const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; - const roots: Array = []; - const defaultDirectory = path.join(installPath, "skills"); - const hasDefaultDirectory = yield* fileSystem - .exists(defaultDirectory) - .pipe(Effect.orElseSucceed(() => false)); - if (hasDefaultDirectory) roots.push({ directory: defaultDirectory, scope, prefix }); - const declared = manifest?.skills; - if (declared === undefined && !hasDefaultDirectory) { - const hasRootSkill = yield* fileSystem - .exists(path.join(installPath, "SKILL.md")) - .pipe(Effect.orElseSucceed(() => false)); - if (hasRootSkill) roots.push({ directory: installPath, scope, prefix }); - } - const canonicalInstallPath = yield* fileSystem .realPath(installPath) .pipe(Effect.orElseSucceed(() => undefined)); - for (const relative of typeof declared === "string" ? [declared] : (declared ?? [])) { + const directories: Array = []; + for (const relative of declared) { const directory = path.resolve(installPath, relative); if (!isInsideDirectory(path, installPath, directory) || canonicalInstallPath === undefined) { continue; @@ -422,14 +422,53 @@ const pluginSkillRoots = Effect.fn("pluginSkillRoots")(function* ( const canonicalDirectory = yield* fileSystem .realPath(directory) .pipe(Effect.orElseSucceed(() => undefined)); - // The native loader rejects manifest roots that escape through a symlink, too. if ( canonicalDirectory !== undefined && isInsideDirectory(path, canonicalInstallPath, canonicalDirectory) ) { - roots.push({ directory, scope, prefix }); + directories.push(directory); } } + return directories; +}); + +const pluginSkillRoots = Effect.fn("pluginSkillRoots")(function* ( + installPath: string, + scope: ClaudeSkillScope, + prefix: string, + manifest: typeof PluginManifest.Type | undefined, + entrySkills?: ReadonlyArray, +) { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const defaultDirectory = path.join(installPath, "skills"); + // A root-sourced marketplace entry's skills list replaces the plugin's skills; `./` means skills/. + const entryDirectories = + entrySkills === undefined ? [] : yield* containedSkillDirectories(installPath, entrySkills); + if (entryDirectories.length > 0) { + return entryDirectories.map((directory) => ({ + directory: directory === installPath ? defaultDirectory : directory, + scope, + prefix, + })); + } + const roots: Array = []; + const hasDefaultDirectory = yield* fileSystem + .exists(defaultDirectory) + .pipe(Effect.orElseSucceed(() => false)); + if (hasDefaultDirectory) roots.push({ directory: defaultDirectory, scope, prefix }); + const declared = manifest?.skills; + if (declared === undefined && !hasDefaultDirectory) { + const hasRootSkill = yield* fileSystem + .exists(path.join(installPath, "SKILL.md")) + .pipe(Effect.orElseSucceed(() => false)); + if (hasRootSkill) roots.push({ directory: installPath, scope, prefix }); + } + const declaredDirectories = yield* containedSkillDirectories( + installPath, + typeof declared === "string" ? [declared] : (declared ?? []), + ); + for (const directory of declaredDirectories) roots.push({ directory, scope, prefix }); return roots; }); @@ -567,6 +606,42 @@ const discoverPluginSkillRoots = Effect.fn("discoverPluginSkillRoots")(function* const projectRepositoryRoots = new Map(); const repositoryRoot = workspace === undefined ? undefined : yield* findPluginRepositoryRoot(workspace); + const knownMarketplaces = yield* fileSystem + .readFileString(path.join(pluginsPath, "known_marketplaces.json")) + .pipe( + Effect.flatMap(Schema.decodeUnknownEffect(KnownMarketplaces)), + Effect.orElseSucceed((): Record => ({})), + ); + const marketplaceEntries = new Map>(); + // Claude applies an entry's skills list only when the entry's source is the marketplace root. + const readRootEntrySkills = Effect.fnUntraced(function* (marketplace: string, plugin: string) { + if (!marketplaceEntries.has(marketplace)) { + const location = Option.getOrUndefined( + decodeKnownMarketplace(knownMarketplaces[marketplace]), + )?.installLocation; + const manifest = + location === undefined + ? undefined + : yield* fileSystem + .readFileString(path.join(location, ".claude-plugin", "marketplace.json")) + .pipe( + Effect.flatMap(Schema.decodeUnknownEffect(MarketplaceManifest)), + Effect.orElseSucceed(() => undefined), + ); + marketplaceEntries.set(marketplace, manifest?.plugins ?? []); + } + const entry = (marketplaceEntries.get(marketplace) ?? []) + .flatMap((candidate) => Option.toArray(decodeMarketplaceEntry(candidate))) + .find((candidate) => candidate.name === plugin); + if ( + entry?.skills === undefined || + typeof entry.source !== "string" || + !entry.source.split(/[\\/]/).every((segment) => segment === "" || segment === ".") + ) { + return undefined; + } + return typeof entry.skills === "string" ? [entry.skills] : entry.skills; + }); for (const [key, entries] of Object.entries(installed?.plugins ?? {}).sort()) { if (enabledPlugins.get(key) !== true) continue; @@ -600,7 +675,12 @@ const discoverPluginSkillRoots = Effect.fn("discoverPluginSkillRoots")(function* if (!prefix || inlinePluginNames.has(pluginNameKey(prefix))) continue; // A registry record whose install is gone loads nothing and claims no namespace. if (Option.isSome(existing)) claimedPluginNames.add(pluginNameKey(prefix)); - roots.push(...(yield* pluginSkillRoots(installPath, scope, prefix, manifest))); + const separator = key.lastIndexOf("@"); + const entrySkills = + separator > 0 + ? yield* readRootEntrySkills(key.slice(separator + 1), key.slice(0, separator)) + : undefined; + roots.push(...(yield* pluginSkillRoots(installPath, scope, prefix, manifest, entrySkills))); } if (syncedBucket === undefined) return roots; From 45a3880ce1aebbfe4a3669ab9966e3497ec01f2a Mon Sep 17 00:00:00 2001 From: Victor Date: Wed, 25 Nov 2026 04:57:15 -0600 Subject: [PATCH 012/238] fix(server): PowerPoint attachment text no longer includes slide animation names (#42741) Co-authored-by: Julius Marminge --- apps/server/src/provider/documentTextWorker.ts | 5 +++++ apps/server/src/provider/userInputAttachments.test.ts | 8 ++++++-- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/apps/server/src/provider/documentTextWorker.ts b/apps/server/src/provider/documentTextWorker.ts index 84521565d0f79..36f635784b9f2 100644 --- a/apps/server/src/provider/documentTextWorker.ts +++ b/apps/server/src/provider/documentTextWorker.ts @@ -124,6 +124,11 @@ function xml(source: string, extension: string): XmlNode { (prop) => prop.name === "vanish" && ["true", "1", "on"].includes(prop.attrs.val ?? "1"), )) || (odf && node.name === "annotation" && parent.name !== "semantics") || + (extension === ".pptx" && + node.name === "timing" && + stack.every((ancestor) => + ["root", "sld", "AlternateContent", "Choice", "Fallback"].includes(ancestor.name), + )) || (extension === ".odp" && node.name === "page-thumbnail" && stack.some((ancestor) => ancestor.name === "notes")) diff --git a/apps/server/src/provider/userInputAttachments.test.ts b/apps/server/src/provider/userInputAttachments.test.ts index 8e4d7322de740..d51ec07e755bc 100644 --- a/apps/server/src/provider/userInputAttachments.test.ts +++ b/apps/server/src/provider/userInputAttachments.test.ts @@ -1165,8 +1165,10 @@ describe("question answer paths", () => { `, "ppt/_rels/presentation.xml.rels": '', - "ppt/slides/slide1.xml": "Departure", - "ppt/slides/slide2.xml": "Juniper Pier", + "ppt/slides/slide1.xml": + 'Departurestyle.visibility', + "ppt/slides/slide2.xml": + 'Juniper Pierppt_x', "ppt/slides/_rels/slide2.xml.rels": '', "ppt/slides/_rels/slide1.xml.rels": @@ -1190,6 +1192,8 @@ describe("question answer paths", () => { "11/21/2026", "Crew only", "57", + "style.visibility", + "ppt_x", "[Skipped document part", "[Extracted text truncated", ], From 21a96989b07cf9156053880236a928e10baaeef8 Mon Sep 17 00:00:00 2001 From: AymanKhan9 Date: Wed, 25 Nov 2026 16:35:43 +0530 Subject: [PATCH 013/238] fix(web): include reopened issue selection in the /issues URL (#42745) Co-authored-by: Julius Marminge --- .../ReopenClosedViewShortcut.browser.test.tsx | 44 ++++++++++++++++++- .../components/ReopenClosedViewShortcut.tsx | 18 +++++--- apps/web/src/reopenClosedView.ts | 18 ++++++++ 3 files changed, 72 insertions(+), 8 deletions(-) diff --git a/apps/web/src/components/ReopenClosedViewShortcut.browser.test.tsx b/apps/web/src/components/ReopenClosedViewShortcut.browser.test.tsx index 2b3e9bfb96c14..3298af7822c89 100644 --- a/apps/web/src/components/ReopenClosedViewShortcut.browser.test.tsx +++ b/apps/web/src/components/ReopenClosedViewShortcut.browser.test.tsx @@ -83,7 +83,11 @@ vi.mock(import("./ui/toast"), async (original) => { }); import { useClosedViewStore } from "../closedViewStore"; -import { selectThreadRightPanelState, useRightPanelStore } from "../rightPanelStore"; +import { + ISSUES_PANEL_REF, + selectThreadRightPanelState, + useRightPanelStore, +} from "../rightPanelStore"; import { useTerminalUiStateStore } from "../terminalUiStateStore"; import { ReopenClosedViewShortcut } from "./ReopenClosedViewShortcut"; @@ -358,6 +362,44 @@ describe("root reopen shortcut", () => { expect(useClosedViewStore.getState().entries).toEqual([]); }, ); + it("includes the reopened issue selection in the /issues URL", async () => { + setup(); + const issueSurface = { + id: "issue:remote:project-1:github:github.com:pingdotgg/t3code:42" as const, + kind: "issue" as const, + environmentId: "remote", + projectId: "project-1", + tracker: "github", + host: "github.com", + scope: "pingdotgg/t3code", + key: "42", + }; + useClosedViewStore.getState().remember({ + kind: "panel-tab", + threadRef: ISSUES_PANEL_REF, + surface: issueSurface, + }); + await using _view = await renderShortcut(); + + await act(() => { + press(); + }); + + expect(state.navigate).toHaveBeenCalledWith( + expect.objectContaining({ + to: "/issues", + search: expect.objectContaining({ + selectedEnvironmentId: "remote", + selectedProjectId: "project-1", + selectedHost: "github.com", + tracker: "github", + scope: "pingdotgg/t3code", + key: "42", + }), + }), + ); + }); + it("forwards address-bar focus, zoom, and panel new and close from a focused desktop page", async () => { setup(); await using _shortcut = await renderShortcut(); diff --git a/apps/web/src/components/ReopenClosedViewShortcut.tsx b/apps/web/src/components/ReopenClosedViewShortcut.tsx index 1bc9d62a20c8e..7fa558148e611 100644 --- a/apps/web/src/components/ReopenClosedViewShortcut.tsx +++ b/apps/web/src/components/ReopenClosedViewShortcut.tsx @@ -22,6 +22,7 @@ import { isTerminalFocused } from "../lib/terminalFocus"; import { isModelPickerOpen } from "../modelPickerVisibility"; import { planNextReopen, + issuesSearchForRestore, pullRequestsSearchForRestore, reopenClosedView, } from "../reopenClosedView"; @@ -154,17 +155,20 @@ export function ReopenClosedViewShortcut() { if (router.history.location !== request.location) return; let destination; - if (globalPullRequests) { + if (globalPullRequests || globalIssues) { const selected = selectSelectedRightPanelSurface( useRightPanelStore.getState().byThreadKey, ref, ); - destination = linkOptions({ - to: "/pull-requests", - search: (previous) => pullRequestsSearchForRestore(previous, selected), - }); - } else if (globalIssues) { - destination = linkOptions({ to: "/issues", search: readIssueListPreferences() }); + destination = globalPullRequests + ? linkOptions({ + to: "/pull-requests", + search: (previous) => pullRequestsSearchForRestore(previous, selected), + }) + : linkOptions({ + to: "/issues", + search: issuesSearchForRestore(readIssueListPreferences(), selected), + }); } else { const draftId = thread === null ? drafts.getDraftIdByRef(ref) : null; destination = diff --git a/apps/web/src/reopenClosedView.ts b/apps/web/src/reopenClosedView.ts index cff3810a7b348..69cedab7cbf80 100644 --- a/apps/web/src/reopenClosedView.ts +++ b/apps/web/src/reopenClosedView.ts @@ -91,6 +91,24 @@ export function pullRequestsSearchForRestore( } as S & PullRequestListPreferences; } +export function issuesSearchForRestore( + preferences: S, + selected: RightPanelSurface | null, +) { + if (selected?.kind !== "issue") return preferences; + return { + ...preferences, + ...(selected.environmentId === undefined + ? {} + : { selectedEnvironmentId: selected.environmentId as EnvironmentId }), + selectedProjectId: selected.projectId as ProjectId, + ...(selected.host === undefined ? {} : { selectedHost: selected.host }), + tracker: selected.tracker, + scope: selected.scope, + key: selected.key, + }; +} + export async function reopenClosedView( view: ClosedView, options: { From f99eceb76dac7c8ee405a0c71dd9a5dd4a32d700 Mon Sep 17 00:00:00 2001 From: Victor Date: Wed, 25 Nov 2026 05:38:01 -0600 Subject: [PATCH 014/238] fix(web): reasoning previews no longer cut emojis in half (#42755) Co-authored-by: Julius Marminge --- .../chat/MessagesTimeline.browser.test.tsx | 28 ++++++++++++++++++- .../chat/TimelineWorkEntryRow.logic.ts | 10 +++++++ .../components/chat/TimelineWorkEntryRow.tsx | 7 ++--- .../components/chat/TimelineWorkGroupRows.tsx | 6 ++-- 4 files changed, 42 insertions(+), 9 deletions(-) diff --git a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx index 222f498e7123a..45ba21665b2fe 100644 --- a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx @@ -43,7 +43,11 @@ import { deriveTimelineEntriesFromVisibleTurnItems, } from "../../session-logic"; import { ViewedImagesTimelineRow } from "./TimelineWorkEntryRow"; -import { THOUGHT_PREVIEW_MAX_LENGTH, thoughtPreviewMarkdown } from "./TimelineWorkEntryRow.logic"; +import { + THOUGHT_PREVIEW_MAX_LENGTH, + THOUGHT_PREVIEW_SOURCE_MAX_LENGTH, + thoughtPreviewMarkdown, +} from "./TimelineWorkEntryRow.logic"; import { wordsHast } from "~/markdown/wordsHast"; import { TimelineRowCtx } from "./timelineRowContext"; import { searchableMessageSegments } from "@t3tools/shared/threadFindText"; @@ -2302,6 +2306,28 @@ describe("compact reasoning math", () => { ), ).toEqual(expected); }); + + it("does not split a surrogate pair at the reasoning preview source limit", async () => { + setup(); + const prefix = `[l](${"u".repeat(8_100)}) `; + const filler = "c".repeat(THOUGHT_PREVIEW_SOURCE_MAX_LENGTH - 1 - prefix.length); + await using screen = await renderTimeline( + [ + work("thought-1", { + label: "Thinking", + tone: "thinking", + itemType: "reasoning", + toolLifecycleStatus: "inProgress", + detail: `${prefix}${filler}😀 tail`, + }), + ], + { isWorking: true }, + ); + await vi.waitFor(() => { + expect(screen.text()).toContain(`l ${filler}`); + }); + expect(screen.text()).not.toContain("\uFFFD"); + }); }); it("renders automatic compaction as one live divider that finishes with its reason and token delta", async () => { diff --git a/apps/web/src/components/chat/TimelineWorkEntryRow.logic.ts b/apps/web/src/components/chat/TimelineWorkEntryRow.logic.ts index 894f58f45edb4..098d69f38c81c 100644 --- a/apps/web/src/components/chat/TimelineWorkEntryRow.logic.ts +++ b/apps/web/src/components/chat/TimelineWorkEntryRow.logic.ts @@ -4,6 +4,7 @@ import { resolveWorkEntryToolPresentation, toolGroupAction, } from "@t3tools/client-runtime/work-log/presentation"; +import { splitsSurrogatePair } from "@t3tools/shared/assistantCitations"; import { isJavaScriptReplTool } from "@t3tools/shared/toolActivity"; import { formatWorkspaceRelativePath } from "../../filePathDisplay"; import { m, type MessageResolver } from "../../i18n/messages"; @@ -208,6 +209,15 @@ export function workEntryIconName(workEntry: TimelineWorkEntry): WorkEntryIconNa export const THOUGHT_PREVIEW_SOURCE_MAX_LENGTH = 8_192; export const THOUGHT_PREVIEW_MAX_LENGTH = 2_048; +export function sliceThoughtPreviewSource(text: string): string { + return text.slice( + 0, + splitsSurrogatePair(text, THOUGHT_PREVIEW_SOURCE_MAX_LENGTH) + ? THOUGHT_PREVIEW_SOURCE_MAX_LENGTH - 1 + : THOUGHT_PREVIEW_SOURCE_MAX_LENGTH, + ); +} + const thoughtPreviews = new Map(); /** Compact reasoning keeps formulas while flattening other Markdown into label text. */ diff --git a/apps/web/src/components/chat/TimelineWorkEntryRow.tsx b/apps/web/src/components/chat/TimelineWorkEntryRow.tsx index a2d2a5f9bacef..5662814a6821e 100644 --- a/apps/web/src/components/chat/TimelineWorkEntryRow.tsx +++ b/apps/web/src/components/chat/TimelineWorkEntryRow.tsx @@ -79,8 +79,8 @@ import { workEntryRawCommand, buildToolCallExpandedBody, workEntryIconName, + sliceThoughtPreviewSource, thoughtPreviewMarkdown, - THOUGHT_PREVIEW_SOURCE_MAX_LENGTH, } from "./TimelineWorkEntryRow.logic"; export function useThreadReadTarget(entry: TimelineWorkEntry, environmentId: EnvironmentId) { @@ -603,10 +603,7 @@ function WorkEntryLogRow(props: WorkEntryRowProps) { {isReasoning && !expanded ? ( Date: Wed, 25 Nov 2026 05:45:47 -0600 Subject: [PATCH 015/238] fix(web): held overlay and Usage shortcuts no longer flicker (#42757) Co-authored-by: Julius Marminge --- .../commandPaletteCommands.browser.test.tsx | 44 ++++++++++++++++++- .../src/shortcuts/commandPaletteCommands.ts | 3 ++ 2 files changed, 46 insertions(+), 1 deletion(-) diff --git a/apps/web/src/shortcuts/commandPaletteCommands.browser.test.tsx b/apps/web/src/shortcuts/commandPaletteCommands.browser.test.tsx index 14054438242a5..92a090def3123 100644 --- a/apps/web/src/shortcuts/commandPaletteCommands.browser.test.tsx +++ b/apps/web/src/shortcuts/commandPaletteCommands.browser.test.tsx @@ -9,10 +9,13 @@ import { useCommandPaletteMount, useCommandPaletteStore, } from "../commandPaletteStore"; +import { useThemeEditorStore } from "../components/settings/themeEditorStore"; import { installCommandPaletteCommands } from "./commandPaletteCommands"; const keybindings = compileResolvedKeybindingsConfig([ { key: "mod+k", command: "commandPalette.toggle" }, + { key: "mod+alt+shift+t", command: "themeEditor.toggle" }, + { key: "mod+u", command: "usage.open" }, ]); function MountedPalette() { @@ -22,6 +25,7 @@ function MountedPalette() { function setup() { useCommandPaletteStore.setState(useCommandPaletteStore.getInitialState(), true); + useThemeEditorStore.setState(useThemeEditorStore.getInitialState(), true); } describe("command palette shortcuts", () => { @@ -39,7 +43,7 @@ describe("command palette shortcuts", () => { expect(useCommandPaletteStore.getState().open).toBe(false); }); - it("open the palette while it is mounted, and it closes when it unmounts", async () => { + it("open the palette while it is mounted, keep it open on repeat, and it closes when it unmounts", async () => { setup(); using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("Linux x86_64"); await using screen = await render(, { router: "/" }); @@ -51,6 +55,17 @@ describe("command palette shortcuts", () => { await userEvent.keyboard("{Control>}k{/Control}"); expect(useCommandPaletteStore.getState().open).toBe(true); + const repeatEvent = new KeyboardEvent("keydown", { + key: "k", + ctrlKey: true, + repeat: true, + bubbles: true, + cancelable: true, + }); + document.body.dispatchEvent(repeatEvent); + expect(repeatEvent.defaultPrevented).toBe(true); + expect(useCommandPaletteStore.getState().open).toBe(true); + await screen.rerender(
); expect(useCommandPaletteStore.getState().open).toBe(false); }); @@ -137,6 +152,33 @@ describe("command palette shortcuts", () => { expect(freshEscape.defaultPrevented).toBe(true); expect(useCommandPaletteStore.getState()).toMatchObject({ open: true, mode: "command" }); }); + + it("ignore held theme editor and Usage shortcuts", async () => { + setup(); + using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("Linux x86_64"); + await using screen = await render(, { router: "/" }); + using commands = new DisposableStack(); + commands.defer( + installCommandPaletteCommands(screen.router!, { keybindings: () => keybindings }), + ); + using navigate = vi.spyOn(screen.router!, "navigate").mockResolvedValue(undefined); + + for (const keys of [ + { key: "T", ctrlKey: true, altKey: true, shiftKey: true }, + { key: "u", ctrlKey: true }, + ]) { + const event = new KeyboardEvent("keydown", { + ...keys, + repeat: true, + bubbles: true, + cancelable: true, + }); + document.body.dispatchEvent(event); + expect(event.defaultPrevented, keys.key).toBe(true); + } + expect(useThemeEditorStore.getState().session).toBeNull(); + expect(navigate).not.toHaveBeenCalled(); + }); }); describe("openCommandPalette", () => { diff --git a/apps/web/src/shortcuts/commandPaletteCommands.ts b/apps/web/src/shortcuts/commandPaletteCommands.ts index 9420e4ed5911d..68425ae552960 100644 --- a/apps/web/src/shortcuts/commandPaletteCommands.ts +++ b/apps/web/src/shortcuts/commandPaletteCommands.ts @@ -28,6 +28,7 @@ const toggleOverlay = const mode = overlayModeForCommand(command); if (mode === null) return false; consume(event); + if (event.repeat) return; dispatchCommandPalette({ _tag: "ToggleMode", mode }); }; @@ -92,11 +93,13 @@ export function installCommandPaletteCommands( }, "themeEditor.toggle": (event) => { consume(event); + if (event.repeat) return; const { theme, themeHalves, resolvedTheme } = getThemeSnapshot(); toggleThemeEditorForTheme({ theme, themeHalves, initialAppearance: resolvedTheme }); }, "usage.open": (event) => { consume(event); + if (event.repeat) return; dispatchCommandPalette({ _tag: "SetOpen", open: false }); void router.navigate({ to: "/usage" }); }, From 3a63e0ca37a50d31f78b0188960557ff69964e76 Mon Sep 17 00:00:00 2001 From: Thomas Molinari <100191128+thomas0903@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:04:14 +1100 Subject: [PATCH 016/238] fix(web): expanding linked issues no longer hides thread details sections (#42771) Co-authored-by: Julius Marminge --- .../chat/ThreadDetailsCard.browser.test.tsx | 16 ++++++++ .../src/components/chat/ThreadDetailsCard.tsx | 6 +-- .../chat/ThreadDetailsIssueRows.tsx | 40 ++++++++++--------- .../chat/ThreadDetailsPrRow.browser.test.tsx | 2 + 4 files changed, 43 insertions(+), 21 deletions(-) diff --git a/apps/web/src/components/chat/ThreadDetailsCard.browser.test.tsx b/apps/web/src/components/chat/ThreadDetailsCard.browser.test.tsx index e234686d6ff0c..b03b58e10f4e2 100644 --- a/apps/web/src/components/chat/ThreadDetailsCard.browser.test.tsx +++ b/apps/web/src/components/chat/ThreadDetailsCard.browser.test.tsx @@ -45,6 +45,7 @@ function Card({ rows = 1, automationRows = 0, serverOverflowRows = 0, + issueListRows = 0, }: { threadRef: ScopedThreadRef; inline: boolean; @@ -55,6 +56,8 @@ function Card({ automationRows?: number; /** Rows of 100px that expanded server lists add, which density ignores. */ serverOverflowRows?: number; + /** Rows of 100px that expanded linked issues add, which density ignores. */ + issueListRows?: number; }) { return ( // The web root renders in StrictMode, which re-runs ref callbacks on every mount. @@ -92,6 +95,9 @@ function Card({ style={{ height: serverOverflowRows * 100 }} /> ) : null} + {issueListRows > 0 ? ( +
+ ) : null} )} @@ -196,3 +202,13 @@ it("stays full while expanded server rows overflow", async () => { .element(page.getByRole("region", { name: "Thread details" })) .toHaveAttribute("data-density", "full"); }); + +it("stays full while expanded issue rows overflow", async () => { + using fixture = setup(); + await using _screen = await render( + , + ); + await expect + .element(page.getByRole("region", { name: "Thread details" })) + .toHaveAttribute("data-density", "full"); +}); diff --git a/apps/web/src/components/chat/ThreadDetailsCard.tsx b/apps/web/src/components/chat/ThreadDetailsCard.tsx index 9959dbe2dc41c..aadb47d0724ce 100644 --- a/apps/web/src/components/chat/ThreadDetailsCard.tsx +++ b/apps/web/src/components/chat/ThreadDetailsCard.tsx @@ -80,10 +80,10 @@ export function ThreadDetailsCard({ const measure = () => { const frame = element.closest("[data-thread-details-card]"); const next = element.offsetHeight + (frame ? frame.offsetHeight - frame.clientHeight : 0); - // PR lists, servers, lineage, side chats and automations scroll as they grow. Counting them - // toward density would hide the section and workspace controls when the user asks to see more. + // PR and issue lists, servers, lineage, side chats and automations scroll as they grow. + // Counting them toward density would hide the section and workspace controls when the user asks to see more. const lists = element.querySelectorAll( - "[data-thread-relationships-panel], [data-thread-side-chats-panel], [data-thread-details-pr-list], [data-thread-automations-panel], [data-thread-details-server-overflow]", + "[data-thread-relationships-panel], [data-thread-side-chats-panel], [data-thread-details-pr-list], [data-thread-details-issue-list], [data-thread-automations-panel], [data-thread-details-server-overflow]", ); const fittingHeight = next - Array.from(lists).reduce((sum, list) => sum + list.offsetHeight, 0); diff --git a/apps/web/src/components/chat/ThreadDetailsIssueRows.tsx b/apps/web/src/components/chat/ThreadDetailsIssueRows.tsx index 5726d1edeca14..36776560c594a 100644 --- a/apps/web/src/components/chat/ThreadDetailsIssueRows.tsx +++ b/apps/web/src/components/chat/ThreadDetailsIssueRows.tsx @@ -160,27 +160,31 @@ export function ThreadDetailsIssueRows({ const [expandedThread, setExpandedThread] = useState(null); const threadKey = scopedThreadKey(threadRef); const expanded = expandedThread === threadKey; - const hasMore = compact && links.length > 1; - const visibleLinks = hasMore && !expanded ? links.slice(0, 1) : links; + const row = (link: ThreadIssueLink) => ( + + ); + const [first, ...rest] = links; + if (first === undefined || !compact || rest.length === 0) return <>{links.map(row)}; return ( <> - {visibleLinks.map((link) => ( - - ))} - {hasMore ? ( - setExpandedThread(expanded ? null : threadKey)} - /> + {row(first)} + {expanded ? ( +
+ {rest.map(row)} +
) : null} + setExpandedThread(expanded ? null : threadKey)} + /> ); } diff --git a/apps/web/src/components/chat/ThreadDetailsPrRow.browser.test.tsx b/apps/web/src/components/chat/ThreadDetailsPrRow.browser.test.tsx index 666bbccd13684..d58a084f4bf68 100644 --- a/apps/web/src/components/chat/ThreadDetailsPrRow.browser.test.tsx +++ b/apps/web/src/components/chat/ThreadDetailsPrRow.browser.test.tsx @@ -455,6 +455,8 @@ it("names the first linked issue and reveals more issues on demand", async () => await expect.element(extra).not.toBeInTheDocument(); await screen.getByRole("button", { name: "Show 1 more" }).click(); await expect.element(extra).toBeVisible(); + // The details card leaves this list out of its density measurement. + expect(extra.element().closest("[data-thread-details-issue-list]")).not.toBeNull(); await screen.getByRole("button", { name: "Show less" }).click(); await expect.element(extra).not.toBeInTheDocument(); }); From f7d6796019709464d1ce1c10a19620eb129f638a Mon Sep 17 00:00:00 2001 From: Victor Date: Wed, 25 Nov 2026 06:09:57 -0600 Subject: [PATCH 017/238] fix(server): GB18030 RTF attachments no longer fail text extraction (#42776) Co-authored-by: Julius Marminge --- .../server/src/provider/documentTextWorker.ts | 4 ++- .../src/provider/userInputAttachments.test.ts | 26 +++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/apps/server/src/provider/documentTextWorker.ts b/apps/server/src/provider/documentTextWorker.ts index 36f635784b9f2..93b875e4ad305 100644 --- a/apps/server/src/provider/documentTextWorker.ts +++ b/apps/server/src/provider/documentTextWorker.ts @@ -506,6 +506,7 @@ const RTF_CODE_PAGES = new Map([ [949, "euc-kr"], [950, "big5"], [10000, "macintosh"], + [54936, "gb18030"], [65001, "utf-8"], ]); @@ -546,7 +547,8 @@ function* rtf(source: string): Generator { yield String.fromCharCode(byte); return; } - encoded ??= new Uint8Array(Math.min(source.length, MAX_OUTPUT * 3 + 4)); + // GB18030 spends up to 4 bytes per UTF-16 unit, so a full buffer decodes past MAX_OUTPUT. + encoded ??= new Uint8Array(Math.min(source.length, MAX_OUTPUT * 4 + 4)); if (encodedLength === encoded.length) yield* flushBytes(); encoded[encodedLength++] = byte; } diff --git a/apps/server/src/provider/userInputAttachments.test.ts b/apps/server/src/provider/userInputAttachments.test.ts index d51ec07e755bc..0fca878dfb291 100644 --- a/apps/server/src/provider/userInputAttachments.test.ts +++ b/apps/server/src/provider/userInputAttachments.test.ts @@ -375,6 +375,11 @@ describe("question answer paths", () => { "{\\rtf1\\ansi\\ansicpg936 \\'c4\n\\'e3\\'ba\\'c3}", "你好", ], + [ + "GB18030 code page", + String.raw`{\rtf1\ansi\ansicpg54936 \'d6\'d0\'ce\'c4 \'95\'32\'82\'36}`, + "中文 𠀀", + ], ["Big5 code page", String.raw`{\rtf1\ansi\ansicpg950 \'a7A\'a6n}`, "你好"], [ "multibyte font charsets and font code pages", @@ -434,6 +439,27 @@ describe("question answer paths", () => { }).pipe(Effect.provide(layer)), ); + it.effect("keeps long GB18030 four-byte RTF runs intact up to the output limit", () => + Effect.gen(function* () { + const config = yield* ServerConfig.ServerConfig; + const path = NodePath.join(config.attachmentsDir, "gb18030-long.rtf"); + NodeFS.writeFileSync( + path, + Buffer.concat([ + Buffer.from(String.raw`{\rtf1\ansi\ansicpg54936 `, "latin1"), + Buffer.from([0xd6, 0xd0]), + Buffer.alloc(1_050_000 * 4, Buffer.from([0x81, 0x39, 0xee, 0x39])), + Buffer.from("}", "latin1"), + ]), + ); + const text = yield* Effect.promise(() => extractDocumentText(path, ".rtf")); + expect(text.search(/[^中㐀]/u)).toBe(1_000_000); + expect(text.slice(1_000_000)).toBe( + "\n\n[Extracted text truncated at document extraction limits.]", + ); + }).pipe(Effect.provide(layer)), + ); + it.effect.each([false, true])("limits the child heap for standalone=%s", (standalone) => Effect.acquireUseRelease( Effect.promise(async () => { From 0f9bb6e0e76b525533538bcf3fc3939f0e3c3698 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 25 Nov 2026 04:23:16 -0800 Subject: [PATCH 018/238] fix(mobile): iPad windowed composer sits on the keyboard, not its full height above (#42777) --- ...ct-native-keyboard-controller@1.23.0.patch | 26 +++++++++++++++++-- pnpm-lock.yaml | 6 ++--- 2 files changed, 27 insertions(+), 5 deletions(-) diff --git a/patches/react-native-keyboard-controller@1.23.0.patch b/patches/react-native-keyboard-controller@1.23.0.patch index 979554aa493e1..0808cd79ab49d 100644 --- a/patches/react-native-keyboard-controller@1.23.0.patch +++ b/patches/react-native-keyboard-controller@1.23.0.patch @@ -19,7 +19,7 @@ diff --git a/ios/observers/movement/observer/KeyboardMovementObserver+Listeners. index 545a5b20f6caac289afdfd11cd7596d57de14122..fbdc9840113ee8caaac685d6f14d7d9f3c725c75 100644 --- a/ios/observers/movement/observer/KeyboardMovementObserver+Listeners.swift +++ b/ios/observers/movement/observer/KeyboardMovementObserver+Listeners.swift -@@ -8,6 +8,12 @@ +@@ -8,11 +8,17 @@ extension KeyboardMovementObserver { @objc func keyboardWillAppear(_ notification: Notification) { guard !UIResponder.isKeyboardPreloading else { return } @@ -32,7 +32,13 @@ index 545a5b20f6caac289afdfd11cd7596d57de14122..fbdc9840113ee8caaac685d6f14d7d9f let (duration, frame) = notification.keyboardMetaData() if let keyboardFrame = frame { -@@ -36,8 +42,40 @@ extension KeyboardMovementObserver { + tag = UIResponder.current.reactViewTag +- let keyboardHeight = keyboardFrame.cgRectValue.size.height ++ let keyboardHeight = heightOverlappingWindow(keyboardFrame.cgRectValue) + self.keyboardHeight = keyboardHeight + self.notification = notification + +@@ -36,8 +42,47 @@ extension KeyboardMovementObserver { } } @@ -60,6 +66,13 @@ index 545a5b20f6caac289afdfd11cd7596d57de14122..fbdc9840113ee8caaac685d6f14d7d9f + return frame.width.rounded() < screen.width.rounded() || frame.maxY.rounded() < dockedBottom.rounded() + } + ++ // the frame is screen-relative; a resized iPadOS window ends above the screen's bottom and covers only part of it ++ private func heightOverlappingWindow(_ frame: CGRect) -> CGFloat { ++ guard let window = UIApplication.shared.activeWindow else { return frame.height } ++ let windowFrame = window.convert(window.bounds, to: window.screen.coordinateSpace) ++ return max(0, min(frame.maxY, windowFrame.maxY) - max(frame.minY, windowFrame.minY)) ++ } ++ + private func hideIfKeyboardShown(_ notification: Notification) { + let targetHeight = self.notification?.keyboardMetaData().1?.cgRectValue.height ?? 0 + if targetHeight > 0 { @@ -73,6 +86,15 @@ index 545a5b20f6caac289afdfd11cd7596d57de14122..fbdc9840113ee8caaac685d6f14d7d9f let (duration, _) = notification.keyboardMetaData() tag = UIResponder.current.reactViewTag self.notification = notification +@@ -62,7 +107,7 @@ extension KeyboardMovementObserver { + + let (duration, frame) = notification.keyboardMetaData() + if let keyboardFrame = frame { +- let keyboardHeight = keyboardFrame.cgRectValue.size.height ++ let keyboardHeight = heightOverlappingWindow(keyboardFrame.cgRectValue) + tag = UIResponder.current.reactViewTag + self.keyboardHeight = keyboardHeight + diff --git a/ios/observers/movement/observer/KeyboardMovementObserver.swift b/ios/observers/movement/observer/KeyboardMovementObserver.swift index ae97d611a7f727ebbb0e17eabbb3294e1cc76a2f..2ea1d2ddd3fac6ad418d97c700ab885fe645951f 100644 --- a/ios/observers/movement/observer/KeyboardMovementObserver.swift diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index b4fcab6002c6b..fe5737b876011 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -399,7 +399,7 @@ patchedDependencies: node-pty@1.2.0-beta.15: ff8117509663fe1d5a07ef2648c324e80a9349b7d90401a00a591702615b8b30 react-native-gesture-handler@3.5.0: 171379dd378f8f11e9187876dec2116e5cbf5f21cef6576cdde6956518324f98 react-native-image-viewing@0.2.2: 4aa038d541c7ddcc8f1437eb3e7b4f769f61de78e7f91b53f9805dfca608474d - react-native-keyboard-controller@1.23.0: f34945045e214f8ebc961398bc3b9865590ba48bd2b3afc7809c4316473e69e5 + react-native-keyboard-controller@1.23.0: 6a108ad099cdea5ef76589b308e9c7eed2d0a46a7a0b2fb7b6a85d9ed4eacd94 react-native-pdf-jsi@6.1.0: d29e6b69813548de641a09db705dd94823d3f96832821ae9c3f6a196dd15cb68 react-native-reanimated@4.8.0: db905565fb5bd6f0fa7196d5bc417466556aba0abcd81487e84e8e1d1a2f68f7 react-native-svg@15.16.1: 7f94d240fc19418233c96f9a637dfd248846446657476c204f3614fd2847900e @@ -776,7 +776,7 @@ importers: version: 0.2.2(patch_hash=4aa038d541c7ddcc8f1437eb3e7b4f769f61de78e7f91b53f9805dfca608474d)(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0) react-native-keyboard-controller: specifier: 1.23.0 - version: 1.23.0(patch_hash=f34945045e214f8ebc961398bc3b9865590ba48bd2b3afc7809c4316473e69e5)(4191ff723d14c2df7a3e86cace2d7c00) + version: 1.23.0(patch_hash=6a108ad099cdea5ef76589b308e9c7eed2d0a46a7a0b2fb7b6a85d9ed4eacd94)(4191ff723d14c2df7a3e86cace2d7c00) react-native-nitro-modules: specifier: 0.37.2 version: 0.37.2(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0) @@ -22678,7 +22678,7 @@ snapshots: react: 19.3.0 react-native: 0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6) - react-native-keyboard-controller@1.23.0(patch_hash=f34945045e214f8ebc961398bc3b9865590ba48bd2b3afc7809c4316473e69e5)(4191ff723d14c2df7a3e86cace2d7c00): + react-native-keyboard-controller@1.23.0(patch_hash=6a108ad099cdea5ef76589b308e9c7eed2d0a46a7a0b2fb7b6a85d9ed4eacd94)(4191ff723d14c2df7a3e86cace2d7c00): dependencies: react: 19.3.0 react-native: 0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6) From c478fde9fe323fd6d10ef9a0b109b015546fb8e0 Mon Sep 17 00:00:00 2001 From: Victor Date: Wed, 25 Nov 2026 06:28:06 -0600 Subject: [PATCH 019/238] fix(web): bad workflow pane links no longer pick the first tab or crash (#42791) Co-authored-by: Julius Marminge --- .../workflows/workflowPane.logic.test.ts | 6 +++++- .../workflows/workflowPane.logic.ts | 21 ++++++++++++------- .../workflows/workflowsRouteSearch.test.ts | 21 +++++++++++++++++++ 3 files changed, 40 insertions(+), 8 deletions(-) diff --git a/apps/web/src/components/workflows/workflowPane.logic.test.ts b/apps/web/src/components/workflows/workflowPane.logic.test.ts index f9c9b54f926a2..080efee788644 100644 --- a/apps/web/src/components/workflows/workflowPane.logic.test.ts +++ b/apps/web/src/components/workflows/workflowPane.logic.test.ts @@ -22,7 +22,11 @@ describe("the pane beside a run", () => { ), ).toEqual({ pane: [issue, transcript, { thread: "t1" }], tab: 0 }); // The last tab shows unless the address says another; one it cannot have shows the last. - expect(readWorkflowPane([issue, pullRequest], 7)).toEqual({ pane: [issue, pullRequest] }); + for (const rawTab of [7, "", " ", null, false]) { + const state = readWorkflowPane([issue, pullRequest], rawTab); + expect(state).toEqual({ pane: [issue, pullRequest] }); + expect(activeWorkflowPaneTab(state)).toEqual(pullRequest); + } expect(readWorkflowPane("nope", 0)).toEqual({}); }); diff --git a/apps/web/src/components/workflows/workflowPane.logic.ts b/apps/web/src/components/workflows/workflowPane.logic.ts index 9cdbc4963423d..73aa8a04a1788 100644 --- a/apps/web/src/components/workflows/workflowPane.logic.ts +++ b/apps/web/src/components/workflows/workflowPane.logic.ts @@ -9,9 +9,9 @@ export type WorkflowPaneTab = | { readonly kind: string; readonly key: string }; export interface WorkflowPaneState { - readonly pane?: ReadonlyArray; + readonly pane?: ReadonlyArray | undefined; /** Which tab shows; the last one when it names none. */ - readonly tab?: number; + readonly tab?: number | undefined; } // A link is typed into an address bar: what it holds is capped like the rest of the address. @@ -46,11 +46,18 @@ export function readWorkflowPane(rawPane: unknown, rawTab: unknown): WorkflowPan tabs.push(tab); if (tabs.length === MOST_TABS) break; } - if (tabs.length === 0) return {}; - const tab = typeof rawTab === "number" ? rawTab : Number(rawTab); - return Number.isInteger(tab) && tab >= 0 && tab < tabs.length - 1 - ? { pane: tabs, tab } - : { pane: tabs }; + // The router keeps any address value validateSearch leaves out, so what cannot be read is cleared, not omitted. + if (tabs.length === 0) return { pane: undefined, tab: undefined }; + const tab = + typeof rawTab === "number" + ? rawTab + : typeof rawTab === "string" && rawTab.trim() !== "" + ? Number(rawTab) + : Number.NaN; + return { + pane: tabs, + tab: Number.isInteger(tab) && tab >= 0 && tab < tabs.length - 1 ? tab : undefined, + }; } /** The index of the tab that shows, or -1 when nothing is open. */ diff --git a/apps/web/src/components/workflows/workflowsRouteSearch.test.ts b/apps/web/src/components/workflows/workflowsRouteSearch.test.ts index d68759f87eb75..6703b93d1cf01 100644 --- a/apps/web/src/components/workflows/workflowsRouteSearch.test.ts +++ b/apps/web/src/components/workflows/workflowsRouteSearch.test.ts @@ -40,4 +40,25 @@ describe("workflows route search", () => { ), ).toMatchObject({ env, run, file }); }); + + it("clears an unusable pane or tab instead of keeping the raw search value", () => { + const pane = JSON.stringify([ + { kind: "issue", key: "i412" }, + { kind: "pullRequest", key: "p418" }, + ]); + for (const tab of ["", "null", "true"]) { + const search = matchedSearch(`/workflows?${new URLSearchParams({ pane, tab })}`); + expect(search?.pane).toHaveLength(2); + expect(search?.tab).toBeUndefined(); + } + for (const params of [ + new URLSearchParams({ pane: "nope", tab: "0" }), + new URLSearchParams({ pane: "[]", tab: "" }), + new URLSearchParams({ tab: "null" }), + ]) { + const search = matchedSearch(`/workflows?${params}`); + expect(search?.pane).toBeUndefined(); + expect(search?.tab).toBeUndefined(); + } + }); }); From cef38e408d45b74a02f99da0ed3d400d97fd4182 Mon Sep 17 00:00:00 2001 From: Victor Date: Wed, 25 Nov 2026 06:44:36 -0600 Subject: [PATCH 020/238] fix(web): file picker highlights no longer break emoji in file names (#42805) Co-authored-by: Julius Marminge --- .../files/ProjectFilePicker.logic.test.ts | 42 +++++++++++++++- .../files/ProjectFilePicker.logic.ts | 50 +++++++++++++------ .../components/files/ProjectFilePicker.tsx | 15 +++--- 3 files changed, 85 insertions(+), 22 deletions(-) diff --git a/apps/web/src/components/files/ProjectFilePicker.logic.test.ts b/apps/web/src/components/files/ProjectFilePicker.logic.test.ts index 47efe8f58c44f..ed9344b31a115 100644 --- a/apps/web/src/components/files/ProjectFilePicker.logic.test.ts +++ b/apps/web/src/components/files/ProjectFilePicker.logic.test.ts @@ -1,6 +1,6 @@ import { assert, describe, it } from "vite-plus/test"; -import { getProjectFilePickerMatches } from "./ProjectFilePicker.logic"; +import { getProjectFilePickerMatches, groupMatchRanges } from "./ProjectFilePicker.logic"; function pathsForQuery(entries: Parameters[0], query: string) { return getProjectFilePickerMatches(entries, query).map(({ name, path }) => ({ name, path })); @@ -51,4 +51,44 @@ describe("getProjectFilePickerMatches", () => { ]); assert.deepEqual(indices("İ"), [[0], [0, 6]]); }); + + it("matches emoji by code point without splitting surrogate pairs", () => { + const match = getProjectFilePickerMatches([{ kind: "file", path: "notes/📁-🔥.md" }], "🔥")[0]; + + assert.deepEqual(match, { + name: "📁-🔥.md", + nameMatchIndices: [3, 4], + path: "notes/📁-🔥.md", + pathMatchIndices: [9, 10], + }); + }); + + it("maps emoji highlights accurately when lowercasing expands earlier characters", () => { + const entries = [{ kind: "file", path: "notes/İ-📁-🔥.md" }] as const; + + assert.deepEqual(getProjectFilePickerMatches(entries, "🔥")[0], { + name: "İ-📁-🔥.md", + nameMatchIndices: [5, 6], + path: "notes/İ-📁-🔥.md", + pathMatchIndices: [11, 12], + }); + assert.deepEqual(getProjectFilePickerMatches(entries, "İ🔥m")[0], { + name: "İ-📁-🔥.md", + nameMatchIndices: [0, 5, 6, 8], + path: "notes/İ-📁-🔥.md", + pathMatchIndices: [6, 11, 12, 14], + }); + }); +}); + +describe("groupMatchRanges", () => { + it("groups contiguous indices into [start, end) ranges", () => { + assert.deepEqual(groupMatchRanges([0, 1]), [[0, 2]]); + assert.deepEqual(groupMatchRanges([0, 2, 4, 5]), [ + [0, 1], + [2, 3], + [4, 6], + ]); + assert.deepEqual(groupMatchRanges([]), []); + }); }); diff --git a/apps/web/src/components/files/ProjectFilePicker.logic.ts b/apps/web/src/components/files/ProjectFilePicker.logic.ts index a19e8b4a1e8d5..fcf7993aba8c6 100644 --- a/apps/web/src/components/files/ProjectFilePicker.logic.ts +++ b/apps/web/src/components/files/ProjectFilePicker.logic.ts @@ -15,11 +15,12 @@ function fileName(path: string): string { } /** Return null for unmatched subsequences; server-matched entries still render without highlights. */ -function findMatchIndices(value: string, query: string): number[] | null { - if (!query) return []; +function findMatchIndices(value: string, queryChars: ReadonlyArray): number[] | null { + if (queryChars.length === 0) return []; + // Whole-string lowercasing preserves context-sensitive rules like Greek final sigma (Σ → ς); + // lowercasing lengthens İ (to i̇) and shortens nothing, so only a length change needs mapping back. const normalizedValue = value.toLowerCase(); - // Lowercasing lengthens İ (to i̇) and shortens nothing, so only a longer result needs mapping back. const sourceSpans: Array = []; if (normalizedValue.length !== value.length) { let sourceOffset = 0; @@ -29,20 +30,39 @@ function findMatchIndices(value: string, query: string): number[] | null { sourceOffset = span[1]; } } + const indices: number[] = []; let queryIndex = 0; + let offset = 0; - for (let valueIndex = 0; valueIndex < normalizedValue.length; valueIndex += 1) { - if (normalizedValue[valueIndex] !== query[queryIndex]) continue; - const [start, end] = sourceSpans[valueIndex] ?? [valueIndex, valueIndex + 1]; - for (let i = Math.max(start, (indices.at(-1) ?? -1) + 1); i < end; i += 1) indices.push(i); - queryIndex += 1; - if (queryIndex === query.length) return indices; + for (const char of normalizedValue) { + if (char === queryChars[queryIndex]) { + const [start, end] = sourceSpans[offset] ?? [offset, offset + char.length]; + for (let i = Math.max(start, (indices.at(-1) ?? -1) + 1); i < end; i += 1) indices.push(i); + queryIndex += 1; + if (queryIndex === queryChars.length) return indices; + } + offset += char.length; } return null; } +export function groupMatchRanges( + indices: ReadonlyArray, +): Array { + const ranges: Array<[number, number]> = []; + for (const index of indices) { + const previous = ranges.at(-1); + if (previous && previous[1] === index) { + previous[1] = index + 1; + } else { + ranges.push([index, index + 1]); + } + } + return ranges; +} + /** Preserve server ranking and query normalization while filtering files and computing highlights. */ export function getProjectFilePickerMatches( entries: ReadonlyArray, @@ -51,17 +71,19 @@ export function getProjectFilePickerMatches( ): ProjectFilePickerMatch[] { if (limit <= 0) return []; - const query = normalizeSearchQuery(rawQuery, { - trimLeadingPattern: /^[@./]+/, - }).replaceAll(/\s/g, ""); + const queryChars = Array.from( + normalizeSearchQuery(rawQuery, { + trimLeadingPattern: /^[@./]+/, + }).replaceAll(/\s/g, ""), + ); const matches: ProjectFilePickerMatch[] = []; for (const entry of entries) { if (entry.kind !== "file") continue; const name = fileName(entry.path); - const nameMatchIndices = findMatchIndices(name, query); - const pathMatchIndices = findMatchIndices(entry.path, query); + const nameMatchIndices = findMatchIndices(name, queryChars); + const pathMatchIndices = findMatchIndices(entry.path, queryChars); matches.push({ name, nameMatchIndices: nameMatchIndices ?? [], diff --git a/apps/web/src/components/files/ProjectFilePicker.tsx b/apps/web/src/components/files/ProjectFilePicker.tsx index 8e3f67ff0e809..c5fea40287543 100644 --- a/apps/web/src/components/files/ProjectFilePicker.tsx +++ b/apps/web/src/components/files/ProjectFilePicker.tsx @@ -15,6 +15,7 @@ import { type CommandPaletteActionItem } from "../CommandPalette.logic"; import { CommandPaletteResults } from "../CommandPaletteResults"; import { getProjectFilePickerMatches, + groupMatchRanges, PROJECT_FILE_PICKER_RESULT_LIMIT, } from "./ProjectFilePicker.logic"; import { useProjectFilePickerQuery } from "./projectFilesQueryState"; @@ -31,17 +32,17 @@ function HighlightedFuzzyText(props: { if (!props.active) return props.value; const parts: ReactNode[] = []; - let start = 0; - for (const index of props.indices) { - if (start < index) parts.push(props.value.slice(start, index)); + let cursor = 0; + for (const [start, end] of groupMatchRanges(props.indices)) { + if (cursor < start) parts.push(props.value.slice(cursor, start)); parts.push( - - {props.value[index]} + + {props.value.slice(start, end)} , ); - start = index + 1; + cursor = end; } - if (start < props.value.length) parts.push(props.value.slice(start)); + if (cursor < props.value.length) parts.push(props.value.slice(cursor)); return {parts}; } From 91d6c05ac439aa9677065a4fcecb7344e319952a Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 25 Nov 2026 04:53:39 -0800 Subject: [PATCH 021/238] fix(server): threads deleted before upgrading are purged soon after startup (#42814) --- .../src/persistence/DatabaseStorage.test.ts | 62 ++++++++++++++++++- .../server/src/persistence/DatabaseStorage.ts | 3 +- 2 files changed, 63 insertions(+), 2 deletions(-) diff --git a/apps/server/src/persistence/DatabaseStorage.test.ts b/apps/server/src/persistence/DatabaseStorage.test.ts index 8eae39d0bb078..f7a0cc97d7119 100644 --- a/apps/server/src/persistence/DatabaseStorage.test.ts +++ b/apps/server/src/persistence/DatabaseStorage.test.ts @@ -1,5 +1,6 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, it } from "@effect/vitest"; +import * as DateTime from "effect/DateTime"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; @@ -99,7 +100,7 @@ it.effect("remembers completion only after the paced pass finishes", () => const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; const config = yield* ServerConfig.ServerConfig; - const timestampPath = path.join(path.dirname(config.dbPath), "compacted-at"); + const timestampPath = path.join(path.dirname(config.dbPath), "compacted-at-v2"); const betweenPagesReached = yield* Deferred.make(); const completed = yield* Deferred.make(); const timestampWritten = yield* Deferred.make(); @@ -205,3 +206,62 @@ it.effect( yield* Deferred.await(restarted); }).pipe(Effect.provide(testConfig.pipe(Layer.provideMerge(NodeServices.layer)))), ); + +it.effect( + "purges threads deleted before upgrading without waiting for the next six-hour pass", + () => + Effect.gen(function* () { + yield* TestClock.setTime(startupTime); + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const config = yield* ServerConfig.ServerConfig; + yield* fs.makeDirectory(path.dirname(config.dbPath), { recursive: true }); + // The previous version compacted a minute ago, but never purged deleted threads. + yield* fs.writeFileString( + path.join(path.dirname(config.dbPath), "compacted-at"), + String(startupTime - minute), + ); + const contentRows = Effect.flatMap( + SqlClient.SqlClient, + (sql) => sql<{ readonly count: number }>` + SELECT COUNT(*) AS count FROM orchestration_v2_projection_messages + WHERE thread_id = 'thread:deleted-before-upgrade' + `, + ).pipe(Effect.map((rows) => rows[0]?.count ?? 0)); + + yield* Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + const at = DateTime.formatIso(DateTime.makeUnsafe(startupTime - 2 * minute)); + yield* sql` + INSERT INTO orchestration_v2_projection_threads ( + thread_id, project_id, title, default_provider, runtime_mode, interaction_mode, + created_at, updated_at, deleted_at, payload_json + ) VALUES ( + 'thread:deleted-before-upgrade', 'project:upgrade', 'private title', 'codex', + 'full-access', 'default', ${at}, ${at}, ${at}, '{"title":"private title"}' + ) + `; + yield* sql` + INSERT INTO orchestration_v2_projection_messages ( + message_id, thread_id, role, streaming, created_at, updated_at, payload_json + ) VALUES ( + 'message:deleted-before-upgrade', 'thread:deleted-before-upgrade', 'user', 0, + ${at}, ${at}, '{"text":"private message"}' + ) + `; + assert.equal(yield* contentRows, 1); + yield* DatabaseStorage.DatabaseStorage; + + yield* TestClock.adjust(5 * minute); + + assert.equal(yield* contentRows, 0); + }).pipe( + Effect.provide( + DatabaseStorage.layer.pipe( + Layer.provide(ProjectionMaintenance.layer), + Layer.provideMerge(Sqlite.layerMemory), + ), + ), + ); + }).pipe(Effect.provide(testConfig.pipe(Layer.provideMerge(NodeServices.layer)))), +); diff --git a/apps/server/src/persistence/DatabaseStorage.ts b/apps/server/src/persistence/DatabaseStorage.ts index 151432acaf27d..ba446549c3502 100644 --- a/apps/server/src/persistence/DatabaseStorage.ts +++ b/apps/server/src/persistence/DatabaseStorage.ts @@ -139,7 +139,8 @@ const make = Effect.gen(function* () { // Even a pass that deletes nothing scans the event store. Persist completion // so restarting does not trigger another scan before the six-hour interval. - const compactedAtPath = path.join(path.dirname(config.dbPath), "compacted-at"); + // Versioned: a stamp from before passes purged deleted threads must not delay the first purge. + const compactedAtPath = path.join(path.dirname(config.dbPath), "compacted-at-v2"); const compact = Effect.gen(function* () { let sliceStarted = yield* Clock.monotonicTimeNanos; const betweenPages = Effect.gen(function* () { From 2f7b7f03e32eaf38965246911e1af72d951ca934 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 25 Nov 2026 05:03:08 -0800 Subject: [PATCH 022/238] fix(web): issue number in the Issue panel follows 'Open links in' (#42824) --- .../issue/IssueDetailPanel.browser.test.tsx | 94 +++++++++++++++++++ .../src/components/issue/IssueDetailPanel.tsx | 6 ++ 2 files changed, 100 insertions(+) create mode 100644 apps/web/src/components/issue/IssueDetailPanel.browser.test.tsx diff --git a/apps/web/src/components/issue/IssueDetailPanel.browser.test.tsx b/apps/web/src/components/issue/IssueDetailPanel.browser.test.tsx new file mode 100644 index 0000000000000..7b9755435a1e9 --- /dev/null +++ b/apps/web/src/components/issue/IssueDetailPanel.browser.test.tsx @@ -0,0 +1,94 @@ +import type { IssueDetail } from "@t3tools/contracts"; +import * as AsyncResult from "effect/reactivity/AsyncResult"; +import { describe, expect, it, vi } from "vite-plus/test"; + +import { render } from "../../../test/render"; + +const url = "https://github.com/owner/repo/issues/7"; +const detail = vi.hoisted(() => ({ + tracker: "github", + host: "github.com", + scope: "owner/repo", + key: "7", + displayKey: "#7", + title: "Something is broken", + url: "https://github.com/owner/repo/issues/7", + author: null, + state: { category: "open", name: "Open" }, + createdAt: "2026-01-01T00:00:00.000Z", + updatedAt: "2026-01-01T00:00:00.000Z", + closedAt: null, + assignees: [], + labels: [], + commentCount: 0, + projectId: "project-1", + projectTitle: "Project", + writable: false, + capabilities: { + create: false, + edit: false, + comment: false, + labels: false, + assignees: false, + reactions: false, + templates: false, + linkedPullRequests: false, + events: false, + search: false, + }, + viewerPermissions: { + setState: false, + comment: false, + edit: false, + labels: false, + assignees: false, + }, + states: [], + viewer: null, + body: "", + comments: [], + commentsCursor: null, + events: [], + linkedPullRequests: [], +})) as unknown as IssueDetail; + +const state = vi.hoisted(() => ({ openLink: vi.fn(async () => {}) })); + +vi.mock(import("~/browser/useOpenLink"), () => ({ useOpenLink: () => state.openLink })); +vi.mock(import("./IssueThreadLinks"), () => ({ IssueThreadLinks: (() => null) as never })); +vi.mock(import("~/state/issues"), async (original) => { + const { Atom } = await import("effect/reactivity"); + const actual = await original(); + const detailAtom = Atom.make(AsyncResult.success(detail)); + return { + ...actual, + issueEnvironment: { ...actual.issueEnvironment, detail: (() => detailAtom) as never }, + }; +}); + +import { IssueDetailPanel } from "./IssueDetailPanel"; + +describe("IssueDetailPanel", () => { + it("opens the issue number through the link-target setting, not a popup", async () => { + const threadRef = { environmentId: "env-1", threadId: "thread-1" } as never; + await using screen = await render( + , + ); + const number = screen.getByRole("link", { name: "Open #7 on GitHub" }); + const click = new MouseEvent("click", { bubbles: true, cancelable: true }); + (await number.element()).dispatchEvent(click); + + expect(click.defaultPrevented).toBe(true); + expect(state.openLink).toHaveBeenCalledOnce(); + expect(state.openLink).toHaveBeenCalledWith(url, { event: expect.anything() }); + }); +}); diff --git a/apps/web/src/components/issue/IssueDetailPanel.tsx b/apps/web/src/components/issue/IssueDetailPanel.tsx index 30a55dd1d9e48..38d803e896779 100644 --- a/apps/web/src/components/issue/IssueDetailPanel.tsx +++ b/apps/web/src/components/issue/IssueDetailPanel.tsx @@ -43,6 +43,7 @@ import { m } from "~/i18n/messages"; import { issueEnvironment, refreshIssueLists } from "~/state/issues"; import { useProjects } from "~/state/entities"; import { useEnvironmentQuery } from "~/state/query"; +import { useOpenLink } from "~/browser/useOpenLink"; import { useAtomCommand } from "~/state/use-atom-command"; import { formatRelativeTimeLabel } from "~/timestampFormat"; @@ -443,6 +444,7 @@ export function IssueDetailPanel({ const loadComments = useAtomCommand(issueEnvironment.comments, { reportFailure: false }); const update = useAtomCommand(issueEnvironment.update, { reportFailure: false }); const setState = useAtomCommand(issueEnvironment.setState, { reportFailure: false }); + const openLink = useOpenLink(threadRef); const [editing, setEditing] = useState<"title" | "body" | null>(null); const [titleDraft, setTitleDraft] = useState(""); const [saving, setSaving] = useState(false); @@ -618,6 +620,10 @@ export function IssueDetailPanel({ provider: tracker.providerName, })} render={} + onClick={(event) => { + event.preventDefault(); + void openLink(detail.url, { event }).catch(console.error); + }} > {detail.displayKey} From e849afabb4c1aa600d5c5c33eb51e0fe080a2a4e Mon Sep 17 00:00:00 2001 From: Victor Date: Wed, 25 Nov 2026 07:03:31 -0600 Subject: [PATCH 023/238] fix(server): EPUB glossary entries no longer run together in extracted text (#42816) Co-authored-by: Julius Marminge --- apps/server/src/provider/documentTextWorker.ts | 2 +- apps/server/src/provider/userInputAttachments.test.ts | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/apps/server/src/provider/documentTextWorker.ts b/apps/server/src/provider/documentTextWorker.ts index 93b875e4ad305..230e5d22c144c 100644 --- a/apps/server/src/provider/documentTextWorker.ts +++ b/apps/server/src/provider/documentTextWorker.ts @@ -254,7 +254,7 @@ function* paragraphs(node: XmlNode): Generator { yield "\n"; } else { yield* paragraphs(child); - if (["li", "div", "section"].includes(child.name)) yield "\n"; + if (["li", "div", "section", "dt", "dd"].includes(child.name)) yield "\n"; } } } diff --git a/apps/server/src/provider/userInputAttachments.test.ts b/apps/server/src/provider/userInputAttachments.test.ts index 0fca878dfb291..6aad293a35ec9 100644 --- a/apps/server/src/provider/userInputAttachments.test.ts +++ b/apps/server/src/provider/userInputAttachments.test.ts @@ -1497,7 +1497,7 @@ describe("question answer paths", () => { "OEBPS/a.xhtml": '

Last chapter

Price 10 8 old

', "OEBPS/b.xhtml": - 'My Novel

First chapter

Larkspur

Direct div
Direct section
  • Direct item emphasis trailing
  • Account: A
    Balance: 731Currency: USD
    HeadingTotal
    Important value731
    Before
    Inner
    After
    Neighbor
    ', + 'My Novel

    First chapter

    Larkspur

    Direct div
    Direct section
  • Direct item emphasis trailing
  • Account: A
    Balance: 731Currency: USD
    HeadingTotal
    Important value731
    Before
    Inner
    After
    Neighbor
    Port
    443
    Timeout
    30 seconds
    ', }, expected: [ "## Chapter 1", @@ -1510,6 +1510,7 @@ describe("question answer paths", () => { "Heading\tTotal", "Important value\t731", "Before Inner After\tNeighbor", + "Port\n443\nTimeout\n30 seconds", "## Chapter 2", "Last chapter", "Price 10 8 old", From f7ec366acddb573c3b13dc2c7b575c0c62aed7e9 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Wed, 25 Nov 2026 14:05:50 +0100 Subject: [PATCH 024/238] fix(server): preserve split terminal output when rejoining (#42808) Co-authored-by: Julius Marminge --- apps/server/src/terminal/Manager.test.ts | 37 ++++++++++++++++++++++++ apps/server/src/terminal/Manager.ts | 23 +++++++++++++-- 2 files changed, 57 insertions(+), 3 deletions(-) diff --git a/apps/server/src/terminal/Manager.test.ts b/apps/server/src/terminal/Manager.test.ts index c08912cdc0ab0..10b91b1befce5 100644 --- a/apps/server/src/terminal/Manager.test.ts +++ b/apps/server/src/terminal/Manager.test.ts @@ -1924,6 +1924,43 @@ it.layer( }), ); + it.effect.each([ + { name: "NUL padding", body: "31" + "\u0000".repeat(4_096) + "\r", replay: "31\r" }, + { name: "DEL padding", body: "31" + "\u007f".repeat(4_096) + "\r", replay: "31\r" }, + { name: "non-ASCII padding", body: "31" + "é".repeat(4_096) + "\r", replay: "31\r" }, + { name: "over-budget parameters", body: "1".repeat(5_000) + "\r", replay: "\r" }, + { + name: "parameters filling the budget", + body: "1".repeat(4_094) + "\r", + replay: "1".repeat(4_094), + }, + { name: "repeated carriage returns", body: "31" + "\r".repeat(4_094), replay: "31\r" }, + { + name: "over-budget line feeds", + body: "31" + "\n".repeat(4_094), + replay: "31" + "\n".repeat(4_092), + }, + ])("replays an unfinished CSI with $name on attach", ({ body, replay }) => + Effect.gen(function* () { + const { manager, ptyAdapter } = yield* createManager(); + const input = openInput(); + const live = yield* Stream.toPull(manager.attachOutputStream(input, "live")); + yield* live; + const process = ptyAdapter.processes[0]!; + process.emitData("prompt\u001b[" + body); + yield* live; + + const joining = yield* Stream.toPull(manager.attachOutputStream(input, "joining")); + const [event] = yield* joining; + if (event?.type !== "snapshot") throw new Error("Expected a terminal snapshot"); + process.emitData("mX"); + const [output] = yield* joining; + if (output?.type !== "output") throw new Error("Expected live terminal output"); + + expect(event.snapshot.history + output.data).toBe("prompt\u001b[" + replay + "mX"); + }), + ); + it.effect("preserves large chunked OSC 52 and DCS strings across reopen", () => Effect.gen(function* () { const { manager, ptyAdapter, logsDir } = yield* createManager(); diff --git a/apps/server/src/terminal/Manager.ts b/apps/server/src/terminal/Manager.ts index 2e562182740a7..7ae6452c2c4fa 100644 --- a/apps/server/src/terminal/Manager.ts +++ b/apps/server/src/terminal/Manager.ts @@ -1413,8 +1413,7 @@ const OVERSIZED_SEQUENCE = "\u0018"; // Stands in for the ESC of an oversized sequence, which ended any string history left open. const STRING_TERMINATOR = "\u001b\\"; -// Longer held text is cut to its introducer in a snapshot, so it cannot push history out of the -// client's budget or add its size to every resync. +// Bound the unfinished sequence in snapshots so it cannot push history out of the client's budget. const MAX_SNAPSHOT_SEQUENCE_LENGTH = 4_096; // History leaves out the sequence the terminal is still inside. A client that starts from a @@ -1423,7 +1422,25 @@ function unfinishedSequenceReplay(session: TerminalSessionState): string { const held = session.pendingHistoryControlSequence; if (held.startsWith(OVERSIZED_SEQUENCE)) return held.slice(1); if (held.length <= MAX_SNAPSHOT_SEQUENCE_LENGTH) return held; - return held.slice(0, 2) + (/[\u001b\ud800-\udbff]$/.exec(held)?.[0] ?? ""); + const introducer = held.slice(0, 2); + const tail = /[\u001b\ud800-\udbff]$/.exec(held)?.[0] ?? ""; + if (introducer === "\u001b[") { + // The scanner has already handled bytes that end a CSI. Only intermediates, parameters, + // and executed non-NUL controls affect its replay. + const body = held + .slice(2, held.length - tail.length) + .replace(/[^\x01-\x0f\x20-\x3f]+/g, "") + .replace(/\r{2,}/g, "\r"); + const budget = MAX_SNAPSHOT_SEQUENCE_LENGTH - introducer.length - tail.length; + if (body.length <= budget) return introducer + body + tail; + // Controls execute as they arrive, independently of the parameters dispatched at the end. + const parameters = body.replace(/[^\x20-\x3f]+/g, ""); + const replayParameters = parameters.length <= budget ? parameters : ""; + const controls = body.replace(/[^\x01-\x0f]+/g, ""); + const controlsToSkip = Math.max(0, controls.length - (budget - replayParameters.length)); + return introducer + replayParameters + controls.slice(controlsToSkip) + tail; + } + return introducer + tail; } export function sanitizeTerminalHistoryChunk( From 1c3f0ee88fc75440e173704cf45eae4d15f2cf95 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 25 Nov 2026 05:09:55 -0800 Subject: [PATCH 025/238] fix(server): force-kill a relay client that ignores SIGTERM on restart (#42830) --- .../src/cloud/ManagedEndpointRuntime.test.ts | 49 +++++++++++++++++++ .../src/cloud/ManagedEndpointRuntime.ts | 9 +++- 2 files changed, 56 insertions(+), 2 deletions(-) diff --git a/apps/server/src/cloud/ManagedEndpointRuntime.test.ts b/apps/server/src/cloud/ManagedEndpointRuntime.test.ts index c7caf65264631..0c716811a80cc 100644 --- a/apps/server/src/cloud/ManagedEndpointRuntime.test.ts +++ b/apps/server/src/cloud/ManagedEndpointRuntime.test.ts @@ -509,6 +509,55 @@ describe("CloudManagedEndpointRuntime", () => { }), ); + it.effect("restarts a relay client that ignores SIGTERM within a bounded time", () => { + // cloudflared on a half-open HTTP/2 socket keeps running after SIGTERM; only SIGKILL stops it. + const exits: Array> = []; + return Effect.gen(function* () { + const started = yield* Queue.unbounded(); + const spawner = ChildProcessSpawner.make(() => + Effect.gen(function* () { + const pid = 900 + exits.length; + const exit = yield* Deferred.make(); + exits.push(exit); + const handle = ChildProcessSpawner.makeHandle({ + ...makeHandle({ pid, exitCode: Deferred.await(exit), onKill: () => {} }), + kill: (options) => + options?.forceKillAfter === undefined + ? Deferred.await(exit).pipe(Effect.asVoid) + : Effect.sleep(options.forceKillAfter).pipe( + Effect.andThen(Deferred.succeed(exit, ChildProcessSpawner.ExitCode(137))), + Effect.asVoid, + ), + }); + yield* Queue.offer(started, pid); + return handle; + }), + ); + const runtime = yield* buildCloudManagedEndpointRuntime(spawner); + yield* runtime.applyConfig(tunnelConfig); + expect(yield* Queue.take(started)).toBe(900); + + const restart = yield* runtime + .restartConnector(900, Effect.succeed(true)) + .pipe(Effect.forkChild({ startImmediately: true })); + yield* TestClock.adjust(Duration.minutes(1)); + + expect(restart.pollUnsafe()).toEqual(Exit.succeed(true)); + }).pipe( + Effect.ensuring( + Effect.suspend(() => + Effect.forEach( + exits, + (exit) => Deferred.succeed(exit, ChildProcessSpawner.ExitCode(143)), + { + discard: true, + }, + ), + ), + ), + ); + }); + it.effect("still owns a relay client when activation is interrupted while recording it", () => Effect.gen(function* () { const fixture = yield* makeTransportSpawner(); diff --git a/apps/server/src/cloud/ManagedEndpointRuntime.ts b/apps/server/src/cloud/ManagedEndpointRuntime.ts index ffc533486d3ea..adee8eab0aae6 100644 --- a/apps/server/src/cloud/ManagedEndpointRuntime.ts +++ b/apps/server/src/cloud/ManagedEndpointRuntime.ts @@ -117,6 +117,8 @@ const CONNECTOR_READINESS_INTERVAL = Duration.seconds(30); const CONNECTOR_READINESS_REQUEST_TIMEOUT = Duration.seconds(5); const CONNECTOR_NOT_READY_CHECKS_BEFORE_RESTART = 6; const CONNECTOR_NOT_READY_CHECKS_MAX = 60; +// cloudflared stuck on a dead HTTP/2 socket can ignore SIGTERM for minutes. +const RELAY_CLIENT_FORCE_KILL_AFTER = Duration.seconds(5); const RELAY_CLIENT_METRICS_LINE = /\bStarting metrics server on (127\.0\.0\.1:\d+)\/metrics\b/u; const RELAY_CLIENT_PROTOCOL = /\bprotocol=(\w+)/u; // cloudflared's metrics server: `/ready` answers 200 or 503 with this body, and @@ -586,7 +588,9 @@ export const make = Effect.gen(function* () { tunnelId: connector.config.tunnelId, tunnelName: connector.config.tunnelName, }); - yield* connector.child.kill().pipe(Effect.ignore); + yield* connector.child + .kill({ forceKillAfter: RELAY_CLIENT_FORCE_KILL_AFTER }) + .pipe(Effect.ignore); } }); @@ -798,6 +802,7 @@ export const make = Effect.gen(function* () { ], { detached: false, + forceKillAfter: RELAY_CLIENT_FORCE_KILL_AFTER, env: { ...env, TUNNEL_TOKEN: config.connectorToken, @@ -917,7 +922,7 @@ export const make = Effect.gen(function* () { { pid, tunnelId: active.config.tunnelId, tunnelName: active.config.tunnelName }, ); // The supervisor starts the replacement with its usual crash-loop backoff. - return yield* active.child.kill().pipe( + return yield* active.child.kill({ forceKillAfter: RELAY_CLIENT_FORCE_KILL_AFTER }).pipe( Effect.as(true), Effect.orElseSucceed(() => false), ); From c991a91ec6def51242fc9bdb8205b4be098d9b74 Mon Sep 17 00:00:00 2001 From: Victor Date: Wed, 25 Nov 2026 07:28:58 -0600 Subject: [PATCH 026/238] fix(web): GB18030 RTF files now preview instead of showing no preview (#42827) Co-authored-by: Julius Marminge --- .../components/files/FilePreviewPanel.test.ts | 8 +++++ .../files/extendedDocumentPreview.ts | 1 + .../rtf-preview-decodes-gb18030.e2e.ts | 32 +++++++++++++++++++ 3 files changed, 41 insertions(+) create mode 100644 scripts/scenarios/rtf-preview-decodes-gb18030.e2e.ts diff --git a/apps/web/src/components/files/FilePreviewPanel.test.ts b/apps/web/src/components/files/FilePreviewPanel.test.ts index 8ec04ee1cabe4..8b584e7acf833 100644 --- a/apps/web/src/components/files/FilePreviewPanel.test.ts +++ b/apps/web/src/components/files/FilePreviewPanel.test.ts @@ -324,6 +324,14 @@ Third}`; String.raw`{\rtf1\ansi\ansicpg1251{\fonttbl{\f0\fnil\fcharset0\cpg1251 Arial;}{\f1\fnil\fcharset204 Arial{\*\fontfile\cpg1252 arial.ttf};}}\f0 \'cf\'f0\'e8\f1\'e2\'e5\'f2}`, "

    Привет

    ", ], + [ + String.raw`{\rtf1\ansi\ansicpg54936 Quarterly notes: \'d6\'d0\'ce\'c4 \'95\'32\'82\'36 \'82\'35\'8f\'33 \uc2\u20320\'c4\'e3 done\par}`, + "

    Quarterly notes: 中文 𠀀 龦 你 done

    ", + ], + [ + String.raw`{\rtf1\ansi{\fonttbl{\f0\fnil\fcharset0\cpg54936 SimSun;}}\f0 \'d6\'d0\'ce\'c4}`, + "

    中文

    ", + ], ] as const) { const decoded = openRtf(bytes(rtf)); if (decoded.type !== "document") throw new Error("Expected document"); diff --git a/apps/web/src/components/files/extendedDocumentPreview.ts b/apps/web/src/components/files/extendedDocumentPreview.ts index 517e404f0a8c2..75d8c01b4e3f0 100644 --- a/apps/web/src/components/files/extendedDocumentPreview.ts +++ b/apps/web/src/components/files/extendedDocumentPreview.ts @@ -583,6 +583,7 @@ const rtfCodePageLabel = (codePage: number) => 950: "big5", 874: "windows-874", 10000: "macintosh", + 54936: "gb18030", } as Record )[codePage] ?? `windows-${codePage}`; diff --git a/scripts/scenarios/rtf-preview-decodes-gb18030.e2e.ts b/scripts/scenarios/rtf-preview-decodes-gb18030.e2e.ts new file mode 100644 index 0000000000000..8389d1c219bc8 --- /dev/null +++ b/scripts/scenarios/rtf-preview-decodes-gb18030.e2e.ts @@ -0,0 +1,32 @@ +import { expect } from "e2e"; + +import { test, WEB } from "./t3.ts"; + +// A Simplified Chinese RTF saved with the GB18030 code page (\ansicpg54936). +const GB18030_RTF = String.raw`{\rtf1\ansi\ansicpg54936 Quarterly notes: \'d6\'d0\'ce\'c4 \'95\'32\'82\'36 \'82\'35\'8f\'33 \uc2\u20320\'c4\'e3 done\par}`; + +test( + "An RTF preview decodes text saved with the GB18030 code page", + WEB, + async ({ t3, app, screen, browser }) => { + const project = await t3.project("demo", { "notes.rtf": GB18030_RTF }); + const thread = await t3.thread({ project, title: "Review notes", messages: ["Start"] }); + await t3.open(thread); + await screen.getByText("fixture turn complete", { exact: false }).waitFor(); + + await browser.keyboard.press("Control+p"); + await screen.getByPlaceholder("Search files…").fill("notes.rtf"); + await screen.getByRole("option", "notes.rtf", { exact: false }).tap(); + + const document = browser.frameLocator('iframe[title^="notes.rtf"]'); + try { + // The first document preview loads its worker, which a cold Vite cache optimizes on demand. + // List form treats a missing iframe as 0 matches (ASSERTION_FAILED) rather than LOCATOR_NOT_FOUND. + await expect(document.locator("body")).toHaveText(["Quarterly notes: 中文 𠀀 龦 你 done"], { + timeout: 120_000, + }); + } finally { + await app.screenshot("text"); + } + }, +); From e6738fd8bcc8cf2e3026375d2299fde6edc81c94 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Wed, 25 Nov 2026 14:33:11 +0100 Subject: [PATCH 027/238] fix(server): retain unfinished terminal sequences in attach history (#42817) Co-authored-by: Julius Marminge --- apps/server/src/terminal/Manager.test.ts | 111 +++++++++++++++++- apps/server/src/terminal/Manager.ts | 91 +++++++++----- .../client-runtime/src/state/runtime.test.ts | 6 +- packages/client-runtime/src/state/terminal.ts | 8 +- .../src/state/terminalOutput.ts | 36 +++++- .../src/state/terminalSession.test.ts | 84 +++++++++++++ .../src/state/terminalSession.ts | 2 +- packages/contracts/src/terminal.ts | 57 ++++++++- 8 files changed, 352 insertions(+), 43 deletions(-) diff --git a/apps/server/src/terminal/Manager.test.ts b/apps/server/src/terminal/Manager.test.ts index 10b91b1befce5..dbc3bb95e8adf 100644 --- a/apps/server/src/terminal/Manager.test.ts +++ b/apps/server/src/terminal/Manager.test.ts @@ -8,7 +8,7 @@ import { ProjectId, ThreadId, TerminalCwdNotFoundError, - type TerminalAttachStreamEvent, + TerminalAttachStreamEvent, type TerminalEvent, type TerminalOpenInput, ProviderDriverKind, @@ -3342,6 +3342,115 @@ it.layer( }), ); + it.effect( + "keeps a title update hidden when the history limit cuts through the previous title", + () => + Effect.gen(function* () { + const { manager, ptyAdapter } = yield* createManager(); + const input = openInput(); + const live = yield* Stream.toPull(manager.attachOutputStream(input, "live")); + yield* live; + const process = ptyAdapter.processes[0]!; + // UTF-8 exceeds the wire history budget while the string fits the parser's held text limit. + process.emitData("\u001b]0;"); + yield* live; + const titleChunk = "界".repeat(8_192); + for (let index = 0; index < 24; index += 1) { + process.emitData(titleChunk); + yield* live; + } + // The second OSC's escape ends the first title without a separate terminator. + process.emitData("\u001b]0;Build "); + yield* live; + + const joining = yield* Stream.toPull( + manager.attachOutputStream( + { ...input, maxHistoryBytes: DEFAULT_MAX_TERMINAL_BUFFER_BYTES }, + "joining", + ), + ); + const [event] = yield* joining; + if (event?.type !== "snapshot") throw new Error("Expected a terminal snapshot"); + process.emitData("progress\u0007ready\r\n"); + const [output] = yield* joining; + if (output?.type !== "output") throw new Error("Expected live terminal output"); + + const state = terminalSequenceStateAfter(0, event.snapshot.history); + const firstVisible = terminalSequenceEnd(state, output.data); + expect(output.data.slice(firstVisible)).toBe("ready\r\n"); + }), + ); + + it.effect.each([ + { + name: "title with no history budget", + pending: "\u001b]0;Build ", + tail: "progress\u0007", + budget: 0, + history: "", + viewer: "attach", + supportsSnapshotSequenceState: true, + }, + { + name: "title beyond the pending prefix limit", + pending: "\u001b]0;" + "x".repeat(4_096), + tail: "progress\u0007", + budget: DEFAULT_MAX_TERMINAL_BUFFER_BYTES, + history: "before\r\n", + viewer: "attach", + supportsSnapshotSequenceState: true, + }, + ...(["attach", "observe", "resync"] as const).map((viewer) => ({ + name: `long title for a legacy ${viewer} viewer`, + pending: "\u001b]0;" + "x".repeat(4_096), + tail: "progress\u0007", + budget: DEFAULT_MAX_TERMINAL_BUFFER_BYTES, + history: "before\r\n\u001b]", + viewer, + supportsSnapshotSequenceState: false, + })), + ] as const)( + "keeps a snapshot's $name out of visible output", + ({ pending, tail, budget, history, viewer, supportsSnapshotSequenceState }) => + Effect.gen(function* () { + const { manager, ptyAdapter } = yield* createManager(); + const input = openInput(); + const live = yield* Stream.toPull(manager.attachOutputStream(input, "live")); + yield* live; + const process = ptyAdapter.processes[0]!; + process.emitData("before\r\n" + pending); + yield* live; + + const viewerInput = { ...input, supportsSnapshotSequenceState }; + const joining = yield* Stream.toPull( + viewer === "attach" + ? manager.attachOutputStream({ ...viewerInput, maxHistoryBytes: budget }, "joining") + : terminalOutputStream((listener, cleanup) => + viewer === "observe" + ? manager.observeStream(viewerInput, listener, cleanup) + : manager.resyncStream(viewerInput, listener, cleanup), + ), + ); + const [event] = yield* joining; + if (event?.type !== "snapshot") throw new Error("Expected a terminal snapshot"); + // The parser state must survive the wire schema's bounds check. + const wireEvent = Schema.fromJsonString(TerminalAttachStreamEvent); + const decoded = yield* Schema.decodeEffect(wireEvent)( + yield* Schema.encodeEffect(wireEvent)(event), + ); + if (decoded.type !== "snapshot") throw new Error("Expected a terminal snapshot"); + expect(decoded.snapshot.history).toBe(history); + const omitted = decoded.snapshot.historySequenceState; + expect(omitted !== undefined).toBe(supportsSnapshotSequenceState); + const state = omitted ?? terminalSequenceStateAfter(0, decoded.snapshot.history); + + process.emitData(tail + "ready"); + const [output] = yield* joining; + if (output?.type !== "output") throw new Error("Expected terminal output"); + expect(output.data.slice(terminalSequenceEnd(state, output.data))).toBe("ready"); + }), + ); + it.effect("does not replay in-flight output already included in an observer snapshot", () => Effect.gen(function* () { const { manager, ptyAdapter } = yield* createManager(); diff --git a/apps/server/src/terminal/Manager.ts b/apps/server/src/terminal/Manager.ts index 7ae6452c2c4fa..12f72a1e228b7 100644 --- a/apps/server/src/terminal/Manager.ts +++ b/apps/server/src/terminal/Manager.ts @@ -5,7 +5,7 @@ import { withWorkspaceLease } from "../workspace/workspaceLease.ts"; import { DEFAULT_TERMINAL_ID, DEFAULT_MAX_TERMINAL_BUFFER_BYTES, - retainedTerminalHistory, + retainTerminalSnapshotHistory, TERMINAL_SEQUENCE_GROUND, terminalSequenceEnd, terminalSequenceStateAfter, @@ -410,7 +410,10 @@ function terminalWireLabel(session: TerminalSessionState): string { return truncateTerminalWireLabel(getTerminalLabel(session.terminalId)); } -function snapshot(session: TerminalSessionState): TerminalSessionSnapshot { +function snapshot( + session: TerminalSessionState, + supportsSnapshotSequenceState = false, +): TerminalSessionSnapshot { return { threadId: session.threadId, terminalId: session.terminalId, @@ -418,7 +421,7 @@ function snapshot(session: TerminalSessionState): TerminalSessionSnapshot { worktreePath: session.worktreePath, status: session.status, pid: session.pid, - history: session.history.value() + unfinishedSequenceReplay(session), + ...snapshotHistory(session, supportsSnapshotSequenceState), exitCode: session.exitCode, exitSignal: session.exitSignal, label: terminalWireLabel(session), @@ -1418,8 +1421,7 @@ const MAX_SNAPSHOT_SEQUENCE_LENGTH = 4_096; // History leaves out the sequence the terminal is still inside. A client that starts from a // snapshot needs it, or it prints the rest of the sequence as text. -function unfinishedSequenceReplay(session: TerminalSessionState): string { - const held = session.pendingHistoryControlSequence; +function unfinishedSequenceReplay(held: string): string { if (held.startsWith(OVERSIZED_SEQUENCE)) return held.slice(1); if (held.length <= MAX_SNAPSHOT_SEQUENCE_LENGTH) return held; const introducer = held.slice(0, 2); @@ -1443,6 +1445,28 @@ function unfinishedSequenceReplay(session: TerminalSessionState): string { return introducer + tail; } +function snapshotHistory(session: TerminalSessionState, supportsSnapshotSequenceState: boolean) { + const history = session.history.value(); + const held = session.pendingHistoryControlSequence; + const oversized = held.startsWith(OVERSIZED_SEQUENCE); + // A long CSI compacts into a faithful replay, so only strings and oversized prefixes are omitted. + if ( + !supportsSnapshotSequenceState || + (!oversized && (held.length <= MAX_SNAPSHOT_SEQUENCE_LENGTH || held.startsWith("\u001b["))) + ) { + return { history: history + unfinishedSequenceReplay(held) }; + } + const state = terminalSequenceStateAfter(TERMINAL_SEQUENCE_GROUND, held, oversized ? 1 : 0); + // The omitted prefix's ESC may also have ended the preceding string in history. + const closedHistory = + terminalSequenceStateAfter(TERMINAL_SEQUENCE_GROUND, history) === TERMINAL_SEQUENCE_GROUND + ? history + : history + STRING_TERMINATOR; + return state === TERMINAL_SEQUENCE_GROUND + ? { history: closedHistory } + : { history: closedHistory, historySequenceState: state }; +} + export function sanitizeTerminalHistoryChunk( pendingControlSequence: string, data: string, @@ -3397,7 +3421,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func }, "started", ); - return snapshot(session); + return session; } const liveSession = existing.value; @@ -3447,20 +3471,22 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func }, "started", ); - return snapshot(liveSession); + return liveSession; } if (liveSession.cols !== targetCols || liveSession.rows !== targetRows) { yield* resizeSession(liveSession, liveSession.process, targetCols, targetRows); } - return snapshot(liveSession); + return liveSession; }); - const openLocked = (input: TerminalOpenInput) => + const openLocked = (input: TerminalOpenInput, supportsSnapshotSequenceState?: boolean) => withWorkspaceLease( path.resolve(input.worktreePath ?? input.cwd), - openWithWorkspaceLease(input), + openWithWorkspaceLease(input).pipe( + Effect.map((session) => snapshot(session, supportsSnapshotSequenceState)), + ), ); const open: TerminalManager["Service"]["open"] = (input) => @@ -3498,7 +3524,9 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func terminalId, cwd: input.cwd, }); - return yield* Effect.uninterruptible(openLocked(resolvedInput)); + return yield* Effect.uninterruptible( + openLocked(resolvedInput, input.supportsSnapshotSequenceState), + ); } const session = existing.value; @@ -3511,7 +3539,9 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func terminalId, cwd: input.cwd, }); - return yield* Effect.uninterruptible(openLocked(resolvedInput)); + return yield* Effect.uninterruptible( + openLocked(resolvedInput, input.supportsSnapshotSequenceState), + ); } if ( @@ -3522,7 +3552,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func yield* resizeSession(session, session.process, targetCols, targetRows); } - return snapshot(session); + return snapshot(session, input.supportsSnapshotSequenceState); }); const readAllTerminalMetadata = () => @@ -3702,7 +3732,9 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func ) => streamSession( input, - requireSession(input.threadId, input.terminalId).pipe(Effect.map(snapshot)), + requireSession(input.threadId, input.terminalId).pipe( + Effect.map((session) => snapshot(session, input.supportsSnapshotSequenceState)), + ), listener, registerCleanup, ); @@ -3715,7 +3747,11 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func streamSession( input, getSession(input.threadId, input.terminalId).pipe( - Effect.map((session) => (Option.isSome(session) ? snapshot(session.value) : null)), + Effect.map((session) => + Option.isSome(session) + ? snapshot(session.value, input.supportsSnapshotSequenceState) + : null, + ), ), listener, registerCleanup, @@ -3725,22 +3761,21 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func input, viewerId, ) => { - const { maxHistoryBytes } = input; + const { maxHistoryBytes, supportsSnapshotSequenceState } = input; const retained = (listener: (event: TerminalAttachStreamEvent) => Effect.Effect) => maxHistoryBytes === undefined ? listener - : (event: TerminalAttachStreamEvent) => - listener( - "snapshot" in event - ? { - ...event, - snapshot: { - ...event.snapshot, - history: retainedTerminalHistory(event.snapshot.history, maxHistoryBytes), - }, - } - : event, - ); + : (event: TerminalAttachStreamEvent) => { + if (!("snapshot" in event)) return listener(event); + const retained = retainTerminalSnapshotHistory(event.snapshot.history, maxHistoryBytes); + return listener({ + ...event, + snapshot: { + ...event.snapshot, + ...(supportsSnapshotSequenceState ? retained : { history: retained.history }), + }, + }); + }; return Stream.unwrap( Effect.acquireRelease( Effect.sync(() => retainViewerOnce(input, viewerId, null)), diff --git a/packages/client-runtime/src/state/runtime.test.ts b/packages/client-runtime/src/state/runtime.test.ts index 3b54ce7d32b05..84c6f7aacae94 100644 --- a/packages/client-runtime/src/state/runtime.test.ts +++ b/packages/client-runtime/src/state/runtime.test.ts @@ -795,7 +795,11 @@ describe("environment query lifecycle", () => { cwd: "/tmp/project", restartIfNotRunning: true, }; - const sent = { ...input, maxHistoryBytes: DEFAULT_MAX_TERMINAL_BUFFER_BYTES }; + const sent = { + ...input, + maxHistoryBytes: DEFAULT_MAX_TERMINAL_BUFFER_BYTES, + supportsSnapshotSequenceState: true, + }; const atoms = createTerminalEnvironmentAtoms(harness.runtime); const registry = AtomRegistry.make(); const atom = atoms.attach({ environmentId: QUERY_ENVIRONMENT.environmentId, input }); diff --git a/packages/client-runtime/src/state/terminal.ts b/packages/client-runtime/src/state/terminal.ts index 572c116a4b7e3..52f360fdd95ba 100644 --- a/packages/client-runtime/src/state/terminal.ts +++ b/packages/client-runtime/src/state/terminal.ts @@ -81,9 +81,10 @@ export function createTerminalEnvironmentAtoms( label: "environment-data:terminal:observe", subscribe: (input: EnvironmentRpcInput) => Stream.suspend(() => - subscribe(WS_METHODS.terminalObserve, input).pipe( - Stream.scan(nextTerminalAttachSeedState, applyTerminalAttachStreamEvent), - ), + subscribe(WS_METHODS.terminalObserve, { + ...input, + supportsSnapshotSequenceState: true, + }).pipe(Stream.scan(nextTerminalAttachSeedState, applyTerminalAttachStreamEvent)), ), }), attach: createEnvironmentSubscriptionAtomFamily(runtime, { @@ -98,6 +99,7 @@ export function createTerminalEnvironmentAtoms( ...input, ...(replied ? { resume: true } : {}), maxHistoryBytes: DEFAULT_MAX_TERMINAL_BUFFER_BYTES, + supportsSnapshotSequenceState: true, })), ).pipe( Stream.onFirst(() => diff --git a/packages/client-runtime/src/state/terminalOutput.ts b/packages/client-runtime/src/state/terminalOutput.ts index e01785bc30f11..0df9bcb7126d7 100644 --- a/packages/client-runtime/src/state/terminalOutput.ts +++ b/packages/client-runtime/src/state/terminalOutput.ts @@ -1,6 +1,8 @@ import { - retainedTerminalHistory, + retainTerminalSnapshotHistory, + skipTerminalSnapshotContinuation, TERMINAL_SEQUENCE_GROUND, + type TerminalSessionSnapshot, terminalSequenceEnd, terminalSequenceStateAfter, } from "@t3tools/contracts"; @@ -20,6 +22,8 @@ export interface TerminalOutputState { // The terminal parser's state at the first retained code unit. Trimming can cut a control // sequence, and a replay has to skip the rest of it instead of printing it. readonly sequenceState: number; + /** Parser state of a prefix omitted after the snapshot history. */ + readonly pendingSnapshotSequenceState?: number | undefined; /** Chunks before this offset are replayed to emulators but are no longer displayed text. */ readonly textStartOffset: number; } @@ -181,6 +185,27 @@ function appendOutput( current: TerminalOutputState, data: string, maxBufferBytes: number, +): TerminalOutputState { + const pending = current.pendingSnapshotSequenceState; + if (pending === undefined || data.length === 0) { + return appendRetainedOutput(current, data, maxBufferBytes); + } + const continuation = skipTerminalSnapshotContinuation(pending, data); + return appendRetainedOutput( + { + ...current, + pendingSnapshotSequenceState: + continuation.state === TERMINAL_SEQUENCE_GROUND ? undefined : continuation.state, + }, + continuation.data, + maxBufferBytes, + ); +} + +function appendRetainedOutput( + current: TerminalOutputState, + data: string, + maxBufferBytes: number, ): TerminalOutputState { if (data.length === 0) return current; if (maxBufferBytes <= 0) { @@ -254,12 +279,12 @@ function appendOutput( function resetOutput( current: TerminalOutputState, - data: string, + snapshot: Pick, maxBufferBytes: number, ): TerminalOutputState { - const retained = retainedTerminalHistory(data, maxBufferBytes); + const retained = retainTerminalSnapshotHistory(snapshot.history, maxBufferBytes); const reset = splitOutputChunks( - retained, + retained.history, 0, Math.min(DEFAULT_TERMINAL_CHUNK_BYTES, Math.max(1, maxBufferBytes)), ); @@ -270,6 +295,7 @@ function resetOutput( resetVersion: current.resetVersion + 1, nextOffset: reset.nextOffset, sequenceState: TERMINAL_SEQUENCE_GROUND, + pendingSnapshotSequenceState: snapshot.historySequenceState ?? retained.historySequenceState, textStartOffset: 0, }; } @@ -282,7 +308,7 @@ const CLEAR_TERMINAL_TEXT = "\u001b[H\u001b[2J\u001b[3J"; function clearOutput(current: TerminalOutputState, maxBufferBytes: number): TerminalOutputState { // The erase rides over the budget: trimming here would evict the output that set those modes. const cleared = appendOutput( - current, + { ...current, pendingSnapshotSequenceState: undefined }, CLEAR_TERMINAL_TEXT, maxBufferBytes <= 0 ? maxBufferBytes diff --git a/packages/client-runtime/src/state/terminalSession.test.ts b/packages/client-runtime/src/state/terminalSession.test.ts index d4e850b9c8b0a..19401a26c7f89 100644 --- a/packages/client-runtime/src/state/terminalSession.test.ts +++ b/packages/client-runtime/src/state/terminalSession.test.ts @@ -2,7 +2,9 @@ import { describe, expect, it } from "vite-plus/test"; import { EnvironmentId, + retainTerminalSnapshotHistory, retainedTerminalHistory, + terminalSequenceStateAfter, TerminalSessionSnapshot, ThreadId, } from "@t3tools/contracts"; @@ -39,6 +41,88 @@ const BASE_SNAPSHOT: TerminalSessionSnapshot = { }; describe("terminal session reducers", () => { + it.each([ + { + title: "zero-byte attach budget", + history: "\u001b]0;Build ", + budget: 0, + chunks: ["progress", "\u0007"], + attach: true, + }, + { + title: "title cut during observe", + history: "\u001b]0;Build ", + budget: 2, + chunks: ["progress", "\u0007"], + attach: false, + }, + { + title: "split surrogate in a cut DCS", + history: "\u001bP" + "中".repeat(2_000) + "\ud83d", + budget: 4_096, + chunks: ["\ude00"], + attach: true, + }, + { + title: "CSI omitted after replayable history", + history: "before\n", + budget: 8_192, + chunks: ["C"], + attach: false, + historySequenceState: terminalSequenceStateAfter(0, "\u001b[20"), + }, + { + title: "SGR replacing an omitted OSC", + history: "before\n", + budget: 8_192, + chunks: ["progress", "\u001b[31m"], + attach: false, + historySequenceState: terminalSequenceStateAfter(0, "\u001b]0;title"), + escapeReplay: "\u001b[31m", + }, + { + title: "split string terminator after an omitted OSC", + history: "before\n", + budget: 8_192, + chunks: ["progress", "\u001b", "\\"], + attach: false, + historySequenceState: terminalSequenceStateAfter(0, "\u001b]0;title"), + }, + ])( + "skips a continuation after $title", + ({ history, budget, chunks, attach, historySequenceState, escapeReplay }) => { + const snapshot = { + ...BASE_SNAPSHOT, + ...(attach + ? retainTerminalSnapshotHistory(history, budget) + : { history, historySequenceState }), + }; + const clientBudget = attach ? 8_192 : budget; + let state = applyTerminalAttachStreamEvent( + EMPTY_TERMINAL_BUFFER_STATE, + { type: "snapshot", snapshot }, + clientBudget, + ); + const initial = readTerminalOutputUpdate(state.output, INITIAL_TERMINAL_OUTPUT_CURSOR); + const replayed = historySequenceState === undefined ? "" : history; + expect(initial).toMatchObject({ type: "reset", data: replayed }); + let cursor = initial.cursor; + for (const data of [...chunks, "ok"]) { + state = applyTerminalAttachStreamEvent( + state, + { type: "output", threadId: TARGET.threadId, terminalId: TARGET.terminalId, data }, + clientBudget, + ); + const update = readTerminalOutputUpdate(state.output, cursor); + expect("data" in update ? update.data : "").toBe( + data === "ok" || data === escapeReplay ? data : "", + ); + cursor = update.cursor; + } + expect(terminalOutputText(state.output)).toBe(replayed + (escapeReplay ?? "") + "ok"); + }, + ); + it("prefers live attach status over stale metadata after the attach stream starts", () => { const summary = applyTerminalMetadataStreamEvent([], { type: "snapshot", diff --git a/packages/client-runtime/src/state/terminalSession.ts b/packages/client-runtime/src/state/terminalSession.ts index cedc25ec62d48..a7224209920bc 100644 --- a/packages/client-runtime/src/state/terminalSession.ts +++ b/packages/client-runtime/src/state/terminalSession.ts @@ -115,7 +115,7 @@ function terminalBufferStateFromSnapshot( current: TerminalBufferState = EMPTY_TERMINAL_BUFFER_STATE, ): TerminalBufferState { return { - output: resetOutput(current.output, snapshot.history, maxBufferBytes), + output: resetOutput(current.output, snapshot, maxBufferBytes), grid: nextGrid(current.grid, snapshot), status: snapshot.status, error: snapshot.error ?? null, diff --git a/packages/contracts/src/terminal.ts b/packages/contracts/src/terminal.ts index 09678600764b2..31419fe56374b 100644 --- a/packages/contracts/src/terminal.ts +++ b/packages/contracts/src/terminal.ts @@ -97,6 +97,31 @@ export function terminalSequenceEnd(state: number, text: string): number { return index; } +/** Skip the continuation of an omitted snapshot prefix, retaining any new escape sequence. */ +export function skipTerminalSnapshotContinuation(state: number, data: string) { + if (data.length === 0) return { state, data }; + if (state === SEQUENCE_ESCAPE) { + return { + state: TERMINAL_SEQUENCE_GROUND, + data: data[0] === "\\" ? data.slice(1) : "\u001b" + data, + }; + } + + const escape = data.indexOf("\u001b"); + const prefix = escape < 0 ? data : data.slice(0, escape); + const end = terminalSequenceEnd(state, prefix); + const next = terminalSequenceStateAfter(state, prefix, 0, end); + if (next === TERMINAL_SEQUENCE_GROUND || escape < 0) { + return { state: next, data: data.slice(end) }; + } + // Hold a final ESC until we know whether it starts a new sequence or completes ST. + if (escape + 1 === data.length) return { state: SEQUENCE_ESCAPE, data: "" }; + return { + state: TERMINAL_SEQUENCE_GROUND, + data: data.slice(data[escape + 1] === "\\" ? escape + 2 : escape), + }; +} + /** * The final `maxBytes` of UTF-8 a client retains, starting at a code point boundary and * outside any control sequence the cut went through. @@ -130,6 +155,22 @@ export function retainedTerminalHistory(history: string, maxBytes: number): stri return retained.slice(terminalSequenceEnd(state, retained)); } +/** Keep a whole unfinished prefix when possible, or skip its continuation during replay. */ +export function retainTerminalSnapshotHistory(history: string, maxBytes: number) { + const retained = retainedTerminalHistory(history, maxBytes); + if (retained.length > 0) return { history: retained }; + + // The last ESC starts a sequence independently of the discarded prefix. + const start = history.lastIndexOf("\u001b"); + if (start < 0) return { history: retained }; + const state = terminalSequenceStateAfter(TERMINAL_SEQUENCE_GROUND, history, start); + if (state === TERMINAL_SEQUENCE_GROUND) return { history: retained }; + const pending = history.slice(start); + return historyEncoder.encode(pending).byteLength <= maxBytes + ? { history: pending } + : { history: "", historySequenceState: state }; +} + const TrimmedNonEmptyStringSchema = TrimmedNonEmptyString; const TerminalColsSchema = Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)).check( Schema.isLessThanOrEqualTo(1000), @@ -170,8 +211,15 @@ export const TerminalOpenInput = Schema.Struct({ }); export type TerminalOpenInput = typeof TerminalOpenInput.Type; -export const TerminalAttachInput = Schema.Struct({ +export const TerminalObserveInput = Schema.Struct({ ...TerminalSessionInput.fields, + // The viewer can skip a discarded prefix using the snapshot's parser state. + supportsSnapshotSequenceState: Schema.optional(Schema.Boolean), +}); +export type TerminalObserveInput = Schema.Codec.Encoded; + +export const TerminalAttachInput = Schema.Struct({ + ...TerminalObserveInput.fields, cwd: Schema.optional(TrimmedNonEmptyStringSchema), worktreePath: Schema.optional(Schema.NullOr(TrimmedNonEmptyStringSchema)), cols: Schema.optional(TerminalColsSchema), @@ -187,9 +235,6 @@ export const TerminalAttachInput = Schema.Struct({ }); export type TerminalAttachInput = typeof TerminalAttachInput.Type; -export const TerminalObserveInput = TerminalSessionInput; -export type TerminalObserveInput = Schema.Codec.Encoded; - /** Longest `data` one `terminal.write` carries, in UTF-16 code units. */ export const TERMINAL_WRITE_MAX_LENGTH = 65_536; @@ -250,6 +295,10 @@ export const TerminalSessionSnapshot = Schema.Struct({ status: TerminalSessionStatus, pid: Schema.NullOr(Schema.Int.check(Schema.isGreaterThan(0))), history: Schema.String, + // Parser state of an unfinished prefix omitted after the replayable history. + historySequenceState: Schema.optional( + Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: (0xdbff << 3) | SEQUENCE_OSC })), + ), exitCode: Schema.NullOr(Schema.Int), exitSignal: Schema.NullOr(Schema.Int), label: Schema.String.check(Schema.isMaxLength(128)), From 25bbfb34c85d993812b05c732b20fe94c88c530a Mon Sep 17 00:00:00 2001 From: usedhonda Date: Wed, 25 Nov 2026 21:33:23 +0800 Subject: [PATCH 028/238] fix(release): preserve the web asset manifest (#42806) Co-authored-by: usedhonda <70754+usedhonda@users.noreply.github.com> Co-authored-by: Julius Marminge --- .github/workflows/release-desktop.yml | 9 +++++++++ .github/workflows/release.yml | 9 +++++++++ scripts/smoke-cli-archive.ts | 1 + 3 files changed, 19 insertions(+) diff --git a/.github/workflows/release-desktop.yml b/.github/workflows/release-desktop.yml index 2d3a38168c79e..6ead5f98ee102 100644 --- a/.github/workflows/release-desktop.yml +++ b/.github/workflows/release-desktop.yml @@ -281,6 +281,15 @@ jobs: name: js-bundle path: apps + - name: Restore web asset manifest + shell: bash + run: | + client=apps/server/dist/client + if [[ -f "$client/vite-manifest.release.json" ]]; then + mkdir -p "$client/.vite" + mv "$client/vite-manifest.release.json" "$client/.vite/manifest.json" + fi + - name: Install cargo-xwin if: inputs.platform == 'win' && steps.resource_monitor_cache.outputs.cache-hit != 'true' uses: taiki-e/install-action@cfdb7ed4ccc7c7dce37759eae89dc5674b469b39 # v2.90.3 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 6fe82ebcb0069..7caf4aeb2882e 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -601,6 +601,15 @@ jobs: T3CODE_TELEMETRY_CHANNEL: ${{ github.repository == 'pingdotgg/t3code' && needs.preflight.outputs.release_channel || 'dev' }} run: vp run ${{ steps.bundle_build.outputs.script }} + # Upload only the expected hidden file, without opting all build outputs into hidden uploads. + - name: Stage web asset manifest + shell: bash + run: | + manifest=apps/server/dist/client/.vite/manifest.json + if [[ -f "$manifest" ]]; then + cp "$manifest" apps/server/dist/client/vite-manifest.release.json + fi + # Two paths under apps/ so the artifact root is apps/; consumers download # into `apps` to restore both at their original locations. - name: Upload JS bundle diff --git a/scripts/smoke-cli-archive.ts b/scripts/smoke-cli-archive.ts index e11d63c308185..9a8f9e3b34991 100644 --- a/scripts/smoke-cli-archive.ts +++ b/scripts/smoke-cli-archive.ts @@ -101,6 +101,7 @@ const smokeCliArchive = Effect.fn("smokeCliArchive")(function* (input: { for (const required of [ executable, path.join(contentDir, "client/index.html"), + path.join(contentDir, "client/.vite/manifest.json"), ...(platform === "linux" ? [bundledLibatomic, `${bundledLibatomic}.LICENSE`] : []), ]) { if (!(yield* fs.exists(required))) { From e3f7eb50856870fa52f5c2864294639a1f0fa2d2 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 25 Nov 2026 05:44:25 -0800 Subject: [PATCH 029/238] fix(web): Changes pane explains a diff of only hidden test files (#42851) --- .../src/components/DiffPanel.browser.test.tsx | 30 +++++++++++++++++++ apps/web/src/components/DiffPanel.tsx | 14 ++++++++- 2 files changed, 43 insertions(+), 1 deletion(-) diff --git a/apps/web/src/components/DiffPanel.browser.test.tsx b/apps/web/src/components/DiffPanel.browser.test.tsx index 685cac0fc7f62..2e1990b29b63e 100644 --- a/apps/web/src/components/DiffPanel.browser.test.tsx +++ b/apps/web/src/components/DiffPanel.browser.test.tsx @@ -282,6 +282,36 @@ it("opens a repository-relative file from a nested project without a remote", as ).toMatchObject({ activeSurfaceId: "file:back\\slash.txt" }); }); +it("explains a branch diff whose only changes are hidden test files", async () => { + using context = setup("origin/orphan"); + using _hideTestFiles = { + [Symbol.dispose]() { + window.localStorage.removeItem("t3code.diffHideTestFiles"); + }, + }; + const path = "math.test.ts"; + const metadata = preview(); + const source = { + ...metadata.sources[0]!, + files: [{ path, previousPath: null, additions: 1, deletions: 0 }], + }; + state.previews.set("main", Atom.make(AsyncResult.success({ ...metadata, sources: [source] }))); + useDiffPanelStore.getState().selectBranchBaseRef(context.threadRef, "main"); + await using screen = await render( + +
    + +
    +
    , + ); + await expect.element(screen.getByText(path, { exact: true })).toBeVisible(); + await userEvent.click(screen.getByRole("button", { name: "Hide test files", exact: true })); + await expect.element(screen.getByText(path, { exact: true })).not.toBeInTheDocument(); + await expect.element(screen.getByText("1 test file hidden", { exact: true })).toBeVisible(); + await userEvent.click(screen.getByRole("button", { name: "Show test files", exact: true })); + await expect.element(screen.getByText(path, { exact: true })).toBeVisible(); +}); + it.each([false, true])( "expands an unloaded file on the first click with default collapse %s", async (collapsed) => { diff --git a/apps/web/src/components/DiffPanel.tsx b/apps/web/src/components/DiffPanel.tsx index 561bcd2b3e040..c20f426a522ad 100644 --- a/apps/web/src/components/DiffPanel.tsx +++ b/apps/web/src/components/DiffPanel.tsx @@ -81,7 +81,7 @@ import { DiffFileTree } from "./diffs/DiffFileTree"; import { FileExplorerPane } from "./files/FileExplorerPane"; import { diffFileTreeEntries } from "./diffs/diffFileTree.logic"; import { getDiffHeaderClickAction } from "./diffs/diffHeaderClick"; -import { Button } from "./ui/button"; +import { Button, InlineButton } from "./ui/button"; import { ToggleGroup, Toggle } from "./ui/toggle-group"; import { Switch } from "./ui/switch"; import { @@ -1676,6 +1676,18 @@ export default function DiffPanel({

    ) + ) : shownFileEntries.length === 0 && testFileCount > 0 ? ( +
    +

    + {gt( + "{count, plural, one {{count} test file hidden} other {{count} test files hidden}}", + { count: testFileCount }, + )} +

    + setHideTestFiles(false)}> + {gt("Show test files")} + +
    ) : lazySource || renderablePatch?.kind === "files" ? (
    Date: Wed, 25 Nov 2026 05:44:39 -0800 Subject: [PATCH 030/238] fix(web): panel resize handle no longer covers the chat scrollbar on touch devices (#42852) --- apps/web/src/components/preview/RightPanelResizeHandle.tsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/apps/web/src/components/preview/RightPanelResizeHandle.tsx b/apps/web/src/components/preview/RightPanelResizeHandle.tsx index affd8ee729388..616adf12a29e5 100644 --- a/apps/web/src/components/preview/RightPanelResizeHandle.tsx +++ b/apps/web/src/components/preview/RightPanelResizeHandle.tsx @@ -19,14 +19,14 @@ export function RightPanelResizeHandle({ handlers, className, label, ...separato aria-orientation="vertical" {...separatorProps} className={cn( - "group absolute inset-y-0 left-0 z-40 w-1 cursor-col-resize touch-none select-none any-pointer-coarse:-left-2 any-pointer-coarse:w-4", + "group absolute inset-y-0 left-0 z-40 w-1 cursor-col-resize touch-none select-none any-pointer-coarse:w-2", className, )} {...handlers} >
    ); From d2a9b77499c3157d7724bc180b844c5c9e5ec069 Mon Sep 17 00:00:00 2001 From: Soroush Baraouf Date: Wed, 25 Nov 2026 08:49:24 -0500 Subject: [PATCH 031/238] fix(server): linked workflow steps recover replies from older pages (#42818) Co-authored-by: Julius Marminge --- .../src/workflows/WorkflowAgentLinks.test.ts | 109 ++++++++++++++++++ .../src/workflows/WorkflowAgentLinks.ts | 21 +++- 2 files changed, 126 insertions(+), 4 deletions(-) diff --git a/apps/server/src/workflows/WorkflowAgentLinks.test.ts b/apps/server/src/workflows/WorkflowAgentLinks.test.ts index 8fcba6dc9f3f8..0f2e4f1ecf35f 100644 --- a/apps/server/src/workflows/WorkflowAgentLinks.test.ts +++ b/apps/server/src/workflows/WorkflowAgentLinks.test.ts @@ -59,6 +59,42 @@ const input = { const run = (status: string) => ({ recentRuns: [{ runId: "turn-1", status }], items: [] }); const waited = { threadId: "thread-1", runId: "turn-1", status: "idle" }; +const assistant = (position: number, runId: string, text: string) => ({ + type: "assistant_message", + itemId: `item-${position}`, + position, + runId, + text, + textTruncated: false, +}); +const page = ( + items: ReadonlyArray>, + earlierPosition?: number | null, + hasMore = false, +) => ({ + recentRuns: [], + items, + earlierPosition, + hasMore, + nextPosition: items.at(-1)?.position ?? null, +}); +const readReply = (...pages: ReadonlyArray) => { + const there = peer({ + t3_thread_wait: [{ ...waited, timedOut: false }], + t3_thread_read: [run("completed"), ...pages], + }); + return Effect.gen(function* () { + const result = yield* Effect.provide( + Effect.flatMap(WorkflowAgentLinks.make, (links) => + links.result({ threadId: "thread-1", turnId: "turn-1" }, "env-b"), + ), + there.layer, + ); + return { result, reads: there.calls.slice(2).map((call) => call.arguments) }; + }); +}; +const messageRead = { threadId: "thread-1", view: "messages", limit: 100 }; + it.effect("starts a thread there by the project's folder, with the step's key as the request", () => Effect.gen(function* () { const there = peer({ @@ -224,6 +260,79 @@ it.effect("waits in pieces, rides out a dropped route, and returns the output an }), ); +it.effect("returns the whole last reply from an older page of a linked thread", () => + Effect.gen(function* () { + const later = { + ...assistant(4, "turn-1", "Latest "), + textTruncated: true, + nextTextOffset: 7, + }; + const { result, reads } = yield* readReply( + page([assistant(9, "turn-3", "newest turn")], 9), + page([assistant(6, "turn-2", "another turn")], 6, true), + page([assistant(3, "turn-1", "earlier draft"), later], 3, true), + page([{ ...later, text: "complete reply", textTruncated: false }]), + ); + assert.deepStrictEqual(result, { + ending: "completed", + detail: "", + reply: "Latest complete reply", + }); + assert.deepStrictEqual(reads, [ + messageRead, + { ...messageRead, beforePosition: 9 }, + { ...messageRead, beforePosition: 6 }, + { threadId: "thread-1", itemId: "item-4", textOffset: 7, maxCharsPerItem: 50_000 }, + ]); + }), +); + +it.effect("keeps the latest matching reply when paging a legacy peer forward", () => + Effect.gen(function* () { + for (const earlierPosition of [undefined, null]) { + const { result, reads } = yield* readReply( + page([assistant(2, "turn-1", "draft")], earlierPosition, true), + page([assistant(4, "turn-1", "final")], earlierPosition, true), + page([assistant(6, "turn-2", "other turn")], earlierPosition), + ); + assert.strictEqual(result.reply, "final"); + assert.deepStrictEqual(reads, [ + messageRead, + { ...messageRead, afterPosition: 2 }, + { ...messageRead, afterPosition: 4 }, + ]); + } + }), +); + +it.effect("keeps the reply when a legacy peer's forward cursor stops advancing", () => + Effect.gen(function* () { + for (const position of [2, 1]) { + const { result, reads } = yield* readReply( + page([assistant(2, "turn-1", "Done.")], undefined, true), + page([assistant(position, "turn-2", "other turn")], undefined, true), + ); + assert.strictEqual(result.reply, "Done."); + assert.deepStrictEqual(reads, [messageRead, { ...messageRead, afterPosition: 2 }]); + } + }), +); + +it.effect( + "returns an empty reply when older pages are exhausted or their cursor stops advancing", + () => + Effect.gen(function* () { + for (const earlierPosition of [null, 3, 4]) { + const { result, reads } = yield* readReply( + page([assistant(3, "turn-2", "other turn")], 3), + page([assistant(1, "turn-0", "another turn")], earlierPosition, true), + ); + assert.deepStrictEqual(result, { ending: "completed", detail: "", reply: "" }); + assert.deepStrictEqual(reads, [messageRead, { ...messageRead, beforePosition: 3 }]); + } + }), +); + it.effect("a turn someone stopped there is stopped, and a refused link fails at once", () => Effect.gen(function* () { const stopped = peer({ diff --git a/apps/server/src/workflows/WorkflowAgentLinks.ts b/apps/server/src/workflows/WorkflowAgentLinks.ts index 8d0bdc1d0c672..1a1678739c112 100644 --- a/apps/server/src/workflows/WorkflowAgentLinks.ts +++ b/apps/server/src/workflows/WorkflowAgentLinks.ts @@ -131,20 +131,33 @@ export const make = Effect.gen(function* () { environment: string, ) { let last: OrchestratorMcpThreadReadResult["items"][number] | undefined; - let afterPosition: number | undefined; + let cursor: { beforePosition?: number; afterPosition?: number } = {}; while (true) { const read = yield* call(environment, "t3_thread_read", OrchestratorMcpThreadReadResult, { threadId: turn.threadId, view: "messages", limit: 100, - ...(afterPosition === undefined ? {} : { afterPosition }), + ...cursor, }); last = read.items.findLast( (item) => item.type === "assistant_message" && item.runId === turn.turnId, ) ?? last; - if (!read.hasMore || read.nextPosition === null) break; - afterPosition = read.nextPosition; + const { earlierPosition, nextPosition, hasMore } = read; + // Backward pages are chronological too, and hasMore points toward newer items. + if (cursor.afterPosition === undefined && earlierPosition != null) { + if (last !== undefined || earlierPosition >= (cursor.beforePosition ?? Infinity)) break; + cursor = { beforePosition: earlierPosition }; + continue; + } + if ( + cursor.beforePosition !== undefined || + !hasMore || + nextPosition === null || + nextPosition <= (cursor.afterPosition ?? -1) + ) + break; + cursor = { afterPosition: nextPosition }; } if (last === undefined) return ""; let text = last.text ?? ""; From 8f5fd287a42f589887c836cd77b9f4d636e45d30 Mon Sep 17 00:00:00 2001 From: Victor Date: Wed, 25 Nov 2026 07:54:26 -0600 Subject: [PATCH 032/238] fix(web,mobile): Usage says "1 session", not "1 sessions" (#42837) Co-authored-by: Julius Marminge --- apps/mobile/src/features/usage/UsageRouteScreen.tsx | 11 +++++++---- apps/mobile/src/i18n/translations/de.json | 2 +- apps/mobile/src/i18n/translations/en.json | 2 +- apps/mobile/src/i18n/translations/es.json | 2 +- apps/mobile/src/i18n/translations/fr.json | 2 +- apps/mobile/src/i18n/translations/ja.json | 2 +- apps/mobile/src/i18n/translations/ko.json | 2 +- apps/mobile/src/i18n/translations/pt-BR.json | 2 +- apps/mobile/src/i18n/translations/ru.json | 2 +- apps/mobile/src/i18n/translations/sv.json | 2 +- apps/mobile/src/i18n/translations/zh.json | 2 +- apps/web/src/components/usage/UsagePage.tsx | 2 +- apps/web/src/i18n/translations/de.json | 1 - apps/web/src/i18n/translations/en.json | 1 - apps/web/src/i18n/translations/es.json | 1 - apps/web/src/i18n/translations/fr.json | 1 - apps/web/src/i18n/translations/ja.json | 1 - apps/web/src/i18n/translations/ko.json | 1 - apps/web/src/i18n/translations/pt-BR.json | 1 - apps/web/src/i18n/translations/ru.json | 1 - apps/web/src/i18n/translations/sv.json | 1 - apps/web/src/i18n/translations/zh.json | 1 - 22 files changed, 18 insertions(+), 25 deletions(-) diff --git a/apps/mobile/src/features/usage/UsageRouteScreen.tsx b/apps/mobile/src/features/usage/UsageRouteScreen.tsx index 48215804ee2dc..599c80e1bc853 100644 --- a/apps/mobile/src/features/usage/UsageRouteScreen.tsx +++ b/apps/mobile/src/features/usage/UsageRouteScreen.tsx @@ -548,10 +548,13 @@ function UsageSummary(props: { readonly merged: MergedUsage; readonly metric: Us {metric === "cost" ? gt("* if billed at full API rate") - : gt("{count, plural, other {Across {sessions} sessions}}", { - count: merged.sessions, - sessions: formatCount(merged.sessions), - })} + : gt( + "{count, plural, one {Across {sessions} session} other {Across {sessions} sessions}}", + { + count: merged.sessions, + sessions: formatCount(merged.sessions), + }, + )} ); diff --git a/apps/mobile/src/i18n/translations/de.json b/apps/mobile/src/i18n/translations/de.json index 0e1e8b79d090a..c0a851fe55fc4 100644 --- a/apps/mobile/src/i18n/translations/de.json +++ b/apps/mobile/src/i18n/translations/de.json @@ -5209,7 +5209,7 @@ "0b363b02a7e17bcb": "Rohe Token-Kosten", "ea4beda46b22b8b0": "Verarbeitete Tokens", "212d974007cacf3f": "* bei Abrechnung zum vollen API-Preis", - "82bc7f1cc5a039fc": "{count, plural, one {Über {sessions} Sitzung} other {Über {sessions} Sitzungen}}", + "45340a7dc1f89d51": "{count, plural, one {Über {sessions} Sitzung} other {Über {sessions} Sitzungen}}", "2a57181a9d128463": "{share} der Kosten · {tokens} Tokens", "d8a6a99fbdda0d3e": "{share} der Tokens · {cost}", "19a3f4f2ba09e787": "Summen", diff --git a/apps/mobile/src/i18n/translations/en.json b/apps/mobile/src/i18n/translations/en.json index f460c7dccd6e2..07b19c65bc2c1 100644 --- a/apps/mobile/src/i18n/translations/en.json +++ b/apps/mobile/src/i18n/translations/en.json @@ -5211,7 +5211,7 @@ "0b363b02a7e17bcb": "Raw token cost", "ea4beda46b22b8b0": "Processed tokens", "212d974007cacf3f": "* if billed at full API rate", - "82bc7f1cc5a039fc": "{count, plural, other {Across {sessions} sessions}}", + "45340a7dc1f89d51": "{count, plural, one {Across {sessions} session} other {Across {sessions} sessions}}", "2a57181a9d128463": "{share} of cost · {tokens} tokens", "d8a6a99fbdda0d3e": "{share} of tokens · {cost}", "19a3f4f2ba09e787": "Totals", diff --git a/apps/mobile/src/i18n/translations/es.json b/apps/mobile/src/i18n/translations/es.json index c80f59cdd9839..a9d0e0a71522c 100644 --- a/apps/mobile/src/i18n/translations/es.json +++ b/apps/mobile/src/i18n/translations/es.json @@ -5203,7 +5203,7 @@ "0b363b02a7e17bcb": "Coste bruto de tokens", "ea4beda46b22b8b0": "Tokens procesados", "212d974007cacf3f": "* si se facturara a la tarifa completa de la API", - "82bc7f1cc5a039fc": "{count, plural, one {En {sessions} sesión} other {En {sessions} sesiones}}", + "45340a7dc1f89d51": "{count, plural, one {En {sessions} sesión} other {En {sessions} sesiones}}", "2a57181a9d128463": "{share} del coste · {tokens} tokens", "d8a6a99fbdda0d3e": "{share} de los tokens · {cost}", "19a3f4f2ba09e787": "Totales", diff --git a/apps/mobile/src/i18n/translations/fr.json b/apps/mobile/src/i18n/translations/fr.json index 746b4cca96776..53f494c1f78a0 100644 --- a/apps/mobile/src/i18n/translations/fr.json +++ b/apps/mobile/src/i18n/translations/fr.json @@ -5203,7 +5203,7 @@ "0b363b02a7e17bcb": "Coût brut des tokens", "ea4beda46b22b8b0": "Tokens traités", "212d974007cacf3f": "* si facturé au tarif API complet", - "82bc7f1cc5a039fc": "{count, plural, one {Sur {sessions} session} other {Sur {sessions} sessions}}", + "45340a7dc1f89d51": "{count, plural, one {Sur {sessions} session} other {Sur {sessions} sessions}}", "2a57181a9d128463": "{share} du coût · {tokens} tokens", "d8a6a99fbdda0d3e": "{share} des tokens · {cost}", "19a3f4f2ba09e787": "Totaux", diff --git a/apps/mobile/src/i18n/translations/ja.json b/apps/mobile/src/i18n/translations/ja.json index 6e58d8c038c2e..b02e036733a2e 100644 --- a/apps/mobile/src/i18n/translations/ja.json +++ b/apps/mobile/src/i18n/translations/ja.json @@ -5183,7 +5183,7 @@ "0b363b02a7e17bcb": "トークンの素のコスト", "ea4beda46b22b8b0": "処理トークン", "212d974007cacf3f": "* API の正規料金で請求された場合", - "82bc7f1cc5a039fc": "{count, plural, other {{sessions} セッションの合計}}", + "45340a7dc1f89d51": "{count, plural, other {{sessions} セッションの合計}}", "2a57181a9d128463": "コストの {share} · {tokens} トークン", "d8a6a99fbdda0d3e": "トークンの {share} · {cost}", "19a3f4f2ba09e787": "合計", diff --git a/apps/mobile/src/i18n/translations/ko.json b/apps/mobile/src/i18n/translations/ko.json index b9584b73f4c25..ea0b2f0fe6bf6 100644 --- a/apps/mobile/src/i18n/translations/ko.json +++ b/apps/mobile/src/i18n/translations/ko.json @@ -5187,7 +5187,7 @@ "0b363b02a7e17bcb": "원시 토큰 비용", "ea4beda46b22b8b0": "처리된 토큰", "212d974007cacf3f": "* 전체 API 요율로 청구되는 경우", - "82bc7f1cc5a039fc": "{count, plural, other {세션 {sessions}개 전체}}", + "45340a7dc1f89d51": "{count, plural, other {세션 {sessions}개 전체}}", "2a57181a9d128463": "비용의 {share} · 토큰 {tokens}개", "d8a6a99fbdda0d3e": "토큰의 {share} · {cost}", "19a3f4f2ba09e787": "합계", diff --git a/apps/mobile/src/i18n/translations/pt-BR.json b/apps/mobile/src/i18n/translations/pt-BR.json index b3134701db673..2d71166e0e693 100644 --- a/apps/mobile/src/i18n/translations/pt-BR.json +++ b/apps/mobile/src/i18n/translations/pt-BR.json @@ -5203,7 +5203,7 @@ "0b363b02a7e17bcb": "Custo bruto de tokens", "ea4beda46b22b8b0": "Tokens processados", "212d974007cacf3f": "* se cobrado pela taxa cheia da API", - "82bc7f1cc5a039fc": "{count, plural, one {Em {sessions} sessões} other {Em {sessions} sessões}}", + "45340a7dc1f89d51": "{count, plural, one {Em {sessions} sessão} other {Em {sessions} sessões}}", "2a57181a9d128463": "{share} do custo · {tokens} tokens", "d8a6a99fbdda0d3e": "{share} dos tokens · {cost}", "19a3f4f2ba09e787": "Totais", diff --git a/apps/mobile/src/i18n/translations/ru.json b/apps/mobile/src/i18n/translations/ru.json index 81c95ba264906..c3b869d1e87b9 100644 --- a/apps/mobile/src/i18n/translations/ru.json +++ b/apps/mobile/src/i18n/translations/ru.json @@ -5282,7 +5282,7 @@ "0b363b02a7e17bcb": "Стоимость токенов без скидок", "ea4beda46b22b8b0": "Обработанные токены", "212d974007cacf3f": "* при оплате по полной цене API", - "82bc7f1cc5a039fc": "{count, plural, one {За {sessions} сеанс} few {За {sessions} сеанса} many {За {sessions} сеансов} other {За {sessions} сеанса}}", + "45340a7dc1f89d51": "{count, plural, one {За {sessions} сеанс} few {За {sessions} сеанса} many {За {sessions} сеансов} other {За {sessions} сеанса}}", "2a57181a9d128463": "{share} стоимости · {tokens} токенов", "d8a6a99fbdda0d3e": "{share} токенов · {cost}", "19a3f4f2ba09e787": "Итоги", diff --git a/apps/mobile/src/i18n/translations/sv.json b/apps/mobile/src/i18n/translations/sv.json index 73a089e773c34..b5ecfc8d466f4 100644 --- a/apps/mobile/src/i18n/translations/sv.json +++ b/apps/mobile/src/i18n/translations/sv.json @@ -5209,7 +5209,7 @@ "0b363b02a7e17bcb": "Rå tokenkostnad", "ea4beda46b22b8b0": "Bearbetade token", "212d974007cacf3f": "* om det debiterades till fullt API-pris", - "82bc7f1cc5a039fc": "{count, plural, one {Över {sessions} session} other {Över {sessions} sessioner}}", + "45340a7dc1f89d51": "{count, plural, one {Över {sessions} session} other {Över {sessions} sessioner}}", "2a57181a9d128463": "{share} av kostnaden · {tokens} token", "d8a6a99fbdda0d3e": "{share} av token · {cost}", "19a3f4f2ba09e787": "Totalt", diff --git a/apps/mobile/src/i18n/translations/zh.json b/apps/mobile/src/i18n/translations/zh.json index 3fe06b30bd525..b9be48c79205f 100644 --- a/apps/mobile/src/i18n/translations/zh.json +++ b/apps/mobile/src/i18n/translations/zh.json @@ -5192,7 +5192,7 @@ "0b363b02a7e17bcb": "原始 token 费用", "ea4beda46b22b8b0": "处理的 token", "212d974007cacf3f": "* 按完整 API 费率计费时", - "82bc7f1cc5a039fc": "{count, plural, other {共 {sessions} 个会话}}", + "45340a7dc1f89d51": "{count, plural, other {共 {sessions} 个会话}}", "2a57181a9d128463": "占费用的 {share} · {tokens} token", "d8a6a99fbdda0d3e": "占 token 的 {share} · {cost}", "19a3f4f2ba09e787": "总计", diff --git a/apps/web/src/components/usage/UsagePage.tsx b/apps/web/src/components/usage/UsagePage.tsx index 0aa227a146fe5..f4aa54b160eb2 100644 --- a/apps/web/src/components/usage/UsagePage.tsx +++ b/apps/web/src/components/usage/UsagePage.tsx @@ -702,7 +702,7 @@ function UsageOverview({

    - {gt("{count, plural, one {{formatted} sessions} other {{formatted} sessions}}", { + {gt("{count, plural, one {{formatted} session} other {{formatted} sessions}}", { count: merged.sessions, formatted: formatCount(merged.sessions, locale), })} diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 96b3cb7f1967a..121682d3175bd 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -12342,7 +12342,6 @@ "d2d071e45a2d6b89": "Wähle eine Umgebung, um Limits zu sehen.", "c9180daea905a0a6": "Wähle eine Umgebung, um die Nutzung zu sehen.", "f0297ec79e896a13": "{environment}: {error}", - "6dcbf651d51d4023": "{count, plural, one {{formatted} Sitzung} other {{formatted} Sitzungen}}", "b01bf98dd90ee819": "API-Schätzung", "bab34b28e9ee8e88": "Details zur Nutzung ohne Preis", "61571f4542da9903": "{count, plural, one {{formatted} Sitzung} other {{formatted} Sitzungen}}", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index 311e476e747ea..945814048420e 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -12350,7 +12350,6 @@ "d2d071e45a2d6b89": "Select an environment to see limits.", "c9180daea905a0a6": "Select an environment to see usage.", "f0297ec79e896a13": "{environment}: {error}", - "6dcbf651d51d4023": "{count, plural, one {{formatted} sessions} other {{formatted} sessions}}", "b01bf98dd90ee819": "API estimate", "bab34b28e9ee8e88": "Unpriced usage details", "61571f4542da9903": "{count, plural, one {{formatted} session} other {{formatted} sessions}}", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index 56c909b7dd178..f6dd7cccaa75a 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -12335,7 +12335,6 @@ "d2d071e45a2d6b89": "Selecciona un entorno para ver los límites.", "c9180daea905a0a6": "Selecciona un entorno para ver el uso.", "f0297ec79e896a13": "{environment}: {error}", - "6dcbf651d51d4023": "{count, plural, one {{formatted} sesión} other {{formatted} sesiones}}", "b01bf98dd90ee819": "Estimación de API", "bab34b28e9ee8e88": "Detalles del uso sin precio", "61571f4542da9903": "{count, plural, one {{formatted} sesión} other {{formatted} sesiones}}", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index 23a7578590f54..e3b5807b3da59 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -12340,7 +12340,6 @@ "d2d071e45a2d6b89": "Sélectionnez un environnement pour voir les limites.", "c9180daea905a0a6": "Sélectionnez un environnement pour voir l’utilisation.", "f0297ec79e896a13": "{environment} : {error}", - "6dcbf651d51d4023": "{count, plural, one {{formatted} session} other {{formatted} sessions}}", "b01bf98dd90ee819": "Estimation API", "bab34b28e9ee8e88": "Détails de l’utilisation sans prix", "61571f4542da9903": "{count, plural, one {{formatted} session} other {{formatted} sessions}}", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index c89a28f54095d..22421d690a26a 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -12290,7 +12290,6 @@ "d2d071e45a2d6b89": "上限を表示するには環境を選択してください。", "c9180daea905a0a6": "使用量を表示するには環境を選択してください。", "f0297ec79e896a13": "{environment}: {error}", - "6dcbf651d51d4023": "{count, plural, other {{formatted} セッション}}", "b01bf98dd90ee819": "API の推定額", "bab34b28e9ee8e88": "価格不明の使用量の詳細", "61571f4542da9903": "{count, plural, other {{formatted} セッション}}", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index 760c1546802f6..d0773f6146b3d 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -12286,7 +12286,6 @@ "d2d071e45a2d6b89": "한도를 보려면 환경을 선택하세요.", "c9180daea905a0a6": "사용량을 보려면 환경을 선택하세요.", "f0297ec79e896a13": "{environment}: {error}", - "6dcbf651d51d4023": "{count, plural, other {세션 {formatted}개}}", "b01bf98dd90ee819": "API 추정치", "bab34b28e9ee8e88": "가격 없는 사용량 세부 정보", "61571f4542da9903": "{count, plural, other {세션 {formatted}개}}", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index a616078c936f6..ed3816a288bff 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -12340,7 +12340,6 @@ "d2d071e45a2d6b89": "Selecione um ambiente para ver os limites.", "c9180daea905a0a6": "Selecione um ambiente para ver o uso.", "f0297ec79e896a13": "{environment}: {error}", - "6dcbf651d51d4023": "{count, plural, one {{formatted} sessão} other {{formatted} sessões}}", "b01bf98dd90ee819": "Estimativa da API", "bab34b28e9ee8e88": "Detalhes do uso sem preço", "61571f4542da9903": "{count, plural, one {{formatted} sessão} other {{formatted} sessões}}", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 30cdb82efc3a2..e72c7773214b7 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -12341,7 +12341,6 @@ "d2d071e45a2d6b89": "Выберите окружение, чтобы увидеть лимиты.", "c9180daea905a0a6": "Выберите окружение, чтобы увидеть использование.", "f0297ec79e896a13": "{environment}: {error}", - "6dcbf651d51d4023": "{count, plural, one {{formatted} сеанс} few {{formatted} сеанса} many {{formatted} сеансов} other {{formatted} сеанса}}", "b01bf98dd90ee819": "Оценка по API", "bab34b28e9ee8e88": "Подробности использования без цены", "61571f4542da9903": "{count, plural, one {{formatted} сеанс} few {{formatted} сеанса} many {{formatted} сеансов} other {{formatted} сеанса}}", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index 9c524ac8b6e42..0756c1b15fa95 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -12348,7 +12348,6 @@ "d2d071e45a2d6b89": "Välj en miljö för att se gränser.", "c9180daea905a0a6": "Välj en miljö för att se användning.", "f0297ec79e896a13": "{environment}: {error}", - "6dcbf651d51d4023": "{count, plural, one {{formatted} session} other {{formatted} sessioner}}", "b01bf98dd90ee819": "API-uppskattning", "bab34b28e9ee8e88": "Detaljer om användning utan pris", "61571f4542da9903": "{count, plural, one {{formatted} session} other {{formatted} sessioner}}", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index 341422731b4c0..cee3d72a497a2 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -12365,7 +12365,6 @@ "d2d071e45a2d6b89": "选择一个环境即可查看限制。", "c9180daea905a0a6": "选择一个环境即可查看用量。", "f0297ec79e896a13": "{environment}:{error}", - "6dcbf651d51d4023": "{count, plural, other {{formatted} 个会话}}", "b01bf98dd90ee819": "API 估算", "bab34b28e9ee8e88": "未定价用量的详情", "61571f4542da9903": "{count, plural, other {{formatted} 个会话}}", From 19a6e5b57be7b016e037f14ab05ec2c12f0d4853 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 25 Nov 2026 06:06:56 -0800 Subject: [PATCH 033/238] fix(web): clicking outside a citation comment keeps its dictation (#42856) --- .../AssistantCitationChip.browser.test.tsx | 125 +++++++++++++++++- .../components/chat/AssistantCitationChip.tsx | 19 ++- .../chat/AssistantCitationCommentEditor.tsx | 25 +++- 3 files changed, 163 insertions(+), 6 deletions(-) diff --git a/apps/web/src/components/chat/AssistantCitationChip.browser.test.tsx b/apps/web/src/components/chat/AssistantCitationChip.browser.test.tsx index 53cf01fbbc645..8d02e359d3f36 100644 --- a/apps/web/src/components/chat/AssistantCitationChip.browser.test.tsx +++ b/apps/web/src/components/chat/AssistantCitationChip.browser.test.tsx @@ -7,13 +7,86 @@ import { } from "@t3tools/contracts"; import { useState, type ReactNode } from "react"; import { describe, expect, it, vi } from "vite-plus/test"; -import { userEvent } from "vite-plus/test/browser"; +import { page, userEvent } from "vite-plus/test/browser"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; import type { AssistantCitationSourceAnchor } from "~/lib/assistantTextSelection"; import "~/index.css"; import { act, render } from "../../../test/render"; +import { chooseAudioDestination, chooseTranscriptCleanup } from "../../speech/voiceConsent"; -const mocks = vi.hoisted(() => ({ observeSource: vi.fn(), dispose: vi.fn() })); +const mocks = vi.hoisted(() => ({ + observeSource: vi.fn(), + dispose: vi.fn(), + transcribeCalls: 0, + transcript: null as Promise | null, +})); +const environment = vi.hoisted(() => ({ + environmentId: "environment", + serverConfig: { + environment: { capabilities: { voiceTranscription: true, cloudVoiceTranscription: false } }, + }, +})); +const preparedConnection = vi.hoisted(() => ({ + environmentId: "environment", + label: "environment", +})); +vi.mock(import("../../state/session"), async (importOriginal) => ({ + ...(await importOriginal()), + useEnvironmentScope: () => true, + usePreparedConnection: ((environmentId: string | null) => + environmentId === preparedConnection.environmentId + ? Option.some(preparedConnection) + : Option.none()) as never, +})); +vi.mock(import("../../state/environments"), async (importOriginal) => ({ + ...(await importOriginal()), + useEnvironment: ((environmentId: string | null) => + environmentId === environment.environmentId ? environment : null) as never, +})); +vi.mock(import("../../speech/runEnvironmentSpeech"), () => ({ + runEnvironmentSpeech: Effect.runPromise as never, +})); +vi.mock(import("@t3tools/client-runtime/voice-input"), async (importOriginal) => ({ + ...(await importOriginal()), + getEnvironmentSpeechStatus: (() => + Effect.succeed({ + supported: true, + state: "ready", + modelId: "test-model", + model: "Test", + size: 1, + supportsStreaming: false, + supportsTranslation: false, + acceleration: "auto", + benchmarkTier: "accelerated", + modelUnloadTimeout: "min_15", + gpuDevices: [], + })) as never, +})); +vi.mock(import("../../speech/browserVoiceInput"), () => ({ + createAppleSpeechVoiceInputPlatform: vi.fn() as never, + createBrowserVoiceInputPlatform: (() => ({ + recorder: { + uri: "blob:recording", + prepareToRecordAsync: async () => {}, + record() {}, + stop: async () => {}, + }, + transcriber: { + prepare: async () => ({ + locale: "en", + transcribe: async () => { + mocks.transcribeCalls += 1; + return mocks.transcript ?? "dictated comment"; + }, + }), + }, + cancelRecording() {}, + deleteRecording() {}, + })) as never, +})); vi.mock(import("./AssistantCitationSource"), async (importOriginal) => ({ ...(await importOriginal()), observeAssistantCitationCommentSource: mocks.observeSource, @@ -51,6 +124,13 @@ function setup() { return { sourceAnchor, [Symbol.dispose]: () => source.remove() }; } +function useDictation() { + chooseAudioDestination({ kind: "environment", environmentId: citation.environmentId }); + chooseTranscriptCleanup(false); + mocks.transcribeCalls = 0; + mocks.transcript = null; +} + function mount( sourceAnchor: AssistantCitationSourceAnchor | undefined, onSave: () => boolean, @@ -65,7 +145,12 @@ function mount( /> ); } - return render(); + return render( + <> + + + , + ); } const textarea = () => @@ -247,3 +332,37 @@ describe("citation comment popup position", () => { expect(rect.right).toBeLessThanOrEqual(window.innerWidth); }); }); + +describe("citation comment dictation", () => { + async function startDictation(onSave: () => boolean) { + using _source = setup(); + useDictation(); + const screen = await mount(undefined, onSave); + await page.getByRole("button", { name: "Start voice input" }).click(); + await expect.element(page.getByRole("button", { name: "Finish voice input" })).toBeVisible(); + return screen; + } + + it("keeps the dictation when the box is clicked away while recording", async () => { + const onSave = vi.fn(() => true); + await using _screen = await startDictation(onSave); + + await page.getByRole("button", { name: "Outside" }).click(); + + await vi.waitFor(() => expect(onSave).toHaveBeenCalledWith("dictated comment")); + }); + + it("keeps the dictation when the box is clicked away while transcribing", async () => { + const onSave = vi.fn(() => true); + await using _screen = await startDictation(onSave); + let finish!: (text: string) => void; + mocks.transcript = new Promise((resolve) => (finish = resolve)); + await page.getByRole("button", { name: "Finish voice input" }).click(); + await vi.waitFor(() => expect(mocks.transcribeCalls).toBe(1)); + + await page.getByRole("button", { name: "Outside" }).click(); + finish("dictated comment"); + + await vi.waitFor(() => expect(onSave).toHaveBeenCalledWith("dictated comment")); + }); +}); diff --git a/apps/web/src/components/chat/AssistantCitationChip.tsx b/apps/web/src/components/chat/AssistantCitationChip.tsx index 15aa53a2d3487..3bcc1215991d1 100644 --- a/apps/web/src/components/chat/AssistantCitationChip.tsx +++ b/apps/web/src/components/chat/AssistantCitationChip.tsx @@ -27,7 +27,10 @@ import { cn } from "~/lib/utils"; import { useQuietThreadShell } from "~/state/entities"; import { ContextChip, ContextChipAction, ContextChipLabel } from "../ContextChip"; import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover"; -import { AssistantCitationCommentEditor } from "./AssistantCitationCommentEditor"; +import { + AssistantCitationCommentEditor, + type AssistantCitationCommentDictation, +} from "./AssistantCitationCommentEditor"; import { resolveAssistantCitationCommentDismissal } from "./assistantCitationCommentDismissal"; import { observeAssistantCitationCommentSource } from "./AssistantCitationSource"; import { composerFloatingLayerProps } from "./composerEventScope"; @@ -200,6 +203,7 @@ export function AssistantCitationChip({ const commentInputRef = useRef(null); const commentPopupRef = useRef(null); const draftCommentRef = useRef(null); + const dictationRef = useRef(null); const [voiceSetupOpen, setVoiceSetupOpen] = useState(false); const [unavailableSourceAnchor, setUnavailableSourceAnchor] = useState(null); @@ -210,7 +214,7 @@ export function AssistantCitationChip({ useEffect(() => { if (!commentOpen) draftCommentRef.current = null; }, [commentOpen]); - const settleDraftOnClose = (reason: string): boolean => { + const settleDraft = (reason: string): boolean => { const dismissal = resolveAssistantCitationCommentDismissal({ reason, draft: draftCommentRef.current, @@ -219,6 +223,16 @@ export function AssistantCitationChip({ if (dismissal.kind === "commit") return commentEditor?.onSave(dismissal.comment) ?? true; return dismissal.kind !== "keep-open"; }; + // Closing unmounts the editor, which would discard its dictation, so it stays open until that lands. + const settleDraftOnClose = (reason: string): boolean => { + const finishing = + reason !== "escape-key" && + dictationRef.current?.finish((comment) => { + draftCommentRef.current = comment; + if (settleDraft(reason)) commentEditor?.onOpenChange(false); + }); + return !finishing && settleDraft(reason); + }; // The timeline virtualizes rows, so a vanished source is routine; the user may still be typing. const onSourceUnavailable = useEffectEvent(() => { if (sourceAnchor) setUnavailableSourceAnchor(sourceAnchor); @@ -334,6 +348,7 @@ export function AssistantCitationChip({ key={serializeAssistantCitation(citation)} citation={citation} inputRef={commentInputRef} + dictationRef={dictationRef} onVoiceSetupOpenChange={setVoiceSetupOpen} onDraftChange={(comment) => { draftCommentRef.current = comment; diff --git a/apps/web/src/components/chat/AssistantCitationCommentEditor.tsx b/apps/web/src/components/chat/AssistantCitationCommentEditor.tsx index c8909ddc31fef..67cb1559aa4ff 100644 --- a/apps/web/src/components/chat/AssistantCitationCommentEditor.tsx +++ b/apps/web/src/components/chat/AssistantCitationCommentEditor.tsx @@ -1,6 +1,14 @@ import { ASSISTANT_CITATION_MAX_COMMENT_LENGTH, type AssistantCitation } from "@t3tools/contracts"; import { T, useGT, Var } from "gt-react"; -import { use, useEffect, useRef, useState, type RefObject } from "react"; +import { + use, + useEffect, + useImperativeHandle, + useRef, + useState, + type Ref, + type RefObject, +} from "react"; import { TextFieldSpeechControls, useTextFieldSpeech } from "~/speech/useTextFieldSpeech"; import { textDirection } from "~/textDirection"; @@ -8,6 +16,12 @@ import { textDirection } from "~/textDirection"; import { ComposerContextActionsContext } from "../composerContextActions"; import { Button } from "../ui/button"; +/** Lets the popover finish a running dictation, instead of discarding it, when it is dismissed. */ +export type AssistantCitationCommentDictation = { + /** False when nothing is being dictated; otherwise `settle` gets the comment once it is transcribed. */ + finish: (settle: (comment: string) => void) => boolean; +}; + export function AssistantCitationCommentEditor({ citation, inputRef, @@ -16,6 +30,7 @@ export function AssistantCitationCommentEditor({ onCancel, onDraftChange, onVoiceSetupOpenChange, + dictationRef, }: { citation: AssistantCitation; inputRef?: RefObject; @@ -24,6 +39,7 @@ export function AssistantCitationCommentEditor({ onCancel: () => void; onDraftChange?: (comment: string) => void; onVoiceSetupOpenChange?: (open: boolean) => void; + dictationRef?: Ref; }) { const gt = useGT(); const [comment, setComment] = useState(citation.comment ?? ""); @@ -55,6 +71,13 @@ export function AssistantCitationCommentEditor({ onVoiceSetupOpenChange?.(setupOpen); return () => onVoiceSetupOpenChange?.(false); }, [onVoiceSetupOpenChange, setupOpen]); + useImperativeHandle(dictationRef, () => ({ + finish: (settle) => { + if (!speech.blocksSubmission || speech.preparing) return false; + speech.submitAfterDictation(settle); + return true; + }, + })); const commentTooLong = comment.length > ASSISTANT_CITATION_MAX_COMMENT_LENGTH; const submit = () => { speech.submitAfterDictation((text) => { From f1efcfb4948542237f6e2ceb5389de9e23f9baea Mon Sep 17 00:00:00 2001 From: Victor Date: Wed, 25 Nov 2026 08:14:21 -0600 Subject: [PATCH 034/238] fix(client-runtime): feedback trace shows "1 character", not "1 characters" (#42855) Co-authored-by: Julius Marminge --- apps/mobile/src/i18n/translations/de.json | 2 +- apps/mobile/src/i18n/translations/en.json | 2 +- apps/mobile/src/i18n/translations/es.json | 2 +- apps/mobile/src/i18n/translations/fr.json | 2 +- apps/mobile/src/i18n/translations/ja.json | 2 +- apps/mobile/src/i18n/translations/ko.json | 2 +- apps/mobile/src/i18n/translations/pt-BR.json | 2 +- apps/mobile/src/i18n/translations/ru.json | 2 +- apps/mobile/src/i18n/translations/sv.json | 2 +- apps/mobile/src/i18n/translations/zh.json | 2 +- apps/web/src/i18n/translations/de.json | 2 +- apps/web/src/i18n/translations/en.json | 2 +- apps/web/src/i18n/translations/es.json | 2 +- apps/web/src/i18n/translations/fr.json | 2 +- apps/web/src/i18n/translations/ja.json | 2 +- apps/web/src/i18n/translations/ko.json | 2 +- apps/web/src/i18n/translations/pt-BR.json | 2 +- apps/web/src/i18n/translations/ru.json | 2 +- apps/web/src/i18n/translations/sv.json | 2 +- apps/web/src/i18n/translations/zh.json | 2 +- packages/client-runtime/src/feedbackRequest.test.ts | 6 ++++-- packages/client-runtime/src/feedbackRequest.ts | 11 +++++++---- 22 files changed, 31 insertions(+), 26 deletions(-) diff --git a/apps/mobile/src/i18n/translations/de.json b/apps/mobile/src/i18n/translations/de.json index c0a851fe55fc4..3b62045baa01e 100644 --- a/apps/mobile/src/i18n/translations/de.json +++ b/apps/mobile/src/i18n/translations/de.json @@ -66,7 +66,7 @@ "2f6e4f7cd364da73": "Erwartet", "9d11c93d4035de3e": "Tatsächlich passiert", "c87d0595693704f9": "Stattdessen getan", - "d7a4ea6ce5af44e0": "{speaker} · {count} Zeichen", + "ed5c85bb4aecb472": "{count, plural, one {{speaker} · {count} Zeichen} other {{speaker} · {count} Zeichen}}", "f5114fb9c40fd929": "Du", "cd03eb1b84271c02": "Agent", "bfe1a60f3f9c60fb": "Runde {turn} · {what}", diff --git a/apps/mobile/src/i18n/translations/en.json b/apps/mobile/src/i18n/translations/en.json index 07b19c65bc2c1..2e482d69aa7f4 100644 --- a/apps/mobile/src/i18n/translations/en.json +++ b/apps/mobile/src/i18n/translations/en.json @@ -66,7 +66,7 @@ "2f6e4f7cd364da73": "Expected", "9d11c93d4035de3e": "Happened", "c87d0595693704f9": "Did instead", - "d7a4ea6ce5af44e0": "{speaker} · {count} characters", + "ed5c85bb4aecb472": "{count, plural, one {{speaker} · {count} character} other {{speaker} · {count} characters}}", "f5114fb9c40fd929": "You", "cd03eb1b84271c02": "Agent", "bfe1a60f3f9c60fb": "Turn {turn} · {what}", diff --git a/apps/mobile/src/i18n/translations/es.json b/apps/mobile/src/i18n/translations/es.json index a9d0e0a71522c..9f513dfccd516 100644 --- a/apps/mobile/src/i18n/translations/es.json +++ b/apps/mobile/src/i18n/translations/es.json @@ -66,7 +66,7 @@ "2f6e4f7cd364da73": "Resultado esperado", "9d11c93d4035de3e": "Lo que ocurrió", "c87d0595693704f9": "Alternativa utilizada", - "d7a4ea6ce5af44e0": "{speaker} · {count} caracteres", + "ed5c85bb4aecb472": "{count, plural, one {{speaker} · {count} carácter} other {{speaker} · {count} caracteres}}", "f5114fb9c40fd929": "Tú", "cd03eb1b84271c02": "Agente", "bfe1a60f3f9c60fb": "Turno {turn} · {what}", diff --git a/apps/mobile/src/i18n/translations/fr.json b/apps/mobile/src/i18n/translations/fr.json index 53f494c1f78a0..63a62d7f03188 100644 --- a/apps/mobile/src/i18n/translations/fr.json +++ b/apps/mobile/src/i18n/translations/fr.json @@ -66,7 +66,7 @@ "2f6e4f7cd364da73": "Résultat attendu", "9d11c93d4035de3e": "Résultat obtenu", "c87d0595693704f9": "Solution de repli", - "d7a4ea6ce5af44e0": "{speaker} · {count} caractères", + "ed5c85bb4aecb472": "{count, plural, one {{speaker} · {count} caractère} other {{speaker} · {count} caractères}}", "f5114fb9c40fd929": "Vous", "cd03eb1b84271c02": "Agent", "bfe1a60f3f9c60fb": "Tour {turn} · {what}", diff --git a/apps/mobile/src/i18n/translations/ja.json b/apps/mobile/src/i18n/translations/ja.json index b02e036733a2e..f0c24995414d9 100644 --- a/apps/mobile/src/i18n/translations/ja.json +++ b/apps/mobile/src/i18n/translations/ja.json @@ -66,7 +66,7 @@ "2f6e4f7cd364da73": "期待した動作", "9d11c93d4035de3e": "実際の動作", "c87d0595693704f9": "代わりに行ったこと", - "d7a4ea6ce5af44e0": "{speaker} · {count} 文字", + "ed5c85bb4aecb472": "{count, plural, other {{speaker} · {count} 文字}}", "f5114fb9c40fd929": "あなた", "cd03eb1b84271c02": "エージェント", "bfe1a60f3f9c60fb": "ターン {turn} · {what}", diff --git a/apps/mobile/src/i18n/translations/ko.json b/apps/mobile/src/i18n/translations/ko.json index ea0b2f0fe6bf6..e0c188e8c878d 100644 --- a/apps/mobile/src/i18n/translations/ko.json +++ b/apps/mobile/src/i18n/translations/ko.json @@ -66,7 +66,7 @@ "2f6e4f7cd364da73": "기대한 동작", "9d11c93d4035de3e": "실제 동작", "c87d0595693704f9": "대신 한 일", - "d7a4ea6ce5af44e0": "{speaker} · {count}자", + "ed5c85bb4aecb472": "{count, plural, other {{speaker} · {count}자}}", "f5114fb9c40fd929": "나", "cd03eb1b84271c02": "에이전트", "bfe1a60f3f9c60fb": "턴 {turn} · {what}", diff --git a/apps/mobile/src/i18n/translations/pt-BR.json b/apps/mobile/src/i18n/translations/pt-BR.json index 2d71166e0e693..386b5dc53afbf 100644 --- a/apps/mobile/src/i18n/translations/pt-BR.json +++ b/apps/mobile/src/i18n/translations/pt-BR.json @@ -66,7 +66,7 @@ "2f6e4f7cd364da73": "Resultado esperado", "9d11c93d4035de3e": "O que aconteceu", "c87d0595693704f9": "Alternativa utilizada", - "d7a4ea6ce5af44e0": "{speaker} · {count} caracteres", + "ed5c85bb4aecb472": "{count, plural, one {{speaker} · {count} caractere} other {{speaker} · {count} caracteres}}", "f5114fb9c40fd929": "Você", "cd03eb1b84271c02": "Agente", "bfe1a60f3f9c60fb": "Turno {turn} · {what}", diff --git a/apps/mobile/src/i18n/translations/ru.json b/apps/mobile/src/i18n/translations/ru.json index c3b869d1e87b9..c3197052b5fa7 100644 --- a/apps/mobile/src/i18n/translations/ru.json +++ b/apps/mobile/src/i18n/translations/ru.json @@ -66,7 +66,7 @@ "2f6e4f7cd364da73": "Ожидалось", "9d11c93d4035de3e": "Произошло", "c87d0595693704f9": "Что сделано вместо этого", - "d7a4ea6ce5af44e0": "{speaker} · {count} симв.", + "ed5c85bb4aecb472": "{count, plural, one {{speaker} · {count} симв.} few {{speaker} · {count} симв.} many {{speaker} · {count} симв.} other {{speaker} · {count} симв.}}", "f5114fb9c40fd929": "Вы", "cd03eb1b84271c02": "Агент", "bfe1a60f3f9c60fb": "Ход {turn} · {what}", diff --git a/apps/mobile/src/i18n/translations/sv.json b/apps/mobile/src/i18n/translations/sv.json index b5ecfc8d466f4..fa0454bb9f430 100644 --- a/apps/mobile/src/i18n/translations/sv.json +++ b/apps/mobile/src/i18n/translations/sv.json @@ -66,7 +66,7 @@ "2f6e4f7cd364da73": "Förväntat", "9d11c93d4035de3e": "Vad som hände", "c87d0595693704f9": "Gjorde i stället", - "d7a4ea6ce5af44e0": "{speaker} · {count} tecken", + "ed5c85bb4aecb472": "{count, plural, one {{speaker} · {count} tecken} other {{speaker} · {count} tecken}}", "f5114fb9c40fd929": "Du", "cd03eb1b84271c02": "Agent", "bfe1a60f3f9c60fb": "Omgång {turn} · {what}", diff --git a/apps/mobile/src/i18n/translations/zh.json b/apps/mobile/src/i18n/translations/zh.json index b9be48c79205f..5eb155844e938 100644 --- a/apps/mobile/src/i18n/translations/zh.json +++ b/apps/mobile/src/i18n/translations/zh.json @@ -66,7 +66,7 @@ "2f6e4f7cd364da73": "预期行为", "9d11c93d4035de3e": "实际情况", "c87d0595693704f9": "替代做法", - "d7a4ea6ce5af44e0": "{speaker} · {count} 个字符", + "ed5c85bb4aecb472": "{count, plural, other {{speaker} · {count} 个字符}}", "f5114fb9c40fd929": "你", "cd03eb1b84271c02": "智能体", "bfe1a60f3f9c60fb": "第 {turn} 轮 · {what}", diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 121682d3175bd..2f8bb9a78f29e 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -66,7 +66,7 @@ "2f6e4f7cd364da73": "Erwartet", "9d11c93d4035de3e": "Tatsächlich passiert", "c87d0595693704f9": "Stattdessen getan", - "d7a4ea6ce5af44e0": "{speaker} · {count} Zeichen", + "ed5c85bb4aecb472": "{count, plural, one {{speaker} · {count} Zeichen} other {{speaker} · {count} Zeichen}}", "f5114fb9c40fd929": "Du", "cd03eb1b84271c02": "Agent", "bfe1a60f3f9c60fb": "Runde {turn} · {what}", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index 945814048420e..344891fe62609 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -66,7 +66,7 @@ "2f6e4f7cd364da73": "Expected", "9d11c93d4035de3e": "Happened", "c87d0595693704f9": "Did instead", - "d7a4ea6ce5af44e0": "{speaker} · {count} characters", + "ed5c85bb4aecb472": "{count, plural, one {{speaker} · {count} character} other {{speaker} · {count} characters}}", "f5114fb9c40fd929": "You", "cd03eb1b84271c02": "Agent", "bfe1a60f3f9c60fb": "Turn {turn} · {what}", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index f6dd7cccaa75a..38ae9dc156ebc 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -66,7 +66,7 @@ "2f6e4f7cd364da73": "Resultado esperado", "9d11c93d4035de3e": "Lo que ocurrió", "c87d0595693704f9": "Alternativa utilizada", - "d7a4ea6ce5af44e0": "{speaker} · {count} caracteres", + "ed5c85bb4aecb472": "{count, plural, one {{speaker} · {count} carácter} other {{speaker} · {count} caracteres}}", "f5114fb9c40fd929": "Tú", "cd03eb1b84271c02": "Agente", "bfe1a60f3f9c60fb": "Turno {turn} · {what}", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index e3b5807b3da59..57cc6f526c041 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -66,7 +66,7 @@ "2f6e4f7cd364da73": "Résultat attendu", "9d11c93d4035de3e": "Résultat obtenu", "c87d0595693704f9": "Solution de repli", - "d7a4ea6ce5af44e0": "{speaker} · {count} caractères", + "ed5c85bb4aecb472": "{count, plural, one {{speaker} · {count} caractère} other {{speaker} · {count} caractères}}", "f5114fb9c40fd929": "Vous", "cd03eb1b84271c02": "Agent", "bfe1a60f3f9c60fb": "Tour {turn} · {what}", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index 22421d690a26a..5a48ea70d7abc 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -66,7 +66,7 @@ "2f6e4f7cd364da73": "期待した動作", "9d11c93d4035de3e": "実際の動作", "c87d0595693704f9": "代わりに行ったこと", - "d7a4ea6ce5af44e0": "{speaker} · {count} 文字", + "ed5c85bb4aecb472": "{count, plural, other {{speaker} · {count} 文字}}", "f5114fb9c40fd929": "あなた", "cd03eb1b84271c02": "エージェント", "bfe1a60f3f9c60fb": "ターン {turn} · {what}", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index d0773f6146b3d..bdec1db133159 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -66,7 +66,7 @@ "2f6e4f7cd364da73": "기대한 동작", "9d11c93d4035de3e": "실제 동작", "c87d0595693704f9": "대신 한 일", - "d7a4ea6ce5af44e0": "{speaker} · {count}자", + "ed5c85bb4aecb472": "{count, plural, other {{speaker} · {count}자}}", "f5114fb9c40fd929": "나", "cd03eb1b84271c02": "에이전트", "bfe1a60f3f9c60fb": "턴 {turn} · {what}", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index ed3816a288bff..20baf91f8b106 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -66,7 +66,7 @@ "2f6e4f7cd364da73": "Resultado esperado", "9d11c93d4035de3e": "O que aconteceu", "c87d0595693704f9": "Alternativa utilizada", - "d7a4ea6ce5af44e0": "{speaker} · {count} caracteres", + "ed5c85bb4aecb472": "{count, plural, one {{speaker} · {count} caractere} other {{speaker} · {count} caracteres}}", "f5114fb9c40fd929": "Você", "cd03eb1b84271c02": "Agente", "bfe1a60f3f9c60fb": "Turno {turn} · {what}", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index e72c7773214b7..1f58942bc5cfc 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -66,7 +66,7 @@ "2f6e4f7cd364da73": "Ожидалось", "9d11c93d4035de3e": "Произошло", "c87d0595693704f9": "Что сделано вместо этого", - "d7a4ea6ce5af44e0": "{speaker} · {count} симв.", + "ed5c85bb4aecb472": "{count, plural, one {{speaker} · {count} симв.} few {{speaker} · {count} симв.} many {{speaker} · {count} симв.} other {{speaker} · {count} симв.}}", "f5114fb9c40fd929": "Вы", "cd03eb1b84271c02": "Агент", "bfe1a60f3f9c60fb": "Ход {turn} · {what}", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index 0756c1b15fa95..c7370bb2ec772 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -66,7 +66,7 @@ "2f6e4f7cd364da73": "Förväntat", "9d11c93d4035de3e": "Vad som hände", "c87d0595693704f9": "Gjorde i stället", - "d7a4ea6ce5af44e0": "{speaker} · {count} tecken", + "ed5c85bb4aecb472": "{count, plural, one {{speaker} · {count} tecken} other {{speaker} · {count} tecken}}", "f5114fb9c40fd929": "Du", "cd03eb1b84271c02": "Agent", "bfe1a60f3f9c60fb": "Omgång {turn} · {what}", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index cee3d72a497a2..98276b6809237 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -66,7 +66,7 @@ "2f6e4f7cd364da73": "预期行为", "9d11c93d4035de3e": "实际情况", "c87d0595693704f9": "替代做法", - "d7a4ea6ce5af44e0": "{speaker} · {count} 个字符", + "ed5c85bb4aecb472": "{count, plural, other {{speaker} · {count} 个字符}}", "f5114fb9c40fd929": "你", "cd03eb1b84271c02": "智能体", "bfe1a60f3f9c60fb": "第 {turn} 轮 · {what}", diff --git a/packages/client-runtime/src/feedbackRequest.test.ts b/packages/client-runtime/src/feedbackRequest.test.ts index 8c1d5b6cae4bd..6911a213867e7 100644 --- a/packages/client-runtime/src/feedbackRequest.test.ts +++ b/packages/client-runtime/src/feedbackRequest.test.ts @@ -31,8 +31,8 @@ describe("feedbackRequestDisplay", () => { describe("feedback preview", () => { it("shows every field that is sent, and each outline entry with its text", () => { const trace = { - turns: 1, - textTurns: 1, + turns: 2, + textTurns: 2, truncated: false, entries: [ { turn: 1, type: "user" as const, length: 5, text: "Hello" }, @@ -43,6 +43,7 @@ describe("feedback preview", () => { outcome: "error" as const, durationMs: 1_500, }, + { turn: 2, type: "user" as const, length: 1, text: "y" }, ], }; expect( @@ -58,6 +59,7 @@ describe("feedback preview", () => { expect(feedbackTraceLines(trace)).toEqual([ { key: "0", line: "Turn 1 · You · 5 characters", text: "Hello" }, { key: "1", line: "Turn 1 · t3_thread_read · error · 1.5 s" }, + { key: "2", line: "Turn 2 · You · 1 character", text: "y" }, ]); // Text only in turn 4 of 5: the wording reaches back to it, not "the last turn". const older = { diff --git a/packages/client-runtime/src/feedbackRequest.ts b/packages/client-runtime/src/feedbackRequest.ts index f6b0079213ebc..4c131c116d3e1 100644 --- a/packages/client-runtime/src/feedbackRequest.ts +++ b/packages/client-runtime/src/feedbackRequest.ts @@ -86,10 +86,13 @@ export function feedbackTraceLines( .filter((part) => part !== undefined) .join(" · ") : resolve( - msg("{speaker} · {count} characters", { - speaker: resolve(entry.type === "user" ? msg("You") : msg("Agent")), - count: entry.length ?? 0, - }), + msg( + "{count, plural, one {{speaker} · {count} character} other {{speaker} · {count} characters}}", + { + speaker: resolve(entry.type === "user" ? msg("You") : msg("Agent")), + count: entry.length ?? 0, + }, + ), ); return { key: `${index}`, From 7814c9f884b2baff651c132ce38a077767de138d Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 25 Nov 2026 06:30:19 -0800 Subject: [PATCH 035/238] fix(desktop): WSL-only backend no longer falls back to Windows when reg.exe is blocked by policy (#42857) --- .../src/wsl/DesktopWslEnvironment.test.ts | 39 ++++++++++++++++++- apps/desktop/src/wsl/DesktopWslEnvironment.ts | 14 +++++-- 2 files changed, 48 insertions(+), 5 deletions(-) diff --git a/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts b/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts index 470091f334fb7..aab0f0b2f8eea 100644 --- a/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts +++ b/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts @@ -557,6 +557,7 @@ describe("parseResolvedPath", () => { const WSL_EXE = "/windows/System32/wsl.exe"; const STORE_SERVICE = "HKLM\\SYSTEM\\CurrentControlSet\\Services\\WSLService"; const INBOX_SERVICE = "HKLM\\SYSTEM\\CurrentControlSet\\Services\\LxssManager"; +const SERVICES_ROOT = "HKLM\\SYSTEM\\CurrentControlSet\\Services"; const registrySpawner = (keys: ReadonlyArray) => ChildProcessSpawner.make((command) => @@ -570,7 +571,7 @@ const registrySpawner = (keys: ReadonlyArray) => ChildProcessSpawner.ExitCode( command._tag === "StandardCommand" && command.command === "reg.exe" && - keys.some((key) => command.args.includes(key)) + [SERVICES_ROOT, ...keys].some((key) => command.args.includes(key)) ? 0 : 1, ), @@ -608,6 +609,42 @@ describe("makeIsAvailable", () => { }), ); + it.effect("keeps WSL when registry tools are disabled by policy and reg.exe cannot answer", () => + Effect.gen(function* () { + const denied = new TextEncoder().encode( + "ERROR: Registry editing has been disabled by your administrator.\r\n", + ); + const blockedRegistry = ChildProcessSpawner.make(() => + Effect.succeed( + ChildProcessSpawner.makeHandle({ + pid: ChildProcessSpawner.ProcessId(1), + stdout: Stream.empty, + stderr: Stream.make(denied), + all: Stream.make(denied), + exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(1)), + isRunning: Effect.succeed(false), + kill: () => Effect.void, + stdin: Sink.drain, + getInputFd: () => Sink.drain, + getOutputFd: () => Stream.empty, + unref: Effect.succeed(Effect.void), + }), + ), + ); + const available = yield* makeIsAvailable("win32", "/windows").pipe( + Effect.provide( + Layer.mergeAll( + FileSystem.layerNoop({ exists: (path) => Effect.succeed(path === WSL_EXE) }), + Path.layer, + DesktopManagedPolicy.layerTest(undefined), + ), + ), + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, blockedRegistry), + ); + assert.isTrue(available); + }), + ); + it.effect("turns WSL off on a machine with a managed policy, even an invalid one", () => Effect.gen(function* () { assert.isTrue(yield* isAvailable()); diff --git a/apps/desktop/src/wsl/DesktopWslEnvironment.ts b/apps/desktop/src/wsl/DesktopWslEnvironment.ts index 9d9540a65dc7d..afd9ef013299d 100644 --- a/apps/desktop/src/wsl/DesktopWslEnvironment.ts +++ b/apps/desktop/src/wsl/DesktopWslEnvironment.ts @@ -1124,13 +1124,16 @@ const WSL_SERVICE_KEYS = [ "HKLM\\SYSTEM\\CurrentControlSet\\Services\\WSLService", "HKLM\\SYSTEM\\CurrentControlSet\\Services\\LxssManager", ] as const; +// Always present; when reg.exe cannot read it (e.g. "Prevent access to registry editing tools"), +// a failed service query says nothing about WSL, so fall back to trusting wsl.exe. +const SERVICES_ROOT_KEY = "HKLM\\SYSTEM\\CurrentControlSet\\Services"; const SERVICE_QUERY_TIMEOUT = Duration.seconds(5); const wslServiceRegistered = Effect.scoped( Effect.gen(function* () { const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const registered = yield* Effect.forEach( - WSL_SERVICE_KEYS, + const [rootReadable, ...servicesFound] = yield* Effect.forEach( + [SERVICES_ROOT_KEY, ...WSL_SERVICE_KEYS], (key) => spawner .spawn( @@ -1142,10 +1145,13 @@ const wslServiceRegistered = Effect.scoped( forceKillAfter: PROCESS_TERMINATE_GRACE, }), ) - .pipe(Effect.flatMap((handle) => handle.exitCode)), + .pipe( + Effect.flatMap((handle) => handle.exitCode), + Effect.map((exitCode) => (exitCode as unknown as number) === 0), + ), { concurrency: "unbounded" }, ); - return registered.some((exitCode) => (exitCode as unknown as number) === 0); + return rootReadable === false || servicesFound.includes(true); }), ).pipe( Effect.timeoutOption(SERVICE_QUERY_TIMEOUT), From 6cca0b18646b172d00fc0d88e2a80021d6b55372 Mon Sep 17 00:00:00 2001 From: Pedro Sousa Date: Wed, 25 Nov 2026 15:39:56 +0100 Subject: [PATCH 036/238] fix(github): count team review requests in the Reviewing filter (#42835) Co-authored-by: Pedro Sousa <4235827+pedrosousa13@users.noreply.github.com> Co-authored-by: Julius Marminge --- .../server/GitHubPullRequestProvider.test.ts | 71 +++++++++++++++++++ .../src/server/GitHubPullRequestProvider.ts | 20 +++++- 2 files changed, 89 insertions(+), 2 deletions(-) diff --git a/packages/source-control-github/src/server/GitHubPullRequestProvider.test.ts b/packages/source-control-github/src/server/GitHubPullRequestProvider.test.ts index 7d305ac4b7873..ad6eab9634315 100644 --- a/packages/source-control-github/src/server/GitHubPullRequestProvider.test.ts +++ b/packages/source-control-github/src/server/GitHubPullRequestProvider.test.ts @@ -967,6 +967,60 @@ describe("loginAvatarUrl", () => { }); }); +describe("listChangeRequests", () => { + it.effect("counts a team review request as the viewer's only on search rows", () => + Effect.gen(function* () { + const teamOnly = { + number: 1, + title: "Change", + url: "https://github.com/acme/web/pull/1", + author: null, + headBranch: "feature", + baseBranch: "main", + state: "open" as const, + isDraft: false, + mergeability: "mergeable" as const, + additions: 0, + deletions: 0, + createdAt: "2026-07-01T00:00:00Z", + updatedAt: "2026-07-02T00:00:00Z", + reviewRequestLogins: ["someone-else"], + hasTeamReviewRequest: true, + labels: [], + reviewDecision: null, + checksState: null, + }; + const list = (continues: boolean, involvement: "all" | "reviewing") => + make.pipe( + Effect.provide( + Layer.mock(GitHubPullRequestApi.GitHubPullRequestApi)({ + listPullRequests: () => + Effect.succeed({ items: [teamOnly], truncated: false, continues }), + }), + ), + Effect.flatMap((provider) => + provider.listChangeRequests({ + cwd: "/w", + host: "github.com", + repository: "acme/web", + state: "open", + involvement, + viewer: "Viewer", + limit: 50, + }), + ), + ); + const searched = yield* list(true, "reviewing"); + expect(searched.items[0]!.reviewRequestLogins).toEqual(["someone-else", "Viewer"]); + const all = yield* list(true, "all"); + expect(all.items[0]!.reviewRequestLogins).toEqual(["someone-else"]); + // The listing fallback keeps any team's request; it cannot say the team is the viewer's. + const listed = yield* list(false, "reviewing"); + expect(listed.items[0]!.reviewRequestLogins).toEqual(["someone-else"]); + }), + ); +}); + describe("listChangeRequestsAcross", () => { const searched = (repository: string): GitHubPullRequestSearchItem => ({ repository, @@ -1082,6 +1136,23 @@ describe("listChangeRequestsAcross", () => { }), ); + it.effect("counts a review requested from the viewer's team as requested from the viewer", () => + Effect.gen(function* () { + const teamOnly = { ...searched("acme/web"), hasTeamReviewRequest: true }; + const read = yield* providerAnswering({ + pages: [ + { items: [teamOnly], truncated: false }, + { items: [teamOnly], truncated: false }, + ], + covered: () => true, + }); + const reviewing = yield* read({ ...across, involvement: "reviewing" }); + expect(reviewing.items[0]!.reviewRequestLogins).toEqual(["viewer"]); + const all = yield* read(across); + expect(all.items[0]!.reviewRequestLogins).toEqual([]); + }), + ); + it.effect("past the first slice, believes a covered repository and not an uncovered one", () => Effect.gen(function* () { const read = yield* providerAnswering({ diff --git a/packages/source-control-github/src/server/GitHubPullRequestProvider.ts b/packages/source-control-github/src/server/GitHubPullRequestProvider.ts index 88dcc1aea2ed9..19e894eb308e0 100644 --- a/packages/source-control-github/src/server/GitHubPullRequestProvider.ts +++ b/packages/source-control-github/src/server/GitHubPullRequestProvider.ts @@ -32,6 +32,22 @@ import type { } from "./gitHubPullRequestJson.ts"; import { definition } from "../shared/definition.ts"; +/** + * `review-requested:` search rows include the viewer's team requests, which name no login, + * so record the viewer as requested. Search rows only: the listing fallback cannot tell whether the + * viewer belongs to a requested team. + */ +function withViewerRequested }>( + item: T, + input: { readonly involvement: string; readonly viewer: string }, +): T { + const viewer = input.viewer.toLowerCase(); + return input.involvement === "reviewing" && + !item.reviewRequestLogins.some((login) => login.toLowerCase() === viewer) + ? { ...item, reviewRequestLogins: [...item.reviewRequestLogins, input.viewer] } + : item; +} + const CAPABILITIES: PullRequestCapabilities = { diff: true, comment: true, @@ -434,7 +450,7 @@ export const make = Effect.gen(function* () { Effect.map((page) => ({ ...page, items: page.items.map((item) => ({ - ...item, + ...(page.continues ? withViewerRequested(item, input) : item), author: withAvatar(item.author, new Map(), input.host), })), })), @@ -460,7 +476,7 @@ export const make = Effect.gen(function* () { Effect.map(unresolvedBySearch(input, batch), (unresolved) => ({ truncated: batch.truncated, items: batch.items.map((item) => ({ - ...item, + ...withViewerRequested(item, input), author: withAvatar(item.author, new Map(), input.host), })), unresolved, From 172309c39c9525df0435141d74d4d9c0530b13e9 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 25 Nov 2026 06:42:13 -0800 Subject: [PATCH 037/238] fix(web): timeline minimap no longer covers the Copy button when the chat lane is shifted left (#42876) --- .../chat/MessagesTimeline.browser.test.tsx | 77 +++++++++++++++++++ .../chat/MessagesTimeline.logic.test.ts | 22 +++--- .../components/chat/MessagesTimeline.logic.ts | 22 ++---- .../src/components/chat/MessagesTimeline.tsx | 35 ++++----- 4 files changed, 110 insertions(+), 46 deletions(-) diff --git a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx index 45ba21665b2fe..b31558c2a38ba 100644 --- a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx @@ -737,6 +737,83 @@ describe("MessagesTimeline messages", () => { }); }); + it("keeps the minimap off the copy button when the chat lane is shifted left", async () => { + setup(); + const pageSize = { width: window.innerWidth, height: window.innerHeight }; + await page.viewport(1280, 800); + await using _pageSize = { + [Symbol.asyncDispose]: () => page.viewport(pageSize.width, pageSize.height), + }; + const props = baseProps(); + const entries = Array.from({ length: 6 }, (_, index) => [ + message(`Question ${index}`, {}, `user-${index}`), + message(`Answer ${index}`, { role: "assistant" }, `assistant-${index}`), + ]).flat(); + // ChatCanvas at 1024px with the details card open: a 48px left gutter, not a centered one. + await using screen = await renderElement( +

    + +
    , + ); + const viewport = props.listRef.current!.getScrollableNode()!; + const lane = screen.container.querySelector("[data-timeline-root]")!; + await vi.waitFor(() => { + expect(screen.container.querySelector("[data-minimap-strip]")).not.toBeNull(); + const laneRect = lane.getBoundingClientRect(); + const viewportRect = viewport.getBoundingClientRect(); + expect(laneRect.left - viewportRect.left).toBeLessThan(viewportRect.right - laneRect.right); + }); + + const jump = screen.buttons(/^Jump to message/)[0]!; + await vi.waitFor(() => + expect(jump.getBoundingClientRect().right).toBeLessThanOrEqual( + lane.getBoundingClientRect().left, + ), + ); + }); + + it("moves the minimap off the chat lane when the lane shifts left without resizing", async () => { + setup(); + const pageSize = { width: window.innerWidth, height: window.innerHeight }; + await page.viewport(1600, 800); + await using _pageSize = { + [Symbol.asyncDispose]: () => page.viewport(pageSize.width, pageSize.height), + }; + const props = baseProps(); + const entries = Array.from({ length: 6 }, (_, index) => [ + message(`Question ${index}`, {}, `user-${index}`), + message(`Answer ${index}`, { role: "assistant" }, `assistant-${index}`), + ]).flat(); + await using screen = await renderElement( +
    + +
    , + ); + const canvas = screen.container.querySelector("[data-chat-canvas]")!; + const lane = screen.container.querySelector("[data-timeline-root]")!; + await vi.waitFor(() => + expect(screen.container.querySelector("[data-minimap-strip]")).not.toBeNull(), + ); + const laneWidth = lane.getBoundingClientRect().width; + + // Opening the details card on a wide canvas moves the lane left at full width. + canvas.style.setProperty("--chat-lane-inset-end", "740px"); + const jump = screen.buttons(/^Jump to message/)[0]!; + await vi.waitFor(() => { + expect(lane.getBoundingClientRect().width).toBe(laneWidth); + expect(jump.getBoundingClientRect().right).toBeLessThanOrEqual( + lane.getBoundingClientRect().left, + ); + }); + }); + it("enables the minimap's next turn button on a thread restored above its bottom", async () => { setup(); const base = baseProps(); diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts index 3257f9588eeae..6330bb33c22fa 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts @@ -43,18 +43,16 @@ import { workEntryIconName } from "./TimelineWorkEntryRow.logic"; describe("resolveTimelineMinimapHitStrip", () => { it.each([ - { viewport: 1280, content: 768, left: 32, width: 40 }, - { viewport: 768, content: 672, left: 32, width: 16 }, - { viewport: 768, content: 704, left: 0, width: 8 }, - { viewport: 768, content: 720, left: 0, width: 8 }, - { viewport: 768, content: 756, left: 0, width: 6 }, - { viewport: 768, content: 768, left: 0, width: 0 }, - ])( - "keeps the minimap inside the gutter at $viewport/$content", - ({ viewport, content, left, width }) => { - expect(resolveTimelineMinimapHitStrip(viewport, content)).toEqual({ left, width }); - }, - ); + { gutter: 256, left: 32, width: 40 }, + { gutter: 48, left: 32, width: 16 }, + { gutter: 32, left: 0, width: 8 }, + { gutter: 24, left: 0, width: 8 }, + { gutter: 6, left: 0, width: 6 }, + { gutter: 0, left: 0, width: 0 }, + { gutter: -4, left: 0, width: 0 }, + ])("keeps the minimap inside a $gutter px gutter", ({ gutter, left, width }) => { + expect(resolveTimelineMinimapHitStrip(gutter)).toEqual({ left, width }); + }); }); describe("resolveAssistantMessageCopyState", () => { diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.ts b/apps/web/src/components/chat/MessagesTimeline.logic.ts index a7bca7de9f901..ae8ad90df43b9 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.ts @@ -464,28 +464,18 @@ export function resolveTimelineMinimapCurrentIndex(input: { return precedingIndex; } -function resolveTimelineSideGutter(viewportWidth: number, contentWidth: number): number { - if (!Number.isFinite(viewportWidth) || viewportWidth <= 0 || !Number.isFinite(contentWidth)) { - return 0; - } - return Math.max(0, (viewportWidth - Math.min(viewportWidth, contentWidth)) / 2); -} - -export function resolveTimelineMinimapHasPersistentGutter( - viewportWidth: number, - contentWidth: number, -): boolean { - return ( - resolveTimelineSideGutter(viewportWidth, contentWidth) >= TIMELINE_MINIMAP_PERSISTENT_GUTTER - ); +export function resolveTimelineMinimapHasPersistentGutter(sideGutter: number): boolean { + return sideGutter >= TIMELINE_MINIMAP_PERSISTENT_GUTTER; } const TIMELINE_MINIMAP_HIT_STRIP_LEFT = 32; const TIMELINE_MINIMAP_HIT_STRIP_MAX_WIDTH = 40; const TIMELINE_MINIMAP_NAVIGATION_REACH = 14; -export function resolveTimelineMinimapHitStrip(viewportWidth: number, contentWidth: number) { - const sideGutter = Math.floor(resolveTimelineSideGutter(viewportWidth, contentWidth)); +export function resolveTimelineMinimapHitStrip(measuredSideGutter: number) { + const sideGutter = Number.isFinite(measuredSideGutter) + ? Math.max(0, Math.floor(measuredSideGutter)) + : 0; if (sideGutter < TIMELINE_MINIMAP_HIT_STRIP_LEFT + TIMELINE_MINIMAP_NAVIGATION_REACH) { // Keep a hover target in the gutter, to the left of the sidebar restore handle. return { left: 0, width: Math.min(8, sideGutter) }; diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx index 1bd08298ec505..07e42d0a6542e 100644 --- a/apps/web/src/components/chat/MessagesTimeline.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.tsx @@ -1067,18 +1067,16 @@ const ConversationTimeline = memo(function ConversationTimeline({ }; const measureTimelineGutter = (viewportElement: HTMLElement) => { - const viewportWidth = viewportElement.getBoundingClientRect().width; - const contentWidth = - viewportElement.querySelector("[data-timeline-root]")?.getBoundingClientRect() - .width ?? viewportWidth; - const nextHasPersistentGutter = resolveTimelineMinimapHasPersistentGutter( - viewportWidth, - contentWidth, - ); + const lane = viewportElement.querySelector("[data-timeline-root]"); + // ChatCanvas can shift the lane off center, so measure the gutter the minimap sits in. + const sideGutter = lane + ? lane.getBoundingClientRect().left - viewportElement.getBoundingClientRect().left + : 0; + const nextHasPersistentGutter = resolveTimelineMinimapHasPersistentGutter(sideGutter); setMinimapHasPersistentGutter((current) => current === nextHasPersistentGutter ? current : nextHasPersistentGutter, ); - const nextHitStrip = resolveTimelineMinimapHitStrip(viewportWidth, contentWidth); + const nextHitStrip = resolveTimelineMinimapHitStrip(sideGutter); setMinimapHitStrip((current) => current.left === nextHitStrip.left && current.width === nextHitStrip.width ? current @@ -1095,16 +1093,17 @@ const ConversationTimeline = memo(function ConversationTimeline({ } handleScroll(); }); - // The content lane only changes width with the viewport or the chat width - // setting, never with streamed content; measuring per content frame would - // force a layout on every chunk. - const measuredLaneWidthRef = useRef(null); + // The content lane only moves or changes width with the viewport, the chat + // width setting or the canvas insets (which resize its row frame), never with + // streamed content; measuring per content frame would force a layout on every chunk. + const measuredLaneWidthRef = useRef(null); const observeLaneWidth = (lane: HTMLDivElement | null) => { - if (!lane) return; - return observeResize(lane, (entries) => { - const width = entries.at(-1)?.contentRect.width; - if (width === undefined || width === measuredLaneWidthRef.current) return; - measuredLaneWidthRef.current = width; + const frame = lane?.parentElement; + if (!lane || !frame) return; + return observeResize([frame, lane], () => { + const widths = `${frame.clientWidth}:${lane.clientWidth}`; + if (widths === measuredLaneWidthRef.current) return; + measuredLaneWidthRef.current = widths; const viewportElement = lane.closest("[data-assistant-citation-viewport]"); if (viewportElement) measureTimelineGutter(viewportElement); }); From 9de5a941eaa42914da08984220daaccb2d971ad2 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 25 Nov 2026 06:42:29 -0800 Subject: [PATCH 038/238] perf(web): Files panel Refresh reads only the folders on screen (#42870) --- .../files/FileBrowserPanel.browser.test.tsx | 8 +++ .../src/components/files/FileBrowserPanel.tsx | 24 ++++++--- .../files/fileTreeExpansion.test.ts | 10 ++++ .../src/components/files/fileTreeExpansion.ts | 16 +++++- .../useDirectoryEntries.browser.test.tsx | 42 +++++++++++++++- .../components/files/useDirectoryEntries.ts | 49 ++++++++++++++++--- 6 files changed, 131 insertions(+), 18 deletions(-) create mode 100644 apps/web/src/components/files/fileTreeExpansion.test.ts diff --git a/apps/web/src/components/files/FileBrowserPanel.browser.test.tsx b/apps/web/src/components/files/FileBrowserPanel.browser.test.tsx index 2a1f16b31070b..ecf51be124491 100644 --- a/apps/web/src/components/files/FileBrowserPanel.browser.test.tsx +++ b/apps/web/src/components/files/FileBrowserPanel.browser.test.tsx @@ -20,6 +20,7 @@ const directory: { entries: readonly ProjectEntry[]; load: () => Promise; refresh: () => void; + revalidate: (directoryPath: string) => void; ready: boolean; error: null; isPending: boolean; @@ -28,6 +29,7 @@ const directory: { entries, load: () => Promise.resolve(), refresh: () => {}, + revalidate: () => {}, ready: true, error: null, isPending: false, @@ -365,9 +367,15 @@ describe("FileBrowserPanel", () => { ); } + using revalidate = vi.spyOn(directory, "revalidate"); await using _second = await render(panel()); await vi.waitFor(() => expect(findTreeRow("src/")).not.toBeNull()); await vi.waitFor(() => expect(findTreeRow("src/")!.getAttribute("aria-expanded")).toBe("true")); + + // Refresh revalidates the folders behind the rows on screen: the open one and the root. + revalidate.mockClear(); + await userEvent.click(page.getByRole("button", { name: "Refresh workspace files" })); + expect(revalidate.mock.calls).toEqual([["src"], [""]]); }); describe("revealing a folder while folders above it are still loading", () => { const roots = Array.from({ length: 12 }, (_, index): ProjectEntry => { diff --git a/apps/web/src/components/files/FileBrowserPanel.tsx b/apps/web/src/components/files/FileBrowserPanel.tsx index 4609a8bacd089..03c6d30972b34 100644 --- a/apps/web/src/components/files/FileBrowserPanel.tsx +++ b/apps/web/src/components/files/FileBrowserPanel.tsx @@ -188,6 +188,7 @@ export default function FileBrowserPanel({ entries: directoryEntries, load, refresh, + revalidate, ready, error, isPending, @@ -300,6 +301,7 @@ export default function FileBrowserPanel({ ); const loadingDirectoriesRef = useRef(loadingDirectories); + const revalidateDirectory = useStableCallback(revalidate); const dragMention = createFileTreeDragMentionController( hostFolder ? { mentionPath: (path: string) => joinHostPath(cwd, path) } : {}, ); @@ -332,12 +334,15 @@ export default function FileBrowserPanel({ } }, paths: [], - renderRowDecoration: ({ item, row }) => - row.kind === "directory" && - row.isExpanded && - loadingDirectoriesRef.current.has(item.path.replace(/\/$/, "")) + renderRowDecoration: ({ item, row }) => { + const path = item.path.replace(/\/$/, ""); + const open = row.kind === "directory" && row.isExpanded; + // Pierre calls this for the rows it renders, which is the only sign of what is on screen. + revalidateDirectory(open ? path : path.slice(0, Math.max(0, path.lastIndexOf("/")))); + return open && loadingDirectoriesRef.current.has(path) ? { icon: "t3-tree-icon-loading", title: gt("Loading…") } - : null, + : null; + }, search: false, onSearchChange: (value) => setQuery(value ?? ""), unsafeCSS: PIERRE_TREE_UNSAFE_CSS, @@ -452,15 +457,20 @@ export default function FileBrowserPanel({ } search.setValue(value); }; - const handleRefresh = () => { + const refreshDirectories = () => { refresh(); + // Renders the rows again, so each one on screen revalidates the folders it comes from. + model.setComposition(model.getComposition()); + }; + const handleRefresh = () => { + refreshDirectories(); if (query.trim()) pathSearch.refresh(); onRefreshSelectedFile?.(); }; useWorkspaceMutationRefresh({ mutationId: workspaceMutationId, refresh: () => { - refresh(); + refreshDirectories(); if (query.trim()) pathSearch.refresh(); }, resourceKey: `files:${environmentId}:${cwd}`, diff --git a/apps/web/src/components/files/fileTreeExpansion.test.ts b/apps/web/src/components/files/fileTreeExpansion.test.ts new file mode 100644 index 0000000000000..6d8ea1a883b9a --- /dev/null +++ b/apps/web/src/components/files/fileTreeExpansion.test.ts @@ -0,0 +1,10 @@ +import { expect, it } from "vite-plus/test"; + +import { readExpandedDirectories, writeExpandedDirectories } from "./fileTreeExpansion"; + +it("keeps the 100 expanded folders nearest the root, so a remount does not list hundreds", () => { + const deep = Array.from({ length: 150 }, (_, index) => `pkg/mod/d${index}/`); + writeExpandedDirectories("env:/repo", [...deep, "pkg/mod/", "pkg/"]); + const restored = readExpandedDirectories("env:/repo"); + expect(restored).toEqual(["pkg/", "pkg/mod/", ...deep.slice(0, 98)]); +}); diff --git a/apps/web/src/components/files/fileTreeExpansion.ts b/apps/web/src/components/files/fileTreeExpansion.ts index 35e6a548603ee..f7055bd1e1b08 100644 --- a/apps/web/src/components/files/fileTreeExpansion.ts +++ b/apps/web/src/components/files/fileTreeExpansion.ts @@ -106,6 +106,8 @@ export function coalesceReentrantCalls(run: () => void): () => void { const EXPANDED_DIRECTORIES_STORAGE_KEY = "t3code.fileTreeExpandedDirectories"; // Roots are kept most recent first and capped so worktrees that come and go do not grow storage. const MAX_STORED_ROOTS = 20; +// Every restored folder is listed when the panel mounts, so a root keeps the folders nearest it. +const MAX_STORED_PATHS_PER_ROOT = 100; const StoredExpandedDirectories = Schema.Array( Schema.Struct({ root: Schema.String, paths: Schema.Array(Schema.String) }), ); @@ -119,13 +121,23 @@ function readStoredExpandedDirectories() { } } +function nearestToRoot(paths: readonly string[]): readonly string[] { + if (paths.length <= MAX_STORED_PATHS_PER_ROOT) return paths; + const depth = (path: string) => path.split("/").length; + return paths + .toSorted((left, right) => depth(left) - depth(right)) + .slice(0, MAX_STORED_PATHS_PER_ROOT); +} + export function readExpandedDirectories(root: string): readonly string[] { - return readStoredExpandedDirectories().find((entry) => entry.root === root)?.paths ?? []; + return nearestToRoot( + readStoredExpandedDirectories().find((entry) => entry.root === root)?.paths ?? [], + ); } export function writeExpandedDirectories(root: string, paths: readonly string[]): void { const others = readStoredExpandedDirectories().filter((entry) => entry.root !== root); - const next = paths.length > 0 ? [{ root, paths }, ...others] : others; + const next = paths.length > 0 ? [{ root, paths: nearestToRoot(paths) }, ...others] : others; try { setLocalStorageItem( EXPANDED_DIRECTORIES_STORAGE_KEY, diff --git a/apps/web/src/components/files/useDirectoryEntries.browser.test.tsx b/apps/web/src/components/files/useDirectoryEntries.browser.test.tsx index 694004d0a044d..cee9a88148050 100644 --- a/apps/web/src/components/files/useDirectoryEntries.browser.test.tsx +++ b/apps/web/src/components/files/useDirectoryEntries.browser.test.tsx @@ -188,11 +188,15 @@ it("retains the four-query concurrency bound across directories and refreshes", expect(state.activeQueries).toBe(0); const refreshStart = state.calls.length; state.resetPeakQueries(); - await act(async () => state.view.refresh()); + const refreshOnScreen = () => { + state.view.refresh(); + for (const folder of folders) state.view.revalidate(folder.path); + }; + await act(async () => refreshOnScreen()); expect(state.peakQueries).toBe(4); expect(state.activeQueries).toBe(4); await act(async () => { - for (let index = 0; index < 20; index++) state.view.refresh(); + for (let index = 0; index < 20; index++) refreshOnScreen(); }); for (let index = refreshStart; index < state.calls.length; index++) { await state.settle(index, state.calls[index]!.path === "" ? folders : []); @@ -206,6 +210,40 @@ it("retains the four-query concurrency bound across directories and refreshes", expect(state.view.isPending).toBe(false); }); +it("refreshes the root, and another folder only once one of its rows is on screen", async () => { + const state = setup(); + // The hook probe does not navigate. + await using _screen = await render(, { router: false }); + const folders = ["src", "src/ui", "docs"].map((path) => ({ path, kind: "directory" as const })); + const listing = (path: string) => + folders.filter((folder) => folder.path.slice(0, folder.path.lastIndexOf("/") + 1) === path); + await state.settle(0, listing("")); + await act(async () => { + for (const folder of folders) void state.view.load(folder.path); + }); + await state.settle(1, listing("src/")); + await state.settle(2); + await state.settle(3); + + await act(async () => { + state.view.refresh(); + state.view.refresh(); + }); + expect(state.calls.slice(4).map((call) => call.path)).toEqual([""]); + await act(async () => { + state.view.revalidate("src/ui"); + state.view.revalidate("src/ui"); + }); + expect(state.calls.slice(4).map((call) => call.path)).toEqual(["", "src/ui", "src"]); + await state.settle(4, listing("")); + await state.settle(5); + await state.settle(6, listing("src/")); + await state.settle(7, listing("")); + expect(state.calls).toHaveLength(8); // The second refresh reads the root once more; `docs` is never read. + expect(state.view.entries.map((entry) => entry.path)).toEqual(["src", "src/ui", "docs"]); + expect(state.view.isPending).toBe(false); +}); + it("does not start a queued follow-up after unmount", async () => { const state = setup(); // The hook probe does not navigate. diff --git a/apps/web/src/components/files/useDirectoryEntries.ts b/apps/web/src/components/files/useDirectoryEntries.ts index fc3a984c4788a..ce210315d073c 100644 --- a/apps/web/src/components/files/useDirectoryEntries.ts +++ b/apps/web/src/components/files/useDirectoryEntries.ts @@ -25,6 +25,8 @@ export function useDirectoryEntries(environmentId: EnvironmentId, cwd: string) { const followUpRefreshes = useRef(new Map>()); const loaded = useRef(new Set()); const requested = useRef(new Set()); + // Listed folders a refresh has not read again yet. `revalidate` reads one once it is on screen. + const stale = useRef(new Set()); const active = useRef(true); const running = useRef(0); const waiting = useRef void>>([]); @@ -32,6 +34,7 @@ export function useDirectoryEntries(environmentId: EnvironmentId, cwd: string) { const startRequest = (directoryPath: string, refresh: boolean): Promise => { loaded.current.add(directoryPath); requested.current.add(directoryPath); + stale.current.delete(directoryPath); const atom = projectEnvironment.listEntries({ environmentId, input: { cwd, directoryPath } }); const detached = detachedRequests.current.get(directoryPath); const request = (async () => { @@ -59,6 +62,7 @@ export function useDirectoryEntries(environmentId: EnvironmentId, cwd: string) { (entry) => entry.path.slice(0, Math.max(0, entry.path.lastIndexOf("/"))) === directoryPath, ); + const listed = listings.current.get(directoryPath); const next = new Map(listings.current).set(directoryPath, children); const childDirectories = new Set( children.filter((entry) => entry.kind === "directory").map((entry) => entry.path), @@ -73,13 +77,28 @@ export function useDirectoryEntries(environmentId: EnvironmentId, cwd: string) { next.delete(path); loaded.current.delete(path); requested.current.delete(path); + stale.current.delete(path); const detachedRequest = requests.current.get(path); if (detachedRequest) detachedRequests.current.set(path, detachedRequest); requests.current.delete(path); followUpRefreshes.current.delete(path); } - listings.current = next; - setDirectories(next); + // A refresh that finds a folder as it was publishes nothing, so the tree is not rebuilt. + const unchanged = + removed.length === 0 && + listed?.length === children.length && + children.every((entry, index) => { + const known = listed[index]!; + return ( + entry.path === known.path && + entry.kind === known.kind && + entry.ignored === known.ignored + ); + }); + if (!unchanged) { + listings.current = next; + setDirectories(next); + } if (removed.length > 0) setLoadingDirectories((previous) => { const remaining = new Set(previous); @@ -87,8 +106,10 @@ export function useDirectoryEntries(environmentId: EnvironmentId, cwd: string) { return remaining; }); setErrors((previous) => { + const cleared = [directoryPath, ...removed].filter((path) => previous.has(path)); + if (cleared.length === 0) return previous; const remaining = new Map(previous); - for (const path of [directoryPath, ...removed]) remaining.delete(path); + for (const path of cleared) remaining.delete(path); return remaining; }); } else { @@ -174,11 +195,24 @@ export function useDirectoryEntries(environmentId: EnvironmentId, cwd: string) { ...entries.filter((entry) => entry.kind === "directory").map((entry) => entry.path), ]); + // Reads the root again and leaves every other listed folder to `revalidate`, so a refresh costs + // what is on screen rather than every folder the tree has listed. const refresh = () => { - const paths = [...requested.current].filter((path) => reachableDirectories.has(path)); - for (const path of paths) { - if (!active.current) break; - void load(path, true); + if (!active.current) return; + for (const path of requested.current) if (path !== "") stale.current.add(path); + void load("", true); + }; + + /** Reads again the stale listings that put a row on screen: `directoryPath` and its ancestors. */ + const revalidate = (directoryPath: string) => { + if (!active.current) return; + for ( + let end = directoryPath.length; + end > 0 && stale.current.size > 0; + end = directoryPath.lastIndexOf("/", end - 1) + ) { + const path = directoryPath.slice(0, end); + if (stale.current.delete(path)) void load(path, true); } }; @@ -186,6 +220,7 @@ export function useDirectoryEntries(environmentId: EnvironmentId, cwd: string) { entries, load, refresh, + revalidate, isPending: pending > 0, loadingDirectories, ready: directories.has(""), From 8783b9d2eaaf102dfd7374eef2ecc75c4b754907 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 25 Nov 2026 06:45:53 -0800 Subject: [PATCH 039/238] fix(web): Restart agent session toast says the conversation is kept (#42880) --- apps/web/src/components/CommandPalette.tsx | 2 +- apps/web/src/i18n/translations/de.json | 2 +- apps/web/src/i18n/translations/en.json | 2 +- apps/web/src/i18n/translations/es.json | 2 +- apps/web/src/i18n/translations/fr.json | 2 +- apps/web/src/i18n/translations/ja.json | 2 +- apps/web/src/i18n/translations/ko.json | 2 +- apps/web/src/i18n/translations/pt-BR.json | 2 +- apps/web/src/i18n/translations/ru.json | 2 +- apps/web/src/i18n/translations/sv.json | 2 +- apps/web/src/i18n/translations/zh.json | 2 +- 11 files changed, 11 insertions(+), 11 deletions(-) diff --git a/apps/web/src/components/CommandPalette.tsx b/apps/web/src/components/CommandPalette.tsx index cf8edc293b7b0..745b96bcdb549 100644 --- a/apps/web/src/components/CommandPalette.tsx +++ b/apps/web/src/components/CommandPalette.tsx @@ -1580,7 +1580,7 @@ function OpenCommandPaletteDialog(props: { toastManager.add({ type: "success", title: gt("Agent session will restart"), - description: gt("Your next message starts a fresh session."), + description: gt("Your next message restarts the agent. This conversation is kept."), }); const project = projectByKey.get(`${environmentId}:${thread.projectId}`); if (!project) return; diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 2f8bb9a78f29e..13ca3148353ec 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -1855,7 +1855,7 @@ "67f5b13c3c7bcd40": "Mit Gast teilen", "82da5b8b340217ac": "Agentensitzung neu starten", "963d099509eabcd6": "Die Agentensitzung wird neu gestartet", - "1d384d4fe7888a09": "Deine nächste Nachricht startet eine neue Sitzung.", + "71ed7c0da0b93c77": "Deine nächste Nachricht startet den Agenten neu. Diese Unterhaltung bleibt erhalten.", "e4b61c891fed297e": "Gehe zu Datei", "d2ccdb8cd3297212": "Projekt hinzufügen", "594bcbef04093f72": "WSL-Ordner öffnen", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index 344891fe62609..373a74dcb3037 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -1856,7 +1856,7 @@ "67f5b13c3c7bcd40": "Share with guest", "82da5b8b340217ac": "Restart agent session", "963d099509eabcd6": "Agent session will restart", - "1d384d4fe7888a09": "Your next message starts a fresh session.", + "71ed7c0da0b93c77": "Your next message restarts the agent. This conversation is kept.", "e4b61c891fed297e": "Go to file", "d2ccdb8cd3297212": "Add project", "594bcbef04093f72": "Open WSL folder", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index 38ae9dc156ebc..907459e4af8cf 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -1856,7 +1856,7 @@ "67f5b13c3c7bcd40": "Compartir con un invitado", "82da5b8b340217ac": "Reiniciar sesión del agente", "963d099509eabcd6": "La sesión del agente se reiniciará", - "1d384d4fe7888a09": "Tu próximo mensaje inicia una sesión nueva.", + "71ed7c0da0b93c77": "Tu próximo mensaje reinicia el agente. Esta conversación se conserva.", "e4b61c891fed297e": "Ir al archivo", "d2ccdb8cd3297212": "Añadir proyecto", "594bcbef04093f72": "Abrir carpeta de WSL", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index 57cc6f526c041..8b299a8bb964e 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -1856,7 +1856,7 @@ "67f5b13c3c7bcd40": "Partager avec un invité", "82da5b8b340217ac": "Redémarrer la session de l’agent", "963d099509eabcd6": "La session de l’agent va redémarrer", - "1d384d4fe7888a09": "Votre prochain message démarre une nouvelle session.", + "71ed7c0da0b93c77": "Votre prochain message redémarre l’agent. Cette conversation est conservée.", "e4b61c891fed297e": "Aller au fichier", "d2ccdb8cd3297212": "Ajouter un projet", "594bcbef04093f72": "Ouvrir un dossier WSL", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index 5a48ea70d7abc..969229a89006d 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -1855,7 +1855,7 @@ "67f5b13c3c7bcd40": "ゲストと共有", "82da5b8b340217ac": "エージェントのセッションを再起動", "963d099509eabcd6": "エージェントのセッションが再起動されます", - "1d384d4fe7888a09": "次のメッセージで新しいセッションが始まります。", + "71ed7c0da0b93c77": "次のメッセージでエージェントが再起動します。この会話はそのまま残ります。", "e4b61c891fed297e": "ファイルに移動", "d2ccdb8cd3297212": "プロジェクトを追加", "594bcbef04093f72": "WSL のフォルダーを開く", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index bdec1db133159..85d3f4d351ad7 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -1855,7 +1855,7 @@ "67f5b13c3c7bcd40": "게스트와 공유", "82da5b8b340217ac": "에이전트 세션 다시 시작", "963d099509eabcd6": "에이전트 세션이 다시 시작됩니다", - "1d384d4fe7888a09": "다음 메시지부터 새 세션이 시작됩니다.", + "71ed7c0da0b93c77": "다음 메시지를 보내면 에이전트가 다시 시작됩니다. 이 대화는 유지됩니다.", "e4b61c891fed297e": "파일로 이동", "d2ccdb8cd3297212": "프로젝트 추가", "594bcbef04093f72": "WSL 폴더 열기", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index 20baf91f8b106..9819cb6981ca0 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -1856,7 +1856,7 @@ "67f5b13c3c7bcd40": "Compartilhar com convidado", "82da5b8b340217ac": "Reiniciar a sessão do agente", "963d099509eabcd6": "A sessão do agente será reiniciada", - "1d384d4fe7888a09": "Sua próxima mensagem inicia uma nova sessão.", + "71ed7c0da0b93c77": "Sua próxima mensagem reinicia o agente. Esta conversa é mantida.", "e4b61c891fed297e": "Ir para arquivo", "d2ccdb8cd3297212": "Adicionar projeto", "594bcbef04093f72": "Abrir pasta do WSL", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 1f58942bc5cfc..4b1d3c7a46f54 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -1856,7 +1856,7 @@ "67f5b13c3c7bcd40": "Поделиться с гостем", "82da5b8b340217ac": "Перезапустить сеанс агента", "963d099509eabcd6": "Сеанс агента будет перезапущен", - "1d384d4fe7888a09": "Следующее сообщение начнёт новый сеанс.", + "71ed7c0da0b93c77": "Следующее сообщение перезапустит агента. Эта беседа сохранится.", "e4b61c891fed297e": "Перейти к файлу", "d2ccdb8cd3297212": "Добавить проект", "594bcbef04093f72": "Открыть папку WSL", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index c7370bb2ec772..734f2a2cdee3f 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -1856,7 +1856,7 @@ "67f5b13c3c7bcd40": "Dela med gäst", "82da5b8b340217ac": "Starta om agentsessionen", "963d099509eabcd6": "Agentsessionen startas om", - "1d384d4fe7888a09": "Ditt nästa meddelande startar en ny session.", + "71ed7c0da0b93c77": "Ditt nästa meddelande startar om agenten. Den här konversationen behålls.", "e4b61c891fed297e": "Gå till fil", "d2ccdb8cd3297212": "Lägg till projekt", "594bcbef04093f72": "Öppna WSL-mapp", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index 98276b6809237..c8c51048fd5e2 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -1856,7 +1856,7 @@ "67f5b13c3c7bcd40": "与访客共享", "82da5b8b340217ac": "重启智能体会话", "963d099509eabcd6": "智能体会话将重启", - "1d384d4fe7888a09": "你的下一条消息将以全新上下文开始。", + "71ed7c0da0b93c77": "你的下一条消息将重启智能体,当前对话会保留。", "e4b61c891fed297e": "转到文件", "d2ccdb8cd3297212": "添加项目", "594bcbef04093f72": "打开 WSL 文件夹", From 9301770ae9e595a65e23d83702b86121c380e919 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 25 Nov 2026 06:46:10 -0800 Subject: [PATCH 040/238] fix(mobile): / menu ranks an exact skill name above description matches (#42879) --- .../threads/composerSlashSkillSearch.ts | 47 ++++++++++++++++--- .../use-composer-command-menu.select.test.tsx | 43 +++++++++++++++++ .../threads/use-composer-command-menu.ts | 10 ++-- 3 files changed, 91 insertions(+), 9 deletions(-) diff --git a/apps/mobile/src/features/threads/composerSlashSkillSearch.ts b/apps/mobile/src/features/threads/composerSlashSkillSearch.ts index 7cd81f036fdd4..ed6ff7ae909ec 100644 --- a/apps/mobile/src/features/threads/composerSlashSkillSearch.ts +++ b/apps/mobile/src/features/threads/composerSlashSkillSearch.ts @@ -1,7 +1,9 @@ import type { ServerProviderSkill } from "@t3tools/contracts"; +import { scoreQueryMatch } from "@t3tools/shared/searchRanking"; -export function matchesSlashSkillQuery(skill: ServerProviderSkill, query: string): boolean { - if (!skill.enabled) return false; +/** Lower is better; `null` when the skill does not match. */ +export function scoreSlashSkillQuery(skill: ServerProviderSkill, query: string): number | null { + if (!skill.enabled) return null; const normalizedQuery = query.toLowerCase(); const skillQuery = normalizedQuery === "skill" @@ -9,8 +11,41 @@ export function matchesSlashSkillQuery(skill: ServerProviderSkill, query: string : normalizedQuery.startsWith("skill:") ? normalizedQuery.slice("skill:".length) : normalizedQuery; - if (!skillQuery) return true; - return [skill.name, skill.displayName, skill.shortDescription, skill.description].some((value) => - value?.toLowerCase().includes(skillQuery), - ); + if (!skillQuery) return 0; + const scores = [ + scoreQueryMatch({ + value: skill.name.toLowerCase(), + query: skillQuery, + exactBase: 0, + prefixBase: 2, + boundaryBase: 4, + includesBase: 6, + boundaryMarkers: ["-", "_", "/"], + }), + scoreQueryMatch({ + value: skill.displayName?.toLowerCase() ?? "", + query: skillQuery, + exactBase: 1, + prefixBase: 3, + boundaryBase: 5, + includesBase: 7, + }), + scoreQueryMatch({ + value: skill.shortDescription?.toLowerCase() ?? "", + query: skillQuery, + exactBase: 20, + prefixBase: 22, + boundaryBase: 24, + includesBase: 26, + }), + scoreQueryMatch({ + value: skill.description?.toLowerCase() ?? "", + query: skillQuery, + exactBase: 30, + prefixBase: 32, + boundaryBase: 34, + includesBase: 36, + }), + ].filter((score): score is number => score !== null); + return scores.length > 0 ? Math.min(...scores) : null; } diff --git a/apps/mobile/src/features/threads/use-composer-command-menu.select.test.tsx b/apps/mobile/src/features/threads/use-composer-command-menu.select.test.tsx index 395961bd91ec7..21e5a88f82fdb 100644 --- a/apps/mobile/src/features/threads/use-composer-command-menu.select.test.tsx +++ b/apps/mobile/src/features/threads/use-composer-command-menu.select.test.tsx @@ -53,3 +53,46 @@ it("/model clears only its trigger and opens the model picker", async () => { expect(onChangeDraftMessage).toHaveBeenCalledWith("fix this "); act(() => root.unmount()); }); + +it("/ ranks a skill whose name matches exactly above skills that only mention it", async () => { + (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + const skill = (name: string, description: string) => ({ + name, + description, + path: `/skills/${name}/SKILL.md`, + enabled: true, + }); + const provider = { + instanceId: "codex", + driver: "codex", + slashCommands: [], + skills: [ + skill("lint", "Run lint before review"), + skill("ship", "Open a pull request after review"), + skill("review", "Review the current diff"), + ], + } as unknown as NonNullable< + Parameters[0]["selectedProviderStatus"] + >; + let menu: ReturnType | undefined; + function Probe() { + menu = useComposerCommandMenu({ + draftMessage: "/review", + ownerKey: "draft", + environmentId: null, + projectCwd: null, + selectedProviderStatus: provider, + hasThread: true, + hasCompactableConversation: false, + onChangeDraftMessage: vi.fn(), + onOpenModelPicker: vi.fn(), + }); + return null; + } + + const root = createRoot(document.createElement("div")); + await act(async () => root.render()); + + expect(menu?.items[0]?.id).toBe("skill:review"); + act(() => root.unmount()); +}); diff --git a/apps/mobile/src/features/threads/use-composer-command-menu.ts b/apps/mobile/src/features/threads/use-composer-command-menu.ts index b5b6ce681c018..3fa3e9d8860b0 100644 --- a/apps/mobile/src/features/threads/use-composer-command-menu.ts +++ b/apps/mobile/src/features/threads/use-composer-command-menu.ts @@ -68,7 +68,7 @@ import { import type { ModelOption } from "../../lib/modelOptions"; import { m, type MessageResolver } from "../../i18n/messages"; import type { ComposerCommandItem } from "./ComposerCommandPopover"; -import { matchesSlashSkillQuery } from "./composerSlashSkillSearch"; +import { scoreSlashSkillQuery } from "./composerSlashSkillSearch"; const idleWorkspaceSnapshotRefreshAtom: Atom.Atom = Atom.make(undefined).pipe( Atom.withLabel("mobile:provider-workspace-snapshot-refresh:idle"), @@ -422,8 +422,12 @@ export function useComposerCommandMenu({ ); const skillItems = visibleSkills - .filter((skill) => matchesSlashSkillQuery(skill, q)) - .map((skill) => ({ + .flatMap((skill) => { + const score = scoreSlashSkillQuery(skill, q); + return score === null ? [] : [{ skill, score }]; + }) + .sort((left, right) => left.score - right.score) + .map(({ skill }) => ({ id: `skill:${skill.name}`, type: "skill" as const, skill, From 80cac28f5ad31fbf7e3d07dcfacf023b0d38a96d Mon Sep 17 00:00:00 2001 From: Victor Date: Wed, 25 Nov 2026 08:50:57 -0600 Subject: [PATCH 041/238] fix(server): EPUB attachment text no longer includes hidden passages (#42871) Co-authored-by: Julius Marminge --- apps/server/src/provider/documentTextWorker.ts | 6 +++++- .../src/provider/userInputAttachments.test.ts | 16 +++++++++++++--- 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/apps/server/src/provider/documentTextWorker.ts b/apps/server/src/provider/documentTextWorker.ts index 230e5d22c144c..4c4504a8b6024 100644 --- a/apps/server/src/provider/documentTextWorker.ts +++ b/apps/server/src/provider/documentTextWorker.ts @@ -110,11 +110,15 @@ function xml(source: string, extension: string): XmlNode { stack.at(-1)!.children.push(node); stack.push(node); }); - parser.on("closetag", () => { + parser.on("closetag", (tag) => { const node = stack.pop()!; const parent = stack.at(-1)!; if (odf && (node.name === "p" || node.name === "h")) collapseOdfWhitespace(node); if ( + (extension === ".epub" && + (stack[1] ?? node).name === "html" && + Object.hasOwn(tag.attributes, "hidden") && + !/^until-found$/i.test(String(tag.attributes.hidden))) || (extension === ".docx" && node.name === "del") || (extension === ".docx" && node.name === "r" && diff --git a/apps/server/src/provider/userInputAttachments.test.ts b/apps/server/src/provider/userInputAttachments.test.ts index 6aad293a35ec9..ea61fab1ce990 100644 --- a/apps/server/src/provider/userInputAttachments.test.ts +++ b/apps/server/src/provider/userInputAttachments.test.ts @@ -1493,11 +1493,12 @@ describe("question answer paths", () => { "META-INF/container.xml": '', "OEBPS/book.opf": - '', + '', "OEBPS/a.xhtml": '

    Last chapter

    Price 10 8 old

    ', "OEBPS/b.xhtml": - 'My Novel

    First chapter

    Larkspur

    Direct div
    Direct section
  • Direct item emphasis trailing
  • Account: A
    Balance: 731Currency: USD
    HeadingTotal
    Important value731
    Before
    Inner
    After
    Neighbor
    Port
    443
    Timeout
    30 seconds
    ', + 'My Novel

    First chapter

    Larkspur

    Direct div
    Direct section
  • Direct item emphasis trailing
  • Account: A
    Balance: 731Currency: USD
    HeadingTotal
    Important value731
    Before
    Inner
    After
    Neighbor
    Port
    443
    Timeout
    30 seconds

    Prefixed note

    ', + "OEBPS/c.xhtml": '

    Root hidden

    ', }, expected: [ "## Chapter 1", @@ -1511,11 +1512,20 @@ describe("question answer paths", () => { "Important value\t731", "Before Inner After\tNeighbor", "Port\n443\nTimeout\n30 seconds", + "Findable note\nDecorative note\nPrefixed note", "## Chapter 2", "Last chapter", "Price 10 8 old", + "## Chapter 3", + ], + absent: [ + "My Novel", + "Hidden Author", + "Draft note", + "Hidden block", + "Hidden nested", + "Root hidden", ], - absent: ["My Novel", "Hidden Author"], }, ]; for (const [caseIndex, item] of cases.entries()) { From 45c011e218dccbb8d02c5408d00c6011ee07b9ec Mon Sep 17 00:00:00 2001 From: AymanKhan9 Date: Wed, 25 Nov 2026 20:21:10 +0530 Subject: [PATCH 042/238] fix(web): reopening a closed pull request tab keeps saved list filters (#42875) Co-authored-by: Julius Marminge --- .../ReopenClosedViewShortcut.browser.test.tsx | 63 +++++++++++++++++++ .../components/ReopenClosedViewShortcut.tsx | 3 +- apps/web/src/reopenClosedView.ts | 48 ++++---------- 3 files changed, 78 insertions(+), 36 deletions(-) diff --git a/apps/web/src/components/ReopenClosedViewShortcut.browser.test.tsx b/apps/web/src/components/ReopenClosedViewShortcut.browser.test.tsx index 3298af7822c89..a7b2d712239db 100644 --- a/apps/web/src/components/ReopenClosedViewShortcut.browser.test.tsx +++ b/apps/web/src/components/ReopenClosedViewShortcut.browser.test.tsx @@ -85,10 +85,12 @@ vi.mock(import("./ui/toast"), async (original) => { import { useClosedViewStore } from "../closedViewStore"; import { ISSUES_PANEL_REF, + PULL_REQUESTS_PANEL_REF, selectThreadRightPanelState, useRightPanelStore, } from "../rightPanelStore"; import { useTerminalUiStateStore } from "../terminalUiStateStore"; +import { writePullRequestListPreferences } from "./pullRequest/pullRequestListPreferences"; import { ReopenClosedViewShortcut } from "./ReopenClosedViewShortcut"; const ref = { environmentId: "remote", threadId: "thread-1" } as ScopedThreadRef; @@ -400,6 +402,67 @@ describe("root reopen shortcut", () => { ); }); + it("reopens a closed pull request tab from another route with saved list preferences and no foreign search params", async () => { + setup(); + window.localStorage.removeItem("t3.pullRequests.preferences"); + using _cleanup = { + [Symbol.dispose]: () => window.localStorage.removeItem("t3.pullRequests.preferences"), + }; + writePullRequestListPreferences({ involvement: "reviewing", state: "merged" }); + useClosedViewStore.getState().remember({ + kind: "panel-tab", + threadRef: PULL_REQUESTS_PANEL_REF, + surface: { + id: "pull-request:remote:project-1:github.com:pingdotgg/t3code#42", + kind: "pull-request", + environmentId: "remote", + projectId: "project-1", + host: "github.com", + repository: "pingdotgg/t3code", + number: 42, + }, + }); + + const history = createMemoryHistory({ + initialEntries: [ + "/issues?who=assigned&status=closed&q=login&host=linear.app&tracker=linear&scope=ENG&key=ENG-12", + ], + }); + const root = createRootRoute({ + component: () => ( + <> + + + + ), + }); + const router = createRouter({ + history, + routeTree: root.addChildren([ + createRoute({ getParentRoute: () => root, path: "issues" }), + createRoute({ getParentRoute: () => root, path: "pull-requests" }), + ]), + }); + state.navigate.mockImplementation(router.navigate); + using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("Linux x86_64"); + await using _view = await render(, { router: false }); + + await act(() => { + press(); + }); + + expect(router.state.location.pathname).toBe("/pull-requests"); + expect(router.state.location.search).toEqual({ + involvement: "reviewing", + state: "merged", + repository: "pingdotgg/t3code", + number: 42, + selectedProjectId: "project-1", + selectedHost: "github.com", + selectedEnvironmentId: "remote", + }); + }); + it("forwards address-bar focus, zoom, and panel new and close from a focused desktop page", async () => { setup(); await using _shortcut = await renderShortcut(); diff --git a/apps/web/src/components/ReopenClosedViewShortcut.tsx b/apps/web/src/components/ReopenClosedViewShortcut.tsx index 7fa558148e611..40b5d40b44cce 100644 --- a/apps/web/src/components/ReopenClosedViewShortcut.tsx +++ b/apps/web/src/components/ReopenClosedViewShortcut.tsx @@ -49,6 +49,7 @@ import { } from "../threadRoutes"; import { toastManager } from "./ui/toast"; import { readIssueListPreferences } from "./issue/issueListPreferences"; +import { readPullRequestListPreferences } from "./pullRequest/pullRequestListPreferences"; declare module "@tanstack/react-router" { interface HistoryState { @@ -163,7 +164,7 @@ export function ReopenClosedViewShortcut() { destination = globalPullRequests ? linkOptions({ to: "/pull-requests", - search: (previous) => pullRequestsSearchForRestore(previous, selected), + search: pullRequestsSearchForRestore(readPullRequestListPreferences(), selected), }) : linkOptions({ to: "/issues", diff --git a/apps/web/src/reopenClosedView.ts b/apps/web/src/reopenClosedView.ts index 69cedab7cbf80..96d263050fa1a 100644 --- a/apps/web/src/reopenClosedView.ts +++ b/apps/web/src/reopenClosedView.ts @@ -2,7 +2,6 @@ import type { EnvironmentId, ProjectId } from "@t3tools/contracts"; import type { OpenPreviewMutation } from "./browser/openFileInPreview"; import type { ClosedView, ClosedViewEntry } from "./closedViewStore"; -import type { PullRequestListPreferences } from "./components/pullRequest/pullRequestListPreferences"; import { openPreviewSession } from "./components/preview/openPreviewSession"; import { rightPanelHostRef, @@ -53,42 +52,21 @@ export function planNextReopen( return { drop, restore: null }; } -type PullRequestsSearchLike = Partial & { - repository?: string; - number?: number; - selectedProjectId?: ProjectId | undefined; - selectedHost?: string | undefined; - selectedEnvironmentId?: EnvironmentId | undefined; -}; - -export function pullRequestsSearchForRestore( - previous: S, +export function pullRequestsSearchForRestore( + preferences: S, selected: RightPanelSurface | null, -): S & PullRequestListPreferences { - const { - repository: _repository, - number: _number, - selectedProjectId: _projectId, - selectedHost: _host, - selectedEnvironmentId: _environmentId, - ...filters - } = previous; +) { + if (selected?.kind !== "pull-request") return preferences; return { - ...filters, - involvement: previous.involvement ?? "all", - state: previous.state ?? "open", - ...(selected?.kind === "pull-request" - ? { - repository: selected.repository, - number: selected.number, - selectedProjectId: selected.projectId as ProjectId, - ...(selected.host === undefined ? {} : { selectedHost: selected.host }), - ...(selected.environmentId === undefined - ? {} - : { selectedEnvironmentId: selected.environmentId as EnvironmentId }), - } - : {}), - } as S & PullRequestListPreferences; + ...preferences, + repository: selected.repository, + number: selected.number, + selectedProjectId: selected.projectId as ProjectId, + ...(selected.host === undefined ? {} : { selectedHost: selected.host }), + ...(selected.environmentId === undefined + ? {} + : { selectedEnvironmentId: selected.environmentId as EnvironmentId }), + }; } export function issuesSearchForRestore( From b61af8a5d2af5e514674bd85fe5a62e4ea8f9918 Mon Sep 17 00:00:00 2001 From: Victor Date: Wed, 25 Nov 2026 08:51:24 -0600 Subject: [PATCH 043/238] fix(web,mobile): mixed add/delete review selections no longer show backwards line ranges (#42863) Co-authored-by: Julius Marminge --- .../review/ReviewCommentComposerSheet.tsx | 2 +- .../review/reviewCommentSelection.test.ts | 35 +++++++++++++++ .../features/review/reviewCommentSelection.ts | 2 +- apps/web/src/reviewCommentContext.test.ts | 45 +++++++++++++++++++ apps/web/src/reviewCommentContext.ts | 2 +- 5 files changed, 83 insertions(+), 3 deletions(-) diff --git a/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx b/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx index 881f67e86648f..2802319289270 100644 --- a/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx +++ b/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx @@ -100,7 +100,7 @@ export function ReviewCommentComposerSheet(props: ReviewCommentComposerSheetProp ? firstNumber !== null ? gt("Line {line}", { line: firstNumber }) : gt("File comment") - : firstNumber !== null && lastNumber !== null + : firstNumber !== null && lastNumber !== null && firstNumber < lastNumber ? gt("Lines {first}-{last}", { first: firstNumber, last: lastNumber }) : gt("{count, plural, one {{count} lines selected} other {{count} lines selected}}", { count: selectedLines.length, diff --git a/apps/mobile/src/features/review/reviewCommentSelection.test.ts b/apps/mobile/src/features/review/reviewCommentSelection.test.ts index 81eb0bba4083a..e5c3e17e92e59 100644 --- a/apps/mobile/src/features/review/reviewCommentSelection.test.ts +++ b/apps/mobile/src/features/review/reviewCommentSelection.test.ts @@ -8,6 +8,7 @@ import { clearReviewCommentTarget, completeReviewCommentRange, formatReviewCommentContext, + formatReviewSelectedRangeLabel, getReviewCommentSelection, reviewCommentSelectionScope, selectReviewCommentSelection, @@ -224,6 +225,40 @@ describe("review comment serialization", () => { }); }); +describe("review selected range label", () => { + it("falls back to line count when unified endpoints decrease across old and new numbers", () => { + expect( + formatReviewSelectedRangeLabel({ + ...makeTarget(), + lines: [ + { + kind: "line", + id: "line-1", + change: "context", + oldLineNumber: 10, + newLineNumber: 13, + content: "line 10 of the original file", + additionTokenIndex: null, + deletionTokenIndex: null, + comparison: null, + }, + { + kind: "line", + id: "line-2", + change: "delete", + oldLineNumber: 11, + newLineNumber: null, + content: "line 11 of the original file", + additionTokenIndex: null, + deletionTokenIndex: 0, + comparison: null, + }, + ], + }), + ).toBe("2 lines"); + }); +}); + describe("review comment selection store", () => { const changes = { id: "git:branch-range", content: "hash-1" }; const scope = reviewCommentSelectionScope(1, "env:thread", changes)!; diff --git a/apps/mobile/src/features/review/reviewCommentSelection.ts b/apps/mobile/src/features/review/reviewCommentSelection.ts index b5f852331acec..741f330375d3f 100644 --- a/apps/mobile/src/features/review/reviewCommentSelection.ts +++ b/apps/mobile/src/features/review/reviewCommentSelection.ts @@ -212,7 +212,7 @@ export function formatReviewSelectedRangeLabel(target: ReviewCommentTarget): str const firstNumber = getReviewUnifiedLineNumber(firstLine); const lastNumber = getReviewUnifiedLineNumber(lastLine); - if (firstNumber === null || lastNumber === null) { + if (firstNumber === null || lastNumber === null || firstNumber > lastNumber) { return lines.length === 1 ? "line" : `${lines.length} lines`; } diff --git a/apps/web/src/reviewCommentContext.test.ts b/apps/web/src/reviewCommentContext.test.ts index a92e3c7ceb5df..486b77248dfce 100644 --- a/apps/web/src/reviewCommentContext.test.ts +++ b/apps/web/src/reviewCommentContext.test.ts @@ -85,6 +85,51 @@ describe("review comment context parsing", () => { expect(new Set(ids).size).toBe(ids.length); }); + it("falls back to a line-count label when mixed diff-side line numbers decrease", () => { + const [fileDiff] = parsePatchFiles( + [ + "diff --git a/notes.txt b/notes.txt", + "--- a/notes.txt", + "+++ b/notes.txt", + "@@ -1,3 +1,6 @@", + "+added A", + "+added B", + "+added C", + " line 1", + " line 2", + " line 3", + "@@ -8,4 +11,3 @@", + " line 8", + " line 9", + " line 10", + "-line 11", + ].join("\n"), + { cacheKeyPrefix: "review-comment-test" }, + )[0]!.files; + + const comment = buildDiffReviewComment({ + id: "comment-inverted", + sectionId: "turn:2", + sectionTitle: "Turn 2", + filePath: "notes.txt", + fileDiff: fileDiff!, + range: { + start: 13, + side: "additions", + end: 11, + endSide: "deletions", + }, + text: "Check this deletion.", + }); + + expect(comment).toEqual( + expect.objectContaining({ + rangeLabel: "2 lines", + diff: "@@ -10,2 +13,1 @@\n line 10\n-line 11", + }), + ); + }); + it("keeps a selection's trailing blank line and whitespace in the rendered excerpt", () => { const fileDiff = parsePatchFiles( [ diff --git a/apps/web/src/reviewCommentContext.ts b/apps/web/src/reviewCommentContext.ts index 81b51fd7a1bf7..a4f3f93e51053 100644 --- a/apps/web/src/reviewCommentContext.ts +++ b/apps/web/src/reviewCommentContext.ts @@ -440,7 +440,7 @@ function formatDiffReviewRangeLabel(lines: ReadonlyArray): strin if (!firstLine || !lastLine) return "line"; const firstNumber = firstLine.newLineNumber ?? firstLine.oldLineNumber; const lastNumber = lastLine.newLineNumber ?? lastLine.oldLineNumber; - if (firstNumber === null || lastNumber === null) { + if (firstNumber === null || lastNumber === null || firstNumber > lastNumber) { return lines.length === 1 ? "line" : `${lines.length} lines`; } From b4a5a4927f371c5e6a9108f56f1c7884b510be79 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 25 Nov 2026 07:28:53 -0800 Subject: [PATCH 044/238] fix(web): reading position survives a panel resize right after a thread opens (#42915) --- .../preserveReadingPosition.browser.test.ts | 35 +++++++++++++++++++ apps/web/src/lib/preserveReadingPosition.ts | 5 +-- 2 files changed, 38 insertions(+), 2 deletions(-) create mode 100644 apps/web/src/lib/preserveReadingPosition.browser.test.ts diff --git a/apps/web/src/lib/preserveReadingPosition.browser.test.ts b/apps/web/src/lib/preserveReadingPosition.browser.test.ts new file mode 100644 index 0000000000000..0884531b7d182 --- /dev/null +++ b/apps/web/src/lib/preserveReadingPosition.browser.test.ts @@ -0,0 +1,35 @@ +import { describe, expect, it, onTestFinished, vi } from "vite-plus/test"; + +import { preserveReadingPosition } from "./preserveReadingPosition"; + +describe("preserveReadingPosition", () => { + it("keeps the reader's line through a resize that lands before the first layout report", async () => { + const scroller = document.createElement("div"); + scroller.style.cssText = + "width: 600px; height: 300px; overflow-y: auto; font: 16px/20px serif;"; + // The marker fits one line at both widths, so whichever caret the probe picks shares its top. + scroller.innerHTML = Array.from({ length: 30 }, (_, index) => + index === 15 + ? "

    Marker line.

    " + : `

    ${"Filler words that wrap across several lines. ".repeat(8)}

    `, + ).join(""); + document.body.append(scroller); + onTestFinished(() => scroller.remove()); + const markerText = [...scroller.querySelectorAll("p")][15]!.firstChild!; + const markerTop = () => { + const range = document.createRange(); + range.setStart(markerText, 0); + range.collapse(true); + return range.getBoundingClientRect().top - scroller.getBoundingClientRect().top; + }; + + const stop = preserveReadingPosition(scroller); + onTestFinished(stop); + scroller.scrollTop += markerTop() - 24; + scroller.dispatchEvent(new Event("scroll")); + const before = markerTop(); + scroller.style.width = "300px"; + + await vi.waitFor(() => expect(Math.abs(markerTop() - before)).toBeLessThan(2)); + }); +}); diff --git a/apps/web/src/lib/preserveReadingPosition.ts b/apps/web/src/lib/preserveReadingPosition.ts index a80f13a85a494..1f8b2fdd8df56 100644 --- a/apps/web/src/lib/preserveReadingPosition.ts +++ b/apps/web/src/lib/preserveReadingPosition.ts @@ -5,13 +5,14 @@ export function preserveReadingPosition( scroller: HTMLElement, enabled: () => boolean = () => true, ): () => void { - // Seeded by the observer's first report, which follows the browser's own layout; reading it - // here would force a layout mid-commit. + // Seeded by the observer's first report or an earlier scroll, never read here: that would force + // a layout mid-commit. A resize before either is not corrected. let width: number | null = null; let anchor: { range: Range; top: number } | null = null; let frame: number | null = null; const capture = () => { + width ??= scroller.clientWidth; if (frame !== null || scroller.clientWidth !== width) return; anchor = null; if (!enabled() || scroller.scrollTop === 0) return; From e045a127e783c41b7ed91fcbc1d17810c7b8c459 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 25 Nov 2026 07:33:57 -0800 Subject: [PATCH 045/238] fix(web): web search result links follow Open links in (#42882) --- .../chat/MessagesTimeline.browser.test.tsx | 57 +++++++++++++++++++ .../src/components/chat/V2ItemInspector.tsx | 56 +++++++++++++++--- 2 files changed, 106 insertions(+), 7 deletions(-) diff --git a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx index b31558c2a38ba..4009d7159f0f0 100644 --- a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx @@ -29,6 +29,7 @@ import { import * as DateTime from "effect/DateTime"; import { Atom, AsyncResult } from "effect/reactivity"; import { describe, expect, it, onTestFinished, vi } from "vite-plus/test"; +import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings"; import "~/index.css"; @@ -54,6 +55,7 @@ import { searchableMessageSegments } from "@t3tools/shared/threadFindText"; import { countThreadSearchOccurrences } from "@t3tools/shared/threadSearch"; import { collectThreadFindRanges } from "./threadFindHighlights"; import { toastManager } from "../ui/toast"; +import { __setClientSettingsForTests } from "../../hooks/useSettings"; import type { CitedHistory } from "./citationProcedure"; import type { TimelineNavigation } from "./timelineViewport"; import { rememberTimelinePosition } from "./timelineScrollAnchoring"; @@ -98,6 +100,26 @@ vi.mock(import("~/assets/assetUrls"), async (original) => { }; }); +const previewAccess = vi.hoisted(() => ({ granted: false })); +vi.mock(import("~/browser/previewRuntime"), async (original) => { + const actual = await original(); + return { + ...actual, + isPreviewAvailableFor: ((...args) => + previewAccess.granted || + actual.isPreviewAvailableFor(...args)) as typeof actual.isPreviewAvailableFor, + }; +}); +vi.mock(import("~/state/session"), async (original) => { + const actual = await original(); + return { + ...actual, + readEnvironmentScope: ((...args) => + previewAccess.granted || + actual.readEnvironmentScope(...args)) as typeof actual.readEnvironmentScope, + }; +}); + const ENVIRONMENT_ID = EnvironmentId.make("environment-local"); const CREATED_AT = "2026-03-17T19:12:28.000Z"; @@ -481,6 +503,41 @@ describe("MessagesTimeline work rows", () => { expect(output!.closest('[role="button"]')).toBeNull(); expect(document.getElementById(toggle.getAttribute("aria-controls") ?? "")).toContain(output); }); + it("opens a web search result in the thread's Browser when links open in T3 Code", async () => { + setup(); + previewAccess.granted = true; + __setClientSettingsForTests({ ...DEFAULT_CLIENT_SETTINGS, browserLinkTarget: "app" }); + onTestFinished(() => { + previewAccess.granted = false; + __setClientSettingsForTests(DEFAULT_CLIENT_SETTINGS); + }); + await using screen = await renderTimeline([ + work("web-search", { + label: "https://example.com/", + tone: "tool", + itemType: "web_search", + projectedItem: v2Item("web_search", { + id: "web-search", + patterns: ["https://example.com/"], + results: [{ url: "https://example.com/", title: "Example Domain" }], + }), + }), + ]); + await click(screen.button("Web search")); + const link = [...screen.container.querySelectorAll("a")].find( + (anchor) => anchor.textContent === "Example Domain", + ); + expect(link).toBeDefined(); + // A _blank click the app leaves to the browser goes to Electron's popup handler, which + // sends it to the system browser. + let followedNatively = true; + await act(async () => { + followedNatively = link!.dispatchEvent( + new MouseEvent("click", { bubbles: true, cancelable: true, button: 0 }), + ); + }); + expect(followedNatively).toBe(false); + }); }); describe("MessagesTimeline messages", () => { diff --git a/apps/web/src/components/chat/V2ItemInspector.tsx b/apps/web/src/components/chat/V2ItemInspector.tsx index f1cea52d8bd8a..82009fca19092 100644 --- a/apps/web/src/components/chat/V2ItemInspector.tsx +++ b/apps/web/src/components/chat/V2ItemInspector.tsx @@ -1,6 +1,10 @@ import { T, Var, useGT } from "gt-react"; import type { ToolCallDiffTarget } from "../../diffPanelStore"; -import type { EnvironmentId, OrchestrationV2ProjectedTurnItem } from "@t3tools/contracts"; +import type { + EnvironmentId, + OrchestrationV2ProjectedTurnItem, + ScopedThreadRef, +} from "@t3tools/contracts"; import { isJsonToolText, toolCallLines, @@ -14,6 +18,9 @@ import { isJavaScriptReplTool } from "@t3tools/shared/toolActivity"; import { ExternalLinkIcon } from "lucide-react"; import { memo, type ReactNode, Suspense, use } from "react"; +import { canOpenLinksInApp, resolveLinkTarget } from "../../browser/browserLinkTarget"; +import { useOpenLink } from "../../browser/useOpenLink"; +import { useClientSettings } from "../../hooks/useSettings"; import { useRenderedAppearance } from "../../hooks/useTheme"; import { cn } from "../../lib/utils"; import { resolveDiffThemeName } from "../../lib/diffRendering"; @@ -196,6 +203,41 @@ export function FetchedToolOutput(props: { ); } +function WebSearchResultLink(props: { + readonly href: string; + readonly threadRef: ScopedThreadRef; + readonly children: ReactNode; +}) { + const openLink = useOpenLink(props.threadRef); + // Subscribe so the synchronous _blank decision sees hydrated settings, as ChatMarkdown does. + const linkTargetPreference = useClientSettings((settings) => settings.browserLinkTarget); + return ( +
    { + if ( + resolveLinkTarget({ + url: props.href, + event, + preference: linkTargetPreference, + canOpenInApp: canOpenLinksInApp(props.threadRef), + }) !== "app" + ) { + return; + } + event.preventDefault(); + void openLink(props.href, { event }).catch(console.error); + }} + > + {props.children} + + + ); +} + function ToolCallBody( props: ToolOutputState & { readonly command?: string; @@ -370,15 +412,15 @@ export const V2ItemInspector = memo(function V2ItemInspector(props: V2ItemInspec return (
  • {safeHref ? ( - {result.title ?? result.url} - - + ) : (

    {result.title ?? result.url ?? gt("Search result")} From c14e9f9717739a03ad62289d82ba287bad64a5bf Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Wed, 25 Nov 2026 16:34:10 +0100 Subject: [PATCH 046/238] fix(server): preserve split terminal control sequences across scrollback clears (#42810) Co-authored-by: Julius Marminge --- .../server/src/terminal/Manager.clear.test.ts | 123 ++++++++++++++++++ apps/server/src/terminal/Manager.ts | 30 ++++- apps/server/src/terminal/OutputProtocol.ts | 18 +-- apps/web/src/terminal/ghostty/core.test.ts | 28 ++++ .../src/state/terminalOutput.ts | 18 ++- .../src/state/terminalSession.test.ts | 22 ++++ .../src/state/terminalSession.ts | 2 +- packages/contracts/src/terminal.ts | 1 + 8 files changed, 224 insertions(+), 18 deletions(-) create mode 100644 apps/server/src/terminal/Manager.clear.test.ts diff --git a/apps/server/src/terminal/Manager.clear.test.ts b/apps/server/src/terminal/Manager.clear.test.ts new file mode 100644 index 0000000000000..5e3815d9df771 --- /dev/null +++ b/apps/server/src/terminal/Manager.clear.test.ts @@ -0,0 +1,123 @@ +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { it } from "@effect/vitest"; +import { DEFAULT_TERMINAL_ID, ThreadId } from "@t3tools/contracts"; +import { SpawnExecutableResolution } from "@t3tools/shared/shell"; +import * as Deferred from "effect/Deferred"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; +import * as Stream from "effect/Stream"; +import { expect, vi } from "vite-plus/test"; + +import * as ProcessRunner from "../processRunner.ts"; +import { makeWithOptions } from "./Manager.ts"; + +const node = Layer.mergeAll(NodeServices.layer, NodeCrypto.layer); + +it.layer(Layer.mergeAll(node, ProcessRunner.layer.pipe(Layer.provide(node))), { + excludeTestServices: true, +})("TerminalManager clear", (it) => { + it.effect.each([ + { + part: "opener", + publishing: "old output\r\n", + queued: "\u001b]0;Build ", + pending: "\u001b]0;Build ", + afterClear: "progress\u0007ready\r\n", + }, + { + part: "CSI", + publishing: "old output\r\n", + queued: "\u001b[\n", + pending: "\u001b[", + afterClear: "mready\r\n", + }, + { + part: "terminator", + publishing: "old output\r\n\u001b]0;Build ", + queued: "progress\u0007", + afterClear: "ready\r\n", + }, + { + part: "exit", + publishing: "old output\r\n\u001b]0;Build ", + queued: "progress\u0007", + afterClear: "ready\r\n", + exit: { exitCode: 42, signal: null }, + }, + ])("keeps visible history correct when the title $part is queued", (row) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const logsDir = yield* fs.makeTempDirectoryScoped(); + const onData = vi.fn<(callback: (data: string) => void) => () => void>(() => () => {}); + const onExit = vi.fn< + (callback: (event: { exitCode: number; signal: number | null }) => void) => () => void + >(() => () => {}); + const manager = yield* makeWithOptions({ + logsDir, + ptyAdapter: { + spawn: () => + Effect.succeed({ + pid: 9000, + write: () => {}, + resize: () => {}, + kill: () => {}, + onData, + onExit, + }), + }, + foregroundProcessGroup: (pid) => Effect.succeed(pid), + processKillGraceMs: 0, + }).pipe(Effect.provideService(SpawnExecutableResolution, (command) => command)); + const input = { threadId: ThreadId.make("thread-1"), terminalId: DEFAULT_TERMINAL_ID }; + yield* manager.open({ ...input, cwd: logsDir }); + const live = yield* Stream.toPull(manager.attachOutputStream(input, "live")); + yield* live; + + const publishing = yield* Deferred.make(); + const resume = yield* Deferred.make(); + const printed = yield* Deferred.make(); + yield* Effect.acquireRelease( + manager.subscribe((event) => { + if (event.type !== "output") return Effect.void; + if (event.data === row.publishing) { + return Deferred.succeed(publishing, undefined).pipe( + Effect.andThen(Deferred.await(resume)), + ); + } + if (event.data === row.afterClear) return Deferred.succeed(printed, undefined); + return Effect.void; + }), + (unsubscribe) => + Deferred.succeed(resume, undefined).pipe(Effect.andThen(Effect.sync(unsubscribe))), + ); + const emitData = onData.mock.calls[0]![0]; + emitData(row.publishing); + yield* Deferred.await(publishing); + yield* live; + emitData(row.queued); + if (row.exit) onExit.mock.calls[0]![0](row.exit); + yield* manager.clear(input); + const [cleared] = yield* live; + expect(cleared?.type).toBe("cleared"); + yield* Deferred.succeed(resume, undefined); + + if (row.exit) { + emitData(row.afterClear); + const [exited] = yield* live; + expect(exited).toMatchObject({ type: "exited", exitCode: row.exit.exitCode }); + return; + } + if (row.pending) expect(cleared).toMatchObject({ pendingControlSequence: row.pending }); + emitData(row.afterClear); + yield* Deferred.await(printed); + + const reopened = yield* Stream.toPull(manager.attachOutputStream(input, "reopened")); + const [event] = yield* reopened; + if (event?.type !== "snapshot") throw new Error("Expected a terminal snapshot"); + const visible = event.snapshot.history.replace(/\u001b\]0;[^\u0007]*\u0007|\u001b\[m/g, ""); + expect(visible).toBe("ready\r\n"); + }), + ); +}); diff --git a/apps/server/src/terminal/Manager.ts b/apps/server/src/terminal/Manager.ts index 12f72a1e228b7..9aa897b970410 100644 --- a/apps/server/src/terminal/Manager.ts +++ b/apps/server/src/terminal/Manager.ts @@ -3941,12 +3941,35 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func Effect.gen(function* () { const terminalId = input.terminalId; const session = yield* requireSession(input.threadId, terminalId); + let queuedExit: PendingProcessEvent | undefined; + // Discard pre-clear output while keeping the parser in sync with the PTY. + for (const event of session.pendingProcessEvents.slice(session.pendingProcessEventIndex)) { + if (event?.type === "exit") { + queuedExit = event; + session.pendingHistoryControlSequence = ""; + break; + } + if (event?.type === "output") { + session.pendingHistoryControlSequence = sanitizeTerminalHistoryChunk( + session.pendingHistoryControlSequence, + event.data, + ).pendingControlSequence; + } + } + // Controls embedded in an unfinished CSI have already run before the clear. + if (session.pendingHistoryControlSequence.startsWith("\u001b[")) { + session.pendingHistoryControlSequence = session.pendingHistoryControlSequence.replace( + /[\x00-\x0f]/g, + "", + ); + } session.history.clear(); - session.pendingHistoryControlSequence = ""; - session.pendingProcessEvents = []; + session.pendingProcessEvents = queuedExit ? [queuedExit] : []; session.pendingProcessEventIndex = 0; - session.processEventDrainRunning = false; const eventStamp = advanceEventSequence(session); + const pendingControlSequence = unfinishedSequenceReplay( + session.pendingHistoryControlSequence, + ); // A drain waits for the key to go idle, which never happens while the shell keeps // printing; every reader of the file flushes it first. yield* persistWorker.enqueue(toSessionKey(input.threadId, terminalId), { @@ -3958,6 +3981,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func threadId: input.threadId, terminalId, sequence: eventStamp.sequence, + ...(pendingControlSequence === "" ? {} : { pendingControlSequence }), }); }), ); diff --git a/apps/server/src/terminal/OutputProtocol.ts b/apps/server/src/terminal/OutputProtocol.ts index 84f6e40923417..1b3f48faa6427 100644 --- a/apps/server/src/terminal/OutputProtocol.ts +++ b/apps/server/src/terminal/OutputProtocol.ts @@ -46,14 +46,16 @@ const queuedSize = (event: TerminalEvent | TerminalAttachStreamEvent) => ? byteLengthOf(event.message) : event.type === "activity" ? byteLengthOf(event.label) - : "snapshot" in event - ? byteLengthOf(event.snapshot.threadId) + - byteLengthOf(event.snapshot.terminalId) + - byteLengthOf(event.snapshot.history) + - byteLengthOf(event.snapshot.cwd) + - byteLengthOf(event.snapshot.worktreePath) + - byteLengthOf(event.snapshot.label) - : 0); + : event.type === "cleared" + ? byteLengthOf(event.pendingControlSequence) + : "snapshot" in event + ? byteLengthOf(event.snapshot.threadId) + + byteLengthOf(event.snapshot.terminalId) + + byteLengthOf(event.snapshot.history) + + byteLengthOf(event.snapshot.cwd) + + byteLengthOf(event.snapshot.worktreePath) + + byteLengthOf(event.snapshot.label) + : 0); // Byte-windowed streams carry TerminalAttachStreamEvent, whose encoded form is the // event itself, so charge it like the output queue does instead of serializing twice. diff --git a/apps/web/src/terminal/ghostty/core.test.ts b/apps/web/src/terminal/ghostty/core.test.ts index daa9820dddc46..4faca7a74f8d7 100644 --- a/apps/web/src/terminal/ghostty/core.test.ts +++ b/apps/web/src/terminal/ghostty/core.test.ts @@ -488,6 +488,34 @@ describe("GhosttyTerminalCore snapshots", () => { expect(core.snapshot()).toEqual(reference.snapshot()); }); + it.each([ + { + sequence: "title", + beforeClear: "", + pending: "\u001b]0;Build ", + afterClear: "progress\u0007", + }, + { sequence: "CSI", beforeClear: "\u001b[\n", pending: "\u001b[", afterClear: "m" }, + ])("resumes a split $sequence after clearing an attached terminal", async (row) => { + const [core, reference] = await Promise.all([createCore(), createCore()]); + let state = createSession(`old output\r\n${row.beforeClear}`); + const initial = readTerminalOutputUpdate(state.output, INITIAL_TERMINAL_OUTPUT_CURSOR); + writeTerminalOutputUpdate(core, initial); + + const cleared = { + type: "cleared", + threadId: "terminal-stream-test", + terminalId: "term-1", + pendingControlSequence: row.pending, + } as const; + state = applyTerminalAttachStreamEvent(state, cleared); + state = append(state, `${row.afterClear}ready\r\n`); + writeTerminalOutputUpdate(core, readTerminalOutputUpdate(state.output, initial.cursor)); + + reference.write("ready\r\n"); + expect(core.snapshot()).toEqual(reference.snapshot()); + }); + it("drops stale text in real Ghostty for a repeated snapshot, clear, restart, and a fresh attach", async () => { const [core, reference] = await Promise.all([createCore(), createCore()]); let state = createSession("hello"); diff --git a/packages/client-runtime/src/state/terminalOutput.ts b/packages/client-runtime/src/state/terminalOutput.ts index 0df9bcb7126d7..2bd870264b9e6 100644 --- a/packages/client-runtime/src/state/terminalOutput.ts +++ b/packages/client-runtime/src/state/terminalOutput.ts @@ -305,14 +305,19 @@ function resetOutput( const CLEAR_TERMINAL_TEXT = "\u001b[H\u001b[2J\u001b[3J"; /** Earlier output stays retained so a replay from the start restores those modes. */ -function clearOutput(current: TerminalOutputState, maxBufferBytes: number): TerminalOutputState { +function clearOutput( + current: TerminalOutputState, + maxBufferBytes: number, + pendingControlSequence = "", +): TerminalOutputState { + const data = CLEAR_TERMINAL_TEXT + pendingControlSequence; // The erase rides over the budget: trimming here would evict the output that set those modes. const cleared = appendOutput( { ...current, pendingSnapshotSequenceState: undefined }, - CLEAR_TERMINAL_TEXT, + data, maxBufferBytes <= 0 ? maxBufferBytes - : Math.max(maxBufferBytes, current.retainedBytes + CLEAR_TERMINAL_TEXT.length), + : Math.max(maxBufferBytes, current.retainedBytes + textEncoder.encode(data).byteLength), ); return { ...cleared, textStartOffset: cleared.nextOffset }; } @@ -327,9 +332,10 @@ export function terminalOutputReplay(output: TerminalOutputState): string { export function terminalOutputText(output: TerminalOutputState): string { const text = output.chunks.map((chunk) => chunk.data).join(""); const firstOffset = output.chunks[0]?.startOffset ?? output.nextOffset; - return text.slice( - Math.max(terminalSequenceEnd(output.sequenceState, text), output.textStartOffset - firstOffset), - ); + const start = Math.max(0, output.textStartOffset - firstOffset); + const sequenceState = terminalSequenceStateAfter(output.sequenceState, text, 0, start); + const visible = text.slice(start); + return visible.slice(terminalSequenceEnd(sequenceState, visible)); } export function readTerminalOutputUpdate( diff --git a/packages/client-runtime/src/state/terminalSession.test.ts b/packages/client-runtime/src/state/terminalSession.test.ts index 19401a26c7f89..2b44a5900f20d 100644 --- a/packages/client-runtime/src/state/terminalSession.test.ts +++ b/packages/client-runtime/src/state/terminalSession.test.ts @@ -386,6 +386,28 @@ describe("terminal session reducers", () => { expect(state.output.retainedBytes).toBe(8); }); + it("skips the rest of an unfinished title when reading text after a clear", () => { + let state = applyTerminalAttachStreamEvent(EMPTY_TERMINAL_BUFFER_STATE, { + type: "snapshot", + snapshot: BASE_SNAPSHOT, + }); + state = applyTerminalAttachStreamEvent(state, { + type: "cleared", + ...TARGET, + pendingControlSequence: "\u001b]0;Build ", + }); + for (const data of ["pro", "gress"]) { + state = applyTerminalAttachStreamEvent(state, { type: "output", ...TARGET, data }); + expect(terminalOutputText(state.output)).toBe(""); + } + state = applyTerminalAttachStreamEvent(state, { + type: "output", + ...TARGET, + data: "\u0007ready", + }); + expect(terminalOutputText(state.output)).toBe("ready"); + }); + it("resets for repeated snapshots and restart even when output text repeats, and erases on clear", () => { let state = applyTerminalAttachStreamEvent(EMPTY_TERMINAL_BUFFER_STATE, { type: "snapshot", diff --git a/packages/client-runtime/src/state/terminalSession.ts b/packages/client-runtime/src/state/terminalSession.ts index a7224209920bc..4eb84e9b192ae 100644 --- a/packages/client-runtime/src/state/terminalSession.ts +++ b/packages/client-runtime/src/state/terminalSession.ts @@ -195,7 +195,7 @@ export function applyTerminalAttachStreamEvent( case "cleared": return { ...current, - output: clearOutput(current.output, maxBufferBytes), + output: clearOutput(current.output, maxBufferBytes, event.pendingControlSequence), error: null, version: current.version + 1, }; diff --git a/packages/contracts/src/terminal.ts b/packages/contracts/src/terminal.ts index 31419fe56374b..0043f87d0eaed 100644 --- a/packages/contracts/src/terminal.ts +++ b/packages/contracts/src/terminal.ts @@ -390,6 +390,7 @@ const TerminalErrorEvent = Schema.Struct({ const TerminalClearedEvent = Schema.Struct({ ...TerminalEventBaseSchema.fields, type: Schema.Literal("cleared"), + pendingControlSequence: Schema.optionalKey(Schema.String), }); const TerminalRestartedEvent = Schema.Struct({ From 3373a78606296baa9bb6e386c242da2f9ae32e04 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Wed, 25 Nov 2026 16:34:28 +0100 Subject: [PATCH 047/238] fix(web): update terminal labels when the language changes (#42872) Co-authored-by: Julius Marminge --- apps/web/src/terminal/ghostty/surface.ts | 80 ++++++++++++------- ...minal-input-follows-language-change.e2e.ts | 57 +++++++++++++ 2 files changed, 106 insertions(+), 31 deletions(-) create mode 100644 scripts/scenarios/pending-terminal-input-follows-language-change.e2e.ts diff --git a/apps/web/src/terminal/ghostty/surface.ts b/apps/web/src/terminal/ghostty/surface.ts index b06a77f490742..b104e749b4756 100644 --- a/apps/web/src/terminal/ghostty/surface.ts +++ b/apps/web/src/terminal/ghostty/surface.ts @@ -23,6 +23,7 @@ import { isMonospaceFamily } from "../../appearanceFonts"; import { observeResize } from "../../lib/observeResize"; import { msg } from "gt-react"; import { m } from "../../i18n/messages"; +import { subscribeI18n } from "../../i18n/runtime"; const DEFAULT_TERMINAL_FONT_SIZE = 12; const MIN_TERMINAL_FONT_SIZE = 6; @@ -667,6 +668,7 @@ export class GhosttyTerminalSurface { metrics: GhosttyCellMetrics, fontFamily: string, options: GhosttyTerminalSurfaceOptions, + private readonly stopObservingI18n: () => void, ) { this.mount = mount; this.canvas = canvas; @@ -703,7 +705,6 @@ export class GhosttyTerminalSurface { const input = document.createElement("textarea"); input.className = "t3-ghostty-input"; - input.setAttribute("aria-label", m(msg("Terminal input"))); input.autocapitalize = "off"; input.autocomplete = "off"; input.spellcheck = false; @@ -714,7 +715,6 @@ export class GhosttyTerminalSurface { scrollbar.className = "group absolute top-1 right-px bottom-1 z-1 w-[var(--app-scrollbar-width)] cursor-default touch-none"; scrollbar.setAttribute("role", "scrollbar"); - scrollbar.setAttribute("aria-label", m(msg("Terminal scrollback"))); scrollbar.setAttribute("aria-orientation", "vertical"); scrollbar.tabIndex = 0; scrollbar.hidden = true; @@ -722,42 +722,59 @@ export class GhosttyTerminalSurface { scrollbarThumb.className = "absolute inset-x-px top-0 rounded-[3px] bg-[var(--app-scrollbar-thumb)] transition-[background-color] duration-[120ms] ease-[ease-out] group-hover:bg-[var(--app-scrollbar-thumb-hover)] group-focus-visible:bg-[var(--app-scrollbar-thumb-hover)]"; scrollbar.append(scrollbarThumb); + const updateAccessibleNames = () => { + input.setAttribute("aria-label", m(msg("Terminal input"))); + scrollbar.setAttribute("aria-label", m(msg("Terminal scrollback"))); + }; + updateAccessibleNames(); mount.replaceChildren(canvas, input, scrollbar); const context = canvas.getContext("2d", { alpha: false }); if (!context) throw new Error("Canvas 2D is unavailable"); context.fillStyle = `rgb(${options.theme.background.r}, ${options.theme.background.g}, ${options.theme.background.b})`; context.fillRect(0, 0, canvas.width, canvas.height); - const fontSize = terminalFontSize(options.font?.size); + const stopObservingI18n = subscribeI18n(updateAccessibleNames); try { - // Load bundled fonts before measuring; fallback metrics would size the wrong grid. - await ensureTerminalSymbolsFont(); - } catch {} - const fontFamily = await loadTerminalFontFamily(options.font?.family, fontSize); - const metrics = measureGhosttyCell(context, fontSize, fontFamily); - const grid = terminalGridSize(mount.clientWidth, mount.clientHeight, metrics, CONTENT_PADDING); - const core = await GhosttyTerminalCore.create( - grid.cols, - grid.rows, - metrics.width, - metrics.height, - options.theme, - options.onReply, - ); - const surface = new GhosttyTerminalSurface( - mount, - canvas, - input, - scrollbar, - scrollbarThumb, - context, - core, - metrics, - fontFamily, - options, - ); - surface.fit(); - return surface; + const fontSize = terminalFontSize(options.font?.size); + try { + // Load bundled fonts before measuring; fallback metrics would size the wrong grid. + await ensureTerminalSymbolsFont(); + } catch {} + const fontFamily = await loadTerminalFontFamily(options.font?.family, fontSize); + const metrics = measureGhosttyCell(context, fontSize, fontFamily); + const grid = terminalGridSize( + mount.clientWidth, + mount.clientHeight, + metrics, + CONTENT_PADDING, + ); + const core = await GhosttyTerminalCore.create( + grid.cols, + grid.rows, + metrics.width, + metrics.height, + options.theme, + options.onReply, + ); + const surface = new GhosttyTerminalSurface( + mount, + canvas, + input, + scrollbar, + scrollbarThumb, + context, + core, + metrics, + fontFamily, + options, + stopObservingI18n, + ); + surface.fit(); + return surface; + } catch (error) { + stopObservingI18n(); + throw error; + } } setVisible(visible: boolean): void { @@ -1079,6 +1096,7 @@ export class GhosttyTerminalSurface { this.disposed = true; this.clearHoveredLink(); this.stopObservingResize(); + this.stopObservingI18n(); document.fonts.removeEventListener("loadingdone", this.onFontsLoaded); this.dprMedia?.removeEventListener("change", this.onDevicePixelRatioChange); this.dprMedia = null; diff --git a/scripts/scenarios/pending-terminal-input-follows-language-change.e2e.ts b/scripts/scenarios/pending-terminal-input-follows-language-change.e2e.ts new file mode 100644 index 0000000000000..05e8abbe98849 --- /dev/null +++ b/scripts/scenarios/pending-terminal-input-follows-language-change.e2e.ts @@ -0,0 +1,57 @@ +import { expect } from "e2e"; + +import { test, WEB } from "./t3.ts"; + +test( + "Language changes update the same terminal input during and after setup", + WEB, + async ({ t3, app, browser, screen }) => { + const project = await t3.project("demo"); + const thread = await t3.thread({ project, title: "Terminal work", messages: ["Start"] }); + await t3.open(thread); + + await browser.evaluate(() => { + const load = FontFace.prototype.load; + const ready = new Promise((resolve) => { + window.addEventListener("release-terminal-font", () => resolve(), { once: true }); + }); + FontFace.prototype.load = function () { + return this.family.includes("Symbols Nerd Font Mono") + ? ready.then(() => load.call(this)) + : load.call(this); + }; + return null; + }); + + await screen.getByRole("button", "Toggle terminal drawer").tap(); + const input = browser.locator(".t3-ghostty-input:not([data-workspace-focus-default])"); + await expect(input).toHaveAttribute("aria-label", "Terminal input"); + await browser.evaluate(() => { + document.querySelector(".t3-ghostty-input")!.setAttribute("data-original-terminal", ""); + return null; + }); + + await screen.getByRole("button", "Settings", { exact: true }).tap(); + await screen.getByLabel("Language", { exact: true }).tap(); + await screen.getByText("日本語", { exact: true }).tap(); + await screen.getByLabel("言語", { exact: true }).waitFor(); + + const originalInput = browser.locator( + ".t3-ghostty-input[data-original-terminal]:not([data-workspace-focus-default])", + ); + await app.screenshot("pending-terminal-input-after-language-change"); + await expect(originalInput).toHaveAttribute("aria-label", "ターミナルの入力"); + await browser.evaluate(() => window.dispatchEvent(new Event("release-terminal-font"))); + + const readyInput = browser.locator( + ".t3-ghostty-input[data-original-terminal][data-workspace-focus-default]", + ); + await expect(readyInput).toHaveAttribute("aria-label", "ターミナルの入力"); + await screen.getByLabel("言語", { exact: true }).tap(); + await screen.getByText("English", { exact: true }).tap(); + await screen.getByLabel("Language", { exact: true }).waitFor(); + await browser.keyboard.press("Escape"); + + await expect(readyInput).toHaveAttribute("aria-label", "Terminal input"); + }, +); From acd4fc67b930b0a9be7799f3f986e0ec46bf7a14 Mon Sep 17 00:00:00 2001 From: Marcus Takagi Date: Wed, 25 Nov 2026 23:34:42 +0800 Subject: [PATCH 048/238] fix(web): show Labs device preferences read-only for projects (#42884) Co-authored-by: huyuetian Co-authored-by: Julius Marminge --- .../LabsSettingsPanel.scope.browser.test.tsx | 129 ++++++++++++++++++ .../components/settings/LabsSettingsPanel.tsx | 2 + docs/user/project-settings.md | 10 +- ...boring-sidebar-read-only-in-project.e2e.ts | 26 ++++ 4 files changed, 162 insertions(+), 5 deletions(-) create mode 100644 apps/web/src/components/settings/LabsSettingsPanel.scope.browser.test.tsx create mode 100644 scripts/scenarios/labs-boring-sidebar-read-only-in-project.e2e.ts diff --git a/apps/web/src/components/settings/LabsSettingsPanel.scope.browser.test.tsx b/apps/web/src/components/settings/LabsSettingsPanel.scope.browser.test.tsx new file mode 100644 index 0000000000000..bce95490d461e --- /dev/null +++ b/apps/web/src/components/settings/LabsSettingsPanel.scope.browser.test.tsx @@ -0,0 +1,129 @@ +import { PrimaryConnectionTarget } from "@t3tools/client-runtime/connection"; +import { EnvironmentId, ProjectId, ServerConfig } from "@t3tools/contracts"; +import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; +import { expect, it, vi } from "vite-plus/test"; + +import { render } from "../../../test/render"; +import "../../index.css"; +import { ensureClientSettingsHydrated, persistClientSettingsPatch } from "../../hooks/useSettings"; +import { buildSidebarProjectSnapshots } from "../../sidebarProjectGrouping"; +import type { EnvironmentPresentation } from "../../state/environments"; +import type { Project } from "../../types"; + +const environmentId = EnvironmentId.make("labs-settings"); +const config = Schema.decodeSync(ServerConfig)({ + environment: { + environmentId, + label: "Desk", + platform: { os: "linux", arch: "x64" }, + serverVersion: "1.0.0", + orchestrationProtocolVersion: 2, + capabilities: {}, + }, + auth: { + policy: "loopback-browser", + bootstrapMethods: ["one-time-token"], + sessionMethods: ["browser-session-cookie"], + sessionCookieName: "t3_session", + }, + cwd: "/workspace/labs", + keybindingsConfigPath: "/workspace/keybindings.json", + keybindings: [], + issues: [], + providers: [], + availableEditors: [], + observability: { + logsDirectoryPath: "/workspace/logs", + localTracingEnabled: false, + otlpTracesEnabled: false, + otlpMetricsEnabled: false, + }, + settings: {}, +}); +const environments: EnvironmentPresentation[] = [ + { + environmentId, + label: "Desk", + displayUrl: "http://localhost:12345", + relayManaged: false, + entry: { + target: new PrimaryConnectionTarget({ + environmentId, + label: "Desk", + httpBaseUrl: "http://localhost:12345", + wsBaseUrl: "ws://localhost:12345/ws", + }), + profile: Option.none(), + enabled: true, + }, + connection: { phase: "connected", error: null, traceId: null }, + refusedRouteIds: [], + serverConfig: config, + }, +]; +const projects: Project[] = [ + { + id: ProjectId.make("labs-project"), + environmentId, + title: "Labs project", + workspaceRoot: "/workspace/labs", + repositoryIdentity: null, + defaultModelSelection: null, + scripts: [], + createdAt: "2026-11-14T00:00:00.000Z", + updatedAt: "2026-11-14T00:00:00.000Z", + }, +]; + +vi.mock(import("../../state/environments"), async (original) => ({ + ...(await original()), + useEnvironments: () => ({ + isReady: true, + networkStatus: "online" as const, + environments, + presentationById: new Map(), + }), + usePrimaryEnvironmentId: () => environmentId, + usePrimaryEnvironment: () => environments[0]!, + readEnvironment: () => environments[0]!, +})); +vi.mock(import("../../state/session"), async (original) => ({ + ...(await original()), + useEnvironmentScope: () => true, + useEnvironmentsWithScope: () => new Set([environmentId]), +})); +vi.mock(import("../../state/entities"), async (original) => ({ + ...(await original()), + useProjects: () => projects, + useServerConfigs: () => new Map([[environmentId, config]]), +})); + +import { LabsSettingsPanel } from "./LabsSettingsPanel"; +import { SettingsScopeProvider } from "./SettingsScopeContext"; + +const [group] = buildSidebarProjectSnapshots({ + projects, + settings: DEFAULT_CLIENT_SETTINGS, + primaryEnvironmentId: environmentId, + resolveEnvironmentLabel: () => "Desk", +}); + +it("shows Boring sidebar device preferences read-only while a project is selected", async () => { + await ensureClientSettingsHydrated(); + await persistClientSettingsPatch( + { boringSidebarEnabled: true, boringSidebarMultilineRows: false }, + async () => {}, + ); + await using screen = await render( + {}}> + + , + { router: "/settings/labs" }, + ); + + for (const name of ["Boring sidebar (group by project)", "Two-line folder rows"]) { + expect(screen.getByRole("switch", { name }).element().closest("[inert]")).not.toBeNull(); + } +}); diff --git a/apps/web/src/components/settings/LabsSettingsPanel.tsx b/apps/web/src/components/settings/LabsSettingsPanel.tsx index 71bf6d6da55f5..d5e77b2dc28a3 100644 --- a/apps/web/src/components/settings/LabsSettingsPanel.tsx +++ b/apps/web/src/components/settings/LabsSettingsPanel.tsx @@ -61,6 +61,7 @@ function BoringSidebarRow() { return ( { + await t3.project("demo"); + await t3.open("/settings/labs"); + + await screen.getByRole("switch", "Boring sidebar (group by project)").check(); + await expect(screen.getByRole("switch", "Two-line folder rows")).toBeVisible(); + + await screen.getByRole("button", "Project scope: All projects").tap(); + await screen.getByRole("menuitemradio").filter({ hasText: "demo" }).tap(); + await expect(screen.getByRole("button", "Project scope: demo")).toBeVisible(); + await app.screenshot("project-selected"); + + // A project cannot override a device preference, so neither switch may offer an edit. + await expect( + browser.locator('[inert] [aria-label="Boring sidebar (group by project)"]'), + ).toBeVisible(); + await expect(browser.locator('[inert] [aria-label="Two-line folder rows"]')).toBeVisible(); + }, +); From aef22ed239b5947300d03d0d487c5d32cb4e5d7f Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 25 Nov 2026 07:34:55 -0800 Subject: [PATCH 049/238] fix(server): t3 connect link says to restart a running server, not start t3 serve (#42904) --- apps/server/src/cli/connect.test.ts | 62 +++++++++++++++++++++++++++++ apps/server/src/cli/connect.ts | 17 +++++--- 2 files changed, 73 insertions(+), 6 deletions(-) diff --git a/apps/server/src/cli/connect.test.ts b/apps/server/src/cli/connect.test.ts index 630fe7cbfbb63..d591cb311fc61 100644 --- a/apps/server/src/cli/connect.test.ts +++ b/apps/server/src/cli/connect.test.ts @@ -278,3 +278,65 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer, NetService.layer)) ); }, ); + +it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer, NetService.layer))( + "t3 connect link next step", + (it) => { + it.effect("tells the user to restart a server that is already running, not to start one", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-connect-link-test-" }); + const relayClientPath = `${baseDir}/bin/cloudflared`; + yield* fs.makeDirectory(`${baseDir}/bin`, { recursive: true }); + yield* fs.writeFileString( + relayClientPath, + `#!/bin/sh\necho "cloudflared version ${RelayClient.CLOUDFLARED_VERSION}"\n`, + ); + yield* fs.chmod(relayClientPath, 0o755); + yield* fs.makeDirectory(`${baseDir}/userdata/secrets`, { recursive: true }); + yield* fs.writeFileString( + `${baseDir}/userdata/secrets/cloud-cli-oauth-token.bin`, + JSON.stringify({ + accessToken: "access", + refreshToken: "refresh", + expiresAtEpochMs: 4_102_444_800_000, + identity: "user@example.com", + }), + ); + const state = yield* makePersistedServerRuntimeState({ + config: { host: "127.0.0.1", devUrl: undefined }, + port: 3773, + }); + yield* persistServerRuntimeState({ + path: `${baseDir}/userdata/server-runtime.json`, + state: { ...state, pid: process.pid }, + }); + + yield* Command.runWith(makeCli({ cloudEnabled: true }), { version: "0.0.0" })([ + "connect", + "link", + "--headless", + "--base-dir", + baseDir, + ]).pipe( + Effect.provide( + ConfigProvider.layer( + ConfigProvider.fromEnv({ env: { T3CODE_CLOUDFLARED_PATH: relayClientPath } }), + ), + ), + ); + + const printed = (yield* TestConsole.logLines).join("\n"); + const restart = yield* resolveHostCliCommand("service restart", ["--base-dir", baseDir]); + const serve = yield* resolveHostCliCommand("serve", ["--base-dir", baseDir]); + assert.include(printed, "✓ Authorized as user@example.com"); + assert.include(printed, `\`${restart.command}\``); + assert.notInclude(printed, `\`${serve.command}\``); + }).pipe( + Effect.scoped, + Effect.provideService(HostProcess.Environment, {}), + Effect.provide(Layer.fresh(TestConsole.layer)), + ), + ); + }, +); diff --git a/apps/server/src/cli/connect.ts b/apps/server/src/cli/connect.ts index 8ef202c2d014f..8dfb794d36c05 100644 --- a/apps/server/src/cli/connect.ts +++ b/apps/server/src/cli/connect.ts @@ -649,12 +649,17 @@ const connectLinkCommand = Command.make("link", { yield* Console.log("T3 Connect\n"); const linked = yield* linkEnvironmentForConnect(flags); if (linked) { - const serveCommand = yield* resolveHostCliHint("serve", flags.baseDir); - yield* Console.log( - flags.publishOnly - ? `✓ Authorized${connectedAs(linked.identity)}\n\nNext\n Start T3 to publish agent activity (no managed tunnel).` - : `✓ Authorized${connectedAs(linked.identity)}\n\nNext\n Start the server with \`${serveCommand}\` to make this machine reachable.`, - ); + const config = yield* ServerConfig.ServerConfig; + const running = yield* readLiveServerRuntimeState(config.serverRuntimeStatePath); + const purpose = flags.publishOnly + ? "publish agent activity (no managed tunnel)" + : "make this machine reachable"; + const next = Option.isSome(running) + ? `A T3 Code server is already running. Restart it to ${purpose}: run \`${yield* resolveHostCliHint("service restart", flags.baseDir)}\` for the background service, or stop the server and start it again.` + : flags.publishOnly + ? `Start T3 to ${purpose}.` + : `Start the server with \`${yield* resolveHostCliHint("serve", flags.baseDir)}\` to ${purpose}.`; + yield* Console.log(`✓ Authorized${connectedAs(linked.identity)}\n\nNext\n ${next}`); } }), ), From 831f2408825c1c79ddb4e1256d8fe9ba9234befc Mon Sep 17 00:00:00 2001 From: Victor Date: Wed, 25 Nov 2026 09:35:09 -0600 Subject: [PATCH 050/238] fix(server): extensionless empty ZIP files are detected as application/zip (#42899) Co-authored-by: Julius Marminge --- apps/server/src/workspace/WorkspaceFileSystem.test.ts | 7 ++++++- apps/server/src/workspace/fileHeaderMimeType.ts | 3 ++- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/apps/server/src/workspace/WorkspaceFileSystem.test.ts b/apps/server/src/workspace/WorkspaceFileSystem.test.ts index 7fd184a1f1e9b..98b34bba97ac9 100644 --- a/apps/server/src/workspace/WorkspaceFileSystem.test.ts +++ b/apps/server/src/workspace/WorkspaceFileSystem.test.ts @@ -153,11 +153,16 @@ it.layer(layerTest, { excludeTestServices: true })("WorkspaceFileSystemLive", (i image, new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), ); + const archive = path.join(cwd, "archive"); + const emptyZip = new Uint8Array(22); + emptyZip.set([0x50, 0x4b, 0x05, 0x06]); + yield* fs.writeFile(archive, emptyZip); expect( - (yield* service.getMetadata({ paths: [path.join(cwd, "run"), image] })).entries, + (yield* service.getMetadata({ paths: [path.join(cwd, "run"), image, archive] })).entries, ).toEqual([ { kind: "file", byteLength: script.length, mimeType: "text/x-python" }, { kind: "file", byteLength: 8, mimeType: "image/png" }, + { kind: "file", byteLength: 22, mimeType: "application/zip" }, ]); }), ); diff --git a/apps/server/src/workspace/fileHeaderMimeType.ts b/apps/server/src/workspace/fileHeaderMimeType.ts index 0c31a734ca730..889f101ac2d81 100644 --- a/apps/server/src/workspace/fileHeaderMimeType.ts +++ b/apps/server/src/workspace/fileHeaderMimeType.ts @@ -3,7 +3,8 @@ export function fileHeaderMimeType(bytes: Uint8Array): string | undefined { signature.every((byte, index) => bytes[offset + index] === byte); if (startsWith([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])) return "image/png"; if (startsWith([0xff, 0xd8, 0xff])) return "image/jpeg"; - if (startsWith([0x50, 0x4b, 0x03, 0x04])) return "application/zip"; + if (startsWith([0x50, 0x4b, 0x03, 0x04]) || startsWith([0x50, 0x4b, 0x05, 0x06])) + return "application/zip"; if (startsWith([0x52, 0x49, 0x46, 0x46]) && startsWith([0x57, 0x45, 0x42, 0x50], 8)) return "image/webp"; const header = new TextDecoder().decode(bytes); From 14cc3d1d38e42040a247a506d2a5586087b3adda Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 25 Nov 2026 07:35:25 -0800 Subject: [PATCH 051/238] fix(server): OpenCode /goal length rejection names the limit (#42905) --- .../Adapters/OpenCode2AdapterV2.test.ts | 33 +++++++++++++++++++ .../provider-core/src/server/failure.test.ts | 6 ++++ packages/provider-core/src/server/failure.ts | 19 +++++++++++ 3 files changed, 58 insertions(+) diff --git a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts index 16193d12e242e..f5279d24116fd 100644 --- a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts @@ -8662,6 +8662,39 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { }), ); + // regression: #42892 + it.effect("shows OpenCode's goal length limit when it rejects a /goal objective", () => + Effect.gen(function* () { + const objective = "a".repeat(4001); + const { runtime, thread } = yield* resumed( + [ + out("command.list", ""), + reply("command.list", { location: { directory: WORK }, data: [{ name: "goal" }] }), + out("message.list", { sessionID: SESSION, order: "desc", limit: "1" }), + reply("message.list", { data: [], cursor: {} }), + out("session.command", { sessionID: SESSION, name: "goal", text: objective }), + reply("session.command", { + status: 500, + body: { + _tag: "CommandExecutionError", + command: "goal", + message: "A goal objective is limited to 4000 characters (got 4001).", + }, + }), + ], + { version: "2.2.5" }, + ); + const terminal = yield* terminalOf(runtime).pipe(Effect.forkScoped); + const input = turnInput(thread); + yield* runtime + .startTurn({ ...input, message: { ...input.message, text: `/goal ${objective}` } }) + .pipe(Effect.ignore); + const ended = yield* Fiber.join(terminal); + assert.equal(ended?.status, "failed"); + assert.include(ended?.failure?.message ?? "", "4000 characters (got 4001)"); + }), + ); + it.effect("reads an existing OpenCode 2.2.5 goal when resuming a session", () => Effect.gen(function* () { const runtime = yield* openCode2ReplayRuntime( diff --git a/packages/provider-core/src/server/failure.test.ts b/packages/provider-core/src/server/failure.test.ts index b052beef8110d..6dfda1bf15db8 100644 --- a/packages/provider-core/src/server/failure.test.ts +++ b/packages/provider-core/src/server/failure.test.ts @@ -220,6 +220,12 @@ it("keeps unrecognized reasons and provider text out of category messages", () = method: "turn/start", message: "goal objective must be at most 4000 characters", }, + { _tag: "CommandExecutionError", command: "goal", message: "private-goal-output" }, + { + _tag: "CommandExecutionError", + command: "review", + message: "A goal objective is limited to 4000 characters (got 4001).", + }, ]) { assert.equal( makeProviderFailure({ cause: { _tag: "ProviderAdapterTurnStartError", cause } }).message, diff --git a/packages/provider-core/src/server/failure.ts b/packages/provider-core/src/server/failure.ts index 43984aaaab5b6..871820d22bb9d 100644 --- a/packages/provider-core/src/server/failure.ts +++ b/packages/provider-core/src/server/failure.ts @@ -87,6 +87,10 @@ export function providerProcessExitGuidance(output: unknown): string { const CODEX_GOAL_VALIDATION_MESSAGE = /^goal objective must (?:not be empty|be at most \d{1,6} characters)$/u; +// OpenCode's /goal command rejecting an objective longer than it accepts. +const OPENCODE_GOAL_LENGTH_REJECTION = + /^A goal objective is limited to \d{1,6} characters \(got \d{1,9}\)\.$/u; + // codex_config::ConstraintError::InvalidValue for a managed requirements.toml or cloud policy. const CODEX_ACCESS_REQUIREMENT_REJECTION = /invalid value for `(approval_policy|sandbox_mode)`: `([A-Za-z]{1,32})` is not in the allowed set /u; @@ -169,6 +173,21 @@ function curatedCauseMessages(cause: unknown): { } break; } + case "CommandExecutionError": { + // Only OpenCode's fixed-shape goal length text is shown; other command output stays hidden. + const rejection = stringField(cause, "message"); + if ( + (cause as Record).command === "goal" && + rejection !== undefined && + OPENCODE_GOAL_LENGTH_REJECTION.test(rejection) + ) { + return { + known: `OpenCode rejected the goal: ${rejection} Shorten it and send /goal again.`, + category: categoryMessage(), + }; + } + break; + } case "AcpProcessExitedError": case "CodexAppServerProcessExitedError": { const exit = `provider process exited${processExitStatus(cause)}`; From 83a7c75b88b45c8076a0c42cd442bed3b243f6a0 Mon Sep 17 00:00:00 2001 From: nikalezah <67012982+nikalezah@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:35:41 +0500 Subject: [PATCH 052/238] fix(web,mobile): adding a project from a draft's picker no longer leaves the draft behind (#42889) Co-authored-by: Julius Marminge --- .../projects/AddProjectScreen.logic.test.ts | 29 ++++++++- .../projects/AddProjectScreen.logic.ts | 32 ++++++++++ .../features/projects/AddProjectScreen.tsx | 52 +++++++++++----- apps/web/src/commandPaletteBus.ts | 8 ++- .../src/components/CommandPalette.logic.ts | 15 ++++- apps/web/src/components/CommandPalette.tsx | 31 +++++++++- .../src/components/chat/DraftHeroHeadline.tsx | 33 +++-------- apps/web/src/hooks/useNewProject.ts | 8 +-- apps/web/src/lib/moveDraftToProject.test.ts | 59 +++++++++++++++++++ apps/web/src/lib/moveDraftToProject.ts | 42 +++++++++++++ .../add-project-takes-the-draft.e2e.ts | 29 +++++++++ 11 files changed, 286 insertions(+), 52 deletions(-) create mode 100644 apps/web/src/lib/moveDraftToProject.test.ts create mode 100644 apps/web/src/lib/moveDraftToProject.ts create mode 100644 scripts/scenarios/add-project-takes-the-draft.e2e.ts diff --git a/apps/mobile/src/features/projects/AddProjectScreen.logic.test.ts b/apps/mobile/src/features/projects/AddProjectScreen.logic.test.ts index 492dc5fc11d35..56fec18809391 100644 --- a/apps/mobile/src/features/projects/AddProjectScreen.logic.test.ts +++ b/apps/mobile/src/features/projects/AddProjectScreen.logic.test.ts @@ -2,7 +2,8 @@ import type { EnvironmentConnectionPhase } from "@t3tools/client-runtime/connect import { EnvironmentId } from "@t3tools/contracts"; import { describe, expect, it } from "vite-plus/test"; -import { resolveAddProjectEnvironment } from "./AddProjectScreen.logic"; +import { newTaskFlowKey } from "../threads/new-task-flow-state"; +import { chooserDraftKey, resolveAddProjectEnvironment } from "./AddProjectScreen.logic"; const ENVIRONMENT_A = EnvironmentId.make("environment-a"); const ENVIRONMENT_B = EnvironmentId.make("environment-b"); @@ -21,3 +22,29 @@ describe("resolveAddProjectEnvironment", () => { ).toBeNull(); }); }); + +describe("chooserDraftKey", () => { + const home = { key: "home", name: "Home" }; + const draftRoute = { key: "thread", name: "Thread", params: { draft: { requestId: "r1" } } }; + const chooser = { key: "chooser", name: "NewTaskProject" }; + const addProject = [ + { key: "add", name: "AddProject" }, + { key: "local", name: "AddProjectLocal" }, + ]; + const flowDraftKeys = new Map([[newTaskFlowKey(draftRoute), "new-task:typed"]]); + const readFlowDraftKey = (flowKey: string) => flowDraftKeys.get(flowKey) ?? null; + + it("picks the added project for the draft whose chooser opened Add project", () => { + expect(chooserDraftKey([home, draftRoute, chooser, ...addProject], readFlowDraftKey)).toBe( + "new-task:typed", + ); + const savedChooser = { ...chooser, params: { draftId: "new-task:saved" } }; + expect(chooserDraftKey([home, savedChooser, ...addProject], readFlowDraftKey)).toBe( + "new-task:saved", + ); + }); + + it("picks no draft when Add project opened outside the chooser", () => { + expect(chooserDraftKey([home, draftRoute, ...addProject], readFlowDraftKey)).toBeNull(); + }); +}); diff --git a/apps/mobile/src/features/projects/AddProjectScreen.logic.ts b/apps/mobile/src/features/projects/AddProjectScreen.logic.ts index 4d1f199e63612..a294d87ad6a9e 100644 --- a/apps/mobile/src/features/projects/AddProjectScreen.logic.ts +++ b/apps/mobile/src/features/projects/AddProjectScreen.logic.ts @@ -3,6 +3,9 @@ import type { EnvironmentConnectionPhase } from "@t3tools/client-runtime/connect import { type EnvironmentId, FilesystemBrowseError } from "@t3tools/contracts"; import * as Schema from "effect/Schema"; +import { newTaskFlowKey } from "../threads/new-task-flow-state"; +import { isDraftThreadRoute, type NewTaskDraftRouteParams } from "../threads/thread-route-state"; + const isFilesystemBrowseError = Schema.is(FilesystemBrowseError); /** Clone destinations may name folders that do not exist yet; cloning creates them. */ @@ -40,3 +43,32 @@ export function resolveAddProjectEnvironment< ) ?? null ); } + +interface StackRoute { + readonly key: string; + readonly name: string; + readonly params?: object; +} + +const firstParam = (value: string | string[] | undefined) => + Array.isArray(value) ? value[0] : value; + +/** + * The draft whose project chooser opened Add project, so the added project is picked for it as + * choosing one in the chooser is. Null when Add project opened from anywhere else. + */ +export function chooserDraftKey( + routes: ReadonlyArray, + readFlowDraftKey: (flowKey: string) => string | null, +): string | null { + const chooserIndex = routes.findLastIndex((route) => !route.name.startsWith("AddProject")); + const chooser = routes[chooserIndex]; + if (chooser?.name !== "NewTaskProject") return null; + const savedDraftId = firstParam((chooser.params as { draftId?: string | string[] })?.draftId); + if (savedDraftId !== undefined) return savedDraftId; + const draftRoute = routes[chooserIndex - 1]; + if (draftRoute === undefined || !isDraftThreadRoute(draftRoute)) return null; + const flowKey = newTaskFlowKey(draftRoute); + const draft = (draftRoute.params as { draft: NewTaskDraftRouteParams }).draft; + return (flowKey && readFlowDraftKey(flowKey)) ?? firstParam(draft.draftId) ?? null; +} diff --git a/apps/mobile/src/features/projects/AddProjectScreen.tsx b/apps/mobile/src/features/projects/AddProjectScreen.tsx index 8de3c67a1825c..4a5ae565dc74c 100644 --- a/apps/mobile/src/features/projects/AddProjectScreen.tsx +++ b/apps/mobile/src/features/projects/AddProjectScreen.tsx @@ -102,11 +102,14 @@ import { useSavedRemoteConnections, } from "../../state/use-remote-environment-registry"; import { + chooserDraftKey, isMissingCloneParentBrowseFailure, resolveAddProjectEnvironment, } from "./AddProjectScreen.logic"; +import { readNewTaskFlowState } from "../threads/new-task-flow-state"; import { createNewTaskDraft, + retargetSavedNewTaskDraft, setComposerDraftText, waitForComposerDraftsLoaded, } from "../../state/use-composer-drafts"; @@ -755,7 +758,7 @@ function getActiveRoute(navigation: { function useOpenNewTaskDraft() { const navigation = useNavigation>(); const selectDetail = useSelectWorkspaceDetail(); - return ( + return async ( params: { environmentId: EnvironmentId; projectId: ProjectId; @@ -765,16 +768,35 @@ function useOpenNewTaskDraft() { }, originRoute: NavigationState["routes"][number] | undefined, ) => { - const activeRoute = getActiveRoute(navigation); - // A warm link can change the task without replacing its native route key. - if ( - !originRoute || - activeRoute?.key !== originRoute.key || - activeRoute.name !== originRoute.name || - activeRoute.params !== originRoute.params - ) - return; - selectDetail({ name: "Thread", params: { draft: params } }); + const isStillOnOrigin = () => { + const activeRoute = getActiveRoute(navigation); + // A warm link can change the task without replacing its native route key. + return ( + originRoute !== undefined && + activeRoute?.key === originRoute.key && + activeRoute.name === originRoute.name && + activeRoute.params === originRoute.params + ); + }; + if (!isStillOnOrigin()) return; + const chooserDraft = + params.draftId === undefined + ? chooserDraftKey( + navigation.getState()?.routes ?? [], + (flowKey) => readNewTaskFlowState(flowKey).draftKey, + ) + : null; + const carried = + chooserDraft !== null && + (await retargetSavedNewTaskDraft(chooserDraft, { + environmentId: params.environmentId, + projectId: params.projectId, + }).catch(() => false)); + if (!isStillOnOrigin()) return; + selectDetail({ + name: "Thread", + params: { draft: carried ? { ...params, draftId: chooserDraft } : params }, + }); }; } @@ -832,7 +854,7 @@ function useOpenExistingProject(environment: EnvironmentOption | null) { ? existing.title : m(msg("{title} is still archived. Try again later.", { title: existing.title })), ); - openNewTaskDraft( + void openNewTaskDraft( { environmentId: existing.environmentId, projectId: existing.id, @@ -912,7 +934,7 @@ function useCreateProject(environment: EnvironmentOption | null) { ); return result; } - openNewTaskDraft( + void openNewTaskDraft( { environmentId: environment.environmentId, projectId, @@ -1306,7 +1328,7 @@ export function AddProjectNewScreen(props: { readonly environmentId?: string | s ); return; } - openNewTaskDraft( + void openNewTaskDraft( { environmentId: environment.environmentId, projectId, @@ -1627,7 +1649,7 @@ export function AddProjectDestinationScreen(props: { ), ); } else { - openNewTaskDraft( + void openNewTaskDraft( { environmentId: environment.environmentId, projectId, diff --git a/apps/web/src/commandPaletteBus.ts b/apps/web/src/commandPaletteBus.ts index 2766f6db6b391..4e2ab43931380 100644 --- a/apps/web/src/commandPaletteBus.ts +++ b/apps/web/src/commandPaletteBus.ts @@ -1,5 +1,6 @@ import type { EnvironmentId, PullRequestLinkedThreadsResult } from "@t3tools/contracts"; +import type { DraftId } from "./composerDraftStore"; import { dispatchCommandPalette, isCommandPaletteMounted } from "./commandPaletteStore"; export interface CommandPaletteLinkedThreads { @@ -9,6 +10,8 @@ export interface CommandPaletteLinkedThreads { export interface CommandPaletteOpenDetail { readonly open?: "add-project" | "new-thread-in"; + /** With add-project: the draft the new project is picked for. */ + readonly draftId?: DraftId | null; readonly query?: string; readonly linkedThreads?: CommandPaletteLinkedThreads; } @@ -20,7 +23,10 @@ export function openCommandPalette(detail: CommandPaletteOpenDetail = {}): void if (detail.open === "new-thread-in") { dispatchCommandPalette({ _tag: "OpenNewThreadIn" }); } else if (detail.open === "add-project") { - dispatchCommandPalette({ _tag: "OpenAddProject" }); + dispatchCommandPalette({ + _tag: "OpenAddProject", + ...(detail.draftId ? { draftId: detail.draftId } : {}), + }); } else if (detail.query !== undefined) { dispatchCommandPalette({ _tag: "OpenSearch", diff --git a/apps/web/src/components/CommandPalette.logic.ts b/apps/web/src/components/CommandPalette.logic.ts index 8fc6f18fa4bd2..964a8557dd4d6 100644 --- a/apps/web/src/components/CommandPalette.logic.ts +++ b/apps/web/src/components/CommandPalette.logic.ts @@ -12,6 +12,7 @@ import { } from "@t3tools/shared/paletteSearch"; import { threadSearchSubject } from "@t3tools/client-runtime/state/thread-search"; import type { CommandPaletteLinkedThreads } from "../commandPaletteBus"; +import type { DraftId } from "../composerDraftStore"; import { addProjectRemoteSourceLabel, addProjectRemoteSourcePathHint, @@ -80,7 +81,12 @@ export function browseInputEndPaddingClass(input: { export type SearchOverlayMode = "command" | "files" | "content"; export type CommandPaletteOpenIntent = - | { readonly kind: "add-project" | "new-thread-in" | "change-theme" } + | { readonly kind: "new-thread-in" | "change-theme" } + | { + readonly kind: "add-project"; + /** The draft a project is being picked for; one with user content moves to it. */ + readonly draftId?: DraftId; + } | { readonly kind: "search"; readonly query: string; @@ -106,7 +112,7 @@ export type CommandPaletteUiAction = readonly query: string; readonly linkedThreads?: CommandPaletteLinkedThreads; } - | { readonly _tag: "OpenAddProject" } + | { readonly _tag: "OpenAddProject"; readonly draftId?: DraftId } | { readonly _tag: "OpenNewThreadIn" } | { readonly _tag: "OpenChangeTheme" } | { @@ -161,7 +167,10 @@ export function reduceCommandPaletteUiState( ...(action.linkedThreads ? { linkedThreads: action.linkedThreads } : {}), }); case "OpenAddProject": - return openWithIntent({ kind: "add-project" }); + return openWithIntent({ + kind: "add-project", + ...(action.draftId ? { draftId: action.draftId } : {}), + }); case "OpenNewThreadIn": return openWithIntent({ kind: "new-thread-in" }); case "OpenChangeTheme": diff --git a/apps/web/src/components/CommandPalette.tsx b/apps/web/src/components/CommandPalette.tsx index 745b96bcdb549..52803134a54a0 100644 --- a/apps/web/src/components/CommandPalette.tsx +++ b/apps/web/src/components/CommandPalette.tsx @@ -57,7 +57,9 @@ import { SourceControlProviderKind, PRIMARY_LOCAL_ENVIRONMENT_ID, resolveEnvironmentMachineKind, + type ScopedProjectRef, } from "@t3tools/contracts"; +import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell"; import { useLocation, useNavigate } from "@tanstack/react-router"; import { ArrowLeftIcon, @@ -106,6 +108,7 @@ import { useDesktopLocalBootstraps } from "../connection/useDesktopLocalBootstra import { useHandleNewThread } from "../hooks/useHandleNewThread"; import { useOpenPanelPullRequestUrl } from "../hooks/useOpenPanelPullRequestUrl"; import { copyThreadReference } from "../lib/copyThreadReference"; +import { moveDraftToProject } from "../lib/moveDraftToProject"; import { queueWorkspaceFocusFromPalette, restoreWorkspaceFocusFromPalette, @@ -583,7 +586,25 @@ function OpenCommandPaletteDialog(props: { const [isCreatingNewProject, setIsCreatingNewProject] = useState(false); // State lags a render behind, so a repeated Enter could start a second create. const newProjectSubmittingRef = useRef(false); - const createNewProject = useNewProject(); + // "Add project" from a draft's project picker picks the new project for that draft. + const [addProjectDraftId] = useState(() => + props.openIntent?.kind === "add-project" ? (props.openIntent.draftId ?? null) : null, + ); + const moveDraftToAddedProject = async (project: EnvironmentProject): Promise => { + if (addProjectDraftId === null || !moveDraftToProject(addProjectDraftId, project)) { + return false; + } + await navigate({ to: "/draft/$draftId", params: { draftId: addProjectDraftId } }); + return true; + }; + const openAddedProject = async (projectRef: ScopedProjectRef): Promise => { + // A moved draft is keyed from the project record, so wait for it to reach this client. + const project = + addProjectDraftId === null ? null : await waitForProject(projectRef, 3_000).catch(() => null); + if (project !== null && (await moveDraftToAddedProject(project))) return; + await handleNewThread(projectRef); + }; + const createNewProject = useNewProject(openAddedProject); const cloneLookupGeneration = useRef(0); const [isRemoteProjectLookingUp, setIsRemoteProjectLookingUp] = useState(false); const [isRemoteProjectCloning, setIsRemoteProjectCloning] = useState(false); @@ -2051,6 +2072,10 @@ function OpenCommandPaletteDialog(props: { input: { projectId: existing.id, archived: false }, }).then((result) => reportProjectFailure(gt("Failed to unarchive project"), result)); } + if (await moveDraftToAddedProject(existing)) { + setOpen(false); + return; + } const latestThread = getLatestThreadForProject( threads.filter((thread) => thread.environmentId === existing.environmentId), existing.id, @@ -2119,7 +2144,7 @@ function OpenCommandPaletteDialog(props: { } const navigationResult = await settlePromise(() => - handleNewThread(scopeProjectRef(input.environmentId, projectId)), + openAddedProject(scopeProjectRef(input.environmentId, projectId)), ); if (navigationResult._tag === "Failure") { const error = squashAtomCommandFailure(navigationResult); @@ -2384,7 +2409,7 @@ function OpenCommandPaletteDialog(props: { startResult.value.projectId, ); await waitForProject(projectRef, 3_000).catch(() => null); - const navigationResult = await settlePromise(() => handleNewThread(projectRef)); + const navigationResult = await settlePromise(() => openAddedProject(projectRef)); if (navigationResult._tag === "Failure") { const error = squashAtomCommandFailure(navigationResult); toastManager.add( diff --git a/apps/web/src/components/chat/DraftHeroHeadline.tsx b/apps/web/src/components/chat/DraftHeroHeadline.tsx index 8f55d1ca51ba0..c01ad1ee78fc5 100644 --- a/apps/web/src/components/chat/DraftHeroHeadline.tsx +++ b/apps/web/src/components/chat/DraftHeroHeadline.tsx @@ -1,5 +1,5 @@ import type { DraftId } from "~/composerDraftStore"; -import { composerDraftHasUserContent, useComposerDraftStore } from "~/composerDraftStore"; +import { useComposerDraftStore } from "~/composerDraftStore"; import { resolveEnvironmentMachineKind, type ScopedProjectRef } from "@t3tools/contracts"; import { scopedProjectKey, scopeProjectRef } from "@t3tools/client-runtime/environment"; import { isScratchProject } from "@t3tools/client-runtime/state/projects"; @@ -13,16 +13,11 @@ import { shortcutLabelForCommand } from "~/keybindings"; import { primaryServerKeybindingsAtom } from "~/state/server"; import { useNewThreadHandler } from "~/hooks/useHandleNewThread"; import { useOrderWhileOpen } from "~/hooks/useOrderWhileOpen"; +import { moveDraftToProject } from "~/lib/moveDraftToProject"; import { useProjectPin } from "~/hooks/useProjectGroupUpdate"; import { useScratchProject } from "~/hooks/useScratchProject"; import { isTriagePrompt } from "@t3tools/shared/triagePrompt"; -import { useClientSettings } from "~/hooks/useSettings"; -import { seedDraftModelSelection } from "~/lib/seedDraftModelSelection"; -import { - deriveLogicalProjectKeyFromSettings, - pickableProjectGroups, - selectProjectGroupingSettings, -} from "@t3tools/client-runtime/state/project-grouping"; +import { pickableProjectGroups } from "@t3tools/client-runtime/state/project-grouping"; import { buildSidebarProjectPickerEntries, projectGroupsSpanEnvironments, @@ -71,16 +66,11 @@ export function DraftHeroHeadline({ const projects = useProjects(); const { environments } = useEnvironments(); const primaryEnvironmentId = usePrimaryEnvironmentId(); - const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings); - const setLogicalProjectDraftThreadId = useComposerDraftStore( - (store) => store.setLogicalProjectDraftThreadId, - ); - const getComposerDraft = useComposerDraftStore((store) => store.getComposerDraft); // A boolean, so typing in a draft does not re-render the hero. const isTriageDraftPrompt = useComposerDraftStore((store) => draftId ? isTriagePrompt(store.getComposerDraft(draftId)?.prompt ?? "") : false, ); - const openAddProject = () => openCommandPalette({ open: "add-project" }); + const openAddProject = () => openCommandPalette({ open: "add-project", draftId }); const { scratchEnvironmentId, scratchWorkspaceRootFor, openScratchProject } = useScratchProject(); const openProjectDraft = useNewThreadHandler(); const keybindings = useAtomValue(primaryServerKeybindingsAtom); @@ -172,19 +162,14 @@ export function DraftHeroHeadline({ ? `${session.environmentId}:${session.projectId}:${session.logicalProjectKey}` : null; }; - // Retargeting an empty draft would overwrite the project's draft and strand browser tabs. - const selectProject = (project: (typeof projects)[number], logicalProjectKey: string) => { + const selectProject = (project: (typeof projects)[number]) => { if (!draftId) { return; } pendingScratchRef.current = null; - const projectRef = scopeProjectRef(project.environmentId, project.id); - if (!composerDraftHasUserContent(getComposerDraft(draftId))) { - void openProjectDraft(projectRef); - return; + if (!moveDraftToProject(draftId, project)) { + void openProjectDraft(scopeProjectRef(project.environmentId, project.id)); } - setLogicalProjectDraftThreadId(logicalProjectKey, projectRef, draftId); - seedDraftModelSelection(draftId, projectRef); }; const startScratch = async (): Promise => { if (scratchTargetEnvironmentId === null || isScratchDraft) { @@ -198,7 +183,7 @@ export function DraftHeroHeadline({ return false; } pendingScratchRef.current = null; - selectProject(project, deriveLogicalProjectKeyFromSettings(project, projectGroupingSettings)); + selectProject(project); return true; }; @@ -229,7 +214,7 @@ export function DraftHeroHeadline({ if (!entry || item.value === activeProjectKey) { return; } - selectProject(entry.targetProject, entry.group.projectKey); + selectProject(entry.targetProject); }} > diff --git a/apps/web/src/hooks/useNewProject.ts b/apps/web/src/hooks/useNewProject.ts index f542435f55552..a4594ad913559 100644 --- a/apps/web/src/hooks/useNewProject.ts +++ b/apps/web/src/hooks/useNewProject.ts @@ -7,7 +7,7 @@ import { isAtomCommandInterrupted, squashAtomCommandFailure, } from "@t3tools/client-runtime/state/runtime"; -import type { EnvironmentId } from "@t3tools/contracts"; +import type { EnvironmentId, ScopedProjectRef } from "@t3tools/contracts"; import { msg } from "gt-react"; import { stackedThreadToast, toastManager } from "~/components/ui/toast"; @@ -16,7 +16,6 @@ import { waitForProject } from "~/state/entities"; import { projectEnvironment } from "~/state/projects"; import { sourceControlEnvironment } from "~/state/sourceControl"; import { useAtomCommand } from "~/state/use-atom-command"; -import { useNewThreadHandler } from "./useHandleNewThread"; import { suggestAppAccessForRemote } from "../components/sourceControlAppAccessToast"; function errorMessage(error: unknown): string { @@ -25,12 +24,11 @@ function errorMessage(error: unknown): string { : m(msg("An error occurred.")); } -export function useNewProject() { +export function useNewProject(openProject: (projectRef: ScopedProjectRef) => Promise) { const createNew = useAtomCommand(projectEnvironment.createNew, { reportFailure: false }); const publishRepository = useAtomCommand(sourceControlEnvironment.publishRepository, { reportFailure: false, }); - const handleNewThread = useNewThreadHandler(); const publishNewRepository = async (input: { readonly environmentId: EnvironmentId; @@ -141,7 +139,7 @@ export function useNewProject() { return null; }); if (project === null) return true; - await handleNewThread(projectRef).catch((error: unknown) => { + await openProject(projectRef).catch((error: unknown) => { toastManager.add( stackedThreadToast({ type: "error", diff --git a/apps/web/src/lib/moveDraftToProject.test.ts b/apps/web/src/lib/moveDraftToProject.test.ts new file mode 100644 index 0000000000000..67ee5c6dd1edc --- /dev/null +++ b/apps/web/src/lib/moveDraftToProject.test.ts @@ -0,0 +1,59 @@ +import { scopeProjectRef } from "@t3tools/client-runtime/environment"; +import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell"; +import { EnvironmentId, ProjectId } from "@t3tools/contracts"; +import { beforeEach, describe, expect, it } from "vite-plus/test"; + +import { DraftId, useComposerDraftStore } from "../composerDraftStore"; +import { moveDraftToProject } from "./moveDraftToProject"; + +const environmentId = EnvironmentId.make("environment-local"); +const draftId = DraftId.make("draft-1"); + +function makeProject(name: string): EnvironmentProject { + return { + id: ProjectId.make(name), + environmentId, + title: name, + workspaceRoot: `/work/${name}`, + repositoryIdentity: null, + defaultModelSelection: null, + createdAt: "2026-03-01T00:00:00.000Z", + updatedAt: "2026-03-01T00:00:00.000Z", + scripts: [], + }; +} + +const current = makeProject("current"); +const added = makeProject("added"); +const currentRef = scopeProjectRef(environmentId, current.id); +const addedRef = scopeProjectRef(environmentId, added.id); + +beforeEach(() => { + useComposerDraftStore.setState({ + draftsByThreadKey: {}, + draftThreadsByThreadKey: {}, + logicalProjectDraftThreadKeyByLogicalProjectKey: {}, + }); + useComposerDraftStore.getState().setProjectDraftThreadId(currentRef, draftId); +}); + +describe("moveDraftToProject", () => { + it("moves a draft the user wrote in, leaving no draft behind in its old project", () => { + const store = useComposerDraftStore.getState(); + store.setPrompt(draftId, "Plan the next project"); + + expect(moveDraftToProject(draftId, added)).toBe(true); + + expect(store.getDraftSessionByProjectRef(addedRef)?.draftId).toBe(draftId); + expect(store.getDraftSessionByProjectRef(currentRef)).toBeNull(); + expect(store.getComposerDraft(draftId)?.prompt).toBe("Plan the next project"); + }); + + it("leaves an empty draft in its project", () => { + expect(moveDraftToProject(draftId, added)).toBe(false); + + const store = useComposerDraftStore.getState(); + expect(store.getDraftSessionByProjectRef(currentRef)?.draftId).toBe(draftId); + expect(store.getDraftSessionByProjectRef(addedRef)).toBeNull(); + }); +}); diff --git a/apps/web/src/lib/moveDraftToProject.ts b/apps/web/src/lib/moveDraftToProject.ts new file mode 100644 index 0000000000000..290897b305273 --- /dev/null +++ b/apps/web/src/lib/moveDraftToProject.ts @@ -0,0 +1,42 @@ +import { scopeProjectRef } from "@t3tools/client-runtime/environment"; +import { + deriveLogicalProjectKeyFromSettings, + selectProjectGroupingSettings, +} from "@t3tools/client-runtime/state/project-grouping"; +import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell"; + +import { + composerDraftHasUserContent, + type DraftId, + useComposerDraftStore, +} from "../composerDraftStore"; +import { getClientSettings } from "../hooks/useSettings"; +import { seedDraftModelSelection } from "./seedDraftModelSelection"; + +/** + * Moves an unsent draft the user wrote in to `project`, keeping its content. Returns false for an + * empty draft, which the caller should leave alone and open the project's own draft instead: + * moving it would replace that draft and strand browser tabs on it. + */ +export function moveDraftToProject(draftId: DraftId, project: EnvironmentProject): boolean { + const store = useComposerDraftStore.getState(); + const session = store.getDraftSession(draftId); + if ( + session === null || + session.promotedTo != null || + !composerDraftHasUserContent(store.getComposerDraft(draftId)) + ) { + return false; + } + const projectRef = scopeProjectRef(project.environmentId, project.id); + store.setLogicalProjectDraftThreadId( + deriveLogicalProjectKeyFromSettings( + project, + selectProjectGroupingSettings(getClientSettings()), + ), + projectRef, + draftId, + ); + seedDraftModelSelection(draftId, projectRef); + return true; +} diff --git a/scripts/scenarios/add-project-takes-the-draft.e2e.ts b/scripts/scenarios/add-project-takes-the-draft.e2e.ts new file mode 100644 index 0000000000000..b6d79a2ff3a53 --- /dev/null +++ b/scripts/scenarios/add-project-takes-the-draft.e2e.ts @@ -0,0 +1,29 @@ +import { expect } from "e2e"; + +import { test, WEB } from "./t3.ts"; + +test( + "A project added from the draft's project picker takes the draft's prompt with it", + WEB, + async ({ t3, app, screen, browser }) => { + const workspace = await t3.project("demo", { "next/README.md": "" }); + await t3.open(); + + const composer = screen.getByRole("textbox"); + await composer.fill("Plan the next project"); + // The draft's project picker has no accessible name of its own. + const projectPicker = browser.locator("[data-draft-project-trigger]"); + await projectPicker.tap(); + await screen.getByRole("option", "Add project").tap(); + await screen.getByText("Local folder").tap(); + await screen.getByRole("combobox").fill(`${workspace}/next`); + await browser.keyboard.press("Enter"); + + await expect(projectPicker).toHaveText("next"); + await app.screenshot("after-add"); + await expect(composer).toContainText("Plan the next project"); + await expect( + screen.getByRole("button", "Plan the next project, Unsent draft", { exact: false }), + ).toBeHidden(); + }, +); From 2891419b9301d89109c86814aeae639428705508 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Wed, 25 Nov 2026 16:35:57 +0100 Subject: [PATCH 053/238] fix(web): localize terminal excerpt line ranges (#42886) Co-authored-by: Julius Marminge --- .../chat/ComposerPendingTerminalContexts.tsx | 8 +----- ...TerminalContextInlineChip.browser.test.tsx | 27 +++++++++++++++++++ .../chat/TerminalContextInlineChip.tsx | 7 +++-- .../chat/UserMessageContextChips.tsx | 1 - apps/web/src/i18n/translations/de.json | 2 ++ apps/web/src/i18n/translations/en.json | 2 ++ apps/web/src/i18n/translations/es.json | 2 ++ apps/web/src/i18n/translations/fr.json | 2 ++ apps/web/src/i18n/translations/ja.json | 2 ++ apps/web/src/i18n/translations/ko.json | 2 ++ apps/web/src/i18n/translations/pt-BR.json | 2 ++ apps/web/src/i18n/translations/ru.json | 2 ++ apps/web/src/i18n/translations/sv.json | 2 ++ apps/web/src/i18n/translations/zh.json | 2 ++ 14 files changed, 53 insertions(+), 10 deletions(-) create mode 100644 apps/web/src/components/chat/TerminalContextInlineChip.browser.test.tsx diff --git a/apps/web/src/components/chat/ComposerPendingTerminalContexts.tsx b/apps/web/src/components/chat/ComposerPendingTerminalContexts.tsx index 0e2aa6e27ad96..196b5b37be832 100644 --- a/apps/web/src/components/chat/ComposerPendingTerminalContexts.tsx +++ b/apps/web/src/components/chat/ComposerPendingTerminalContexts.tsx @@ -1,8 +1,4 @@ -import { - type TerminalContextDraft, - formatTerminalContextLabel, - isTerminalContextExpired, -} from "~/lib/terminalContext"; +import { type TerminalContextDraft, isTerminalContextExpired } from "~/lib/terminalContext"; import type { ContextPresentationCapability } from "../contextPresentationRegistry"; import { TerminalContextInlineChip } from "./TerminalContextInlineChip"; @@ -15,12 +11,10 @@ export function ComposerPendingTerminalContextChip({ context, detailsMode, }: ComposerPendingTerminalContextChipProps) { - const label = formatTerminalContextLabel(context); const expired = isTerminalContextExpired(context); return ( { + initializeI18n(() => {}); + const translations = await getTranslationsSnapshot("ja"); + await using screen = await render( + + + , + ); + + await expect.element(screen.getByText(label, { exact: true })).toBeVisible(); +}); diff --git a/apps/web/src/components/chat/TerminalContextInlineChip.tsx b/apps/web/src/components/chat/TerminalContextInlineChip.tsx index ea2b353b5be03..db048410f9a97 100644 --- a/apps/web/src/components/chat/TerminalContextInlineChip.tsx +++ b/apps/web/src/components/chat/TerminalContextInlineChip.tsx @@ -5,7 +5,6 @@ import type { ContextPresentationCapability } from "../contextPresentationRegist import { ContextChipPopover, ContextChipShell } from "../contextChipParts"; interface TerminalContextInlineChipProps { - label: string; terminalLabel: string; lineStart: number; lineEnd: number; @@ -15,8 +14,12 @@ interface TerminalContextInlineChipProps { } export function TerminalContextInlineChip(props: TerminalContextInlineChipProps) { - const { label, terminalLabel, lineStart, lineEnd, text, detailsMode, expired = false } = props; + const { terminalLabel, lineStart, lineEnd, text, detailsMode, expired = false } = props; const gt = useGT(); + const label = + lineStart === lineEnd + ? gt("{terminalLabel} line {lineStart}", { terminalLabel, lineStart }) + : gt("{terminalLabel} lines {lineStart}-{lineEnd}", { terminalLabel, lineStart, lineEnd }); if (!expired && text.length > 0 && detailsMode === "popover") { return ( diff --git a/apps/web/src/components/chat/UserMessageContextChips.tsx b/apps/web/src/components/chat/UserMessageContextChips.tsx index 56363dfafb3f4..891bce5296265 100644 --- a/apps/web/src/components/chat/UserMessageContextChips.tsx +++ b/apps/web/src/components/chat/UserMessageContextChips.tsx @@ -444,7 +444,6 @@ const userMessageContextPresentationRegistry = createContextPresentationRegistry record.kind === "terminal" ? ( Date: Wed, 25 Nov 2026 16:37:03 +0100 Subject: [PATCH 054/238] fix(server): separate nested EPUB list items in attachment text (#42891) Co-authored-by: Simone <185146821+Lucenx9@users.noreply.github.com> Co-authored-by: Julius Marminge --- .../server/src/provider/documentTextWorker.ts | 30 +++++++++++++++++-- .../src/provider/userInputAttachments.test.ts | 6 +++- 2 files changed, 32 insertions(+), 4 deletions(-) diff --git a/apps/server/src/provider/documentTextWorker.ts b/apps/server/src/provider/documentTextWorker.ts index 4c4504a8b6024..0e9604c300bed 100644 --- a/apps/server/src/provider/documentTextWorker.ts +++ b/apps/server/src/provider/documentTextWorker.ts @@ -12,7 +12,13 @@ const MAX_EXPANDED = 32 * 1024 * 1024; const MAX_OUTPUT = 1_000_000; const CELL_START = Symbol("cell-start"); const CELL_END = Symbol("cell-end"); -type TextPart = string | typeof CELL_START | typeof CELL_END | { fallback: string }; +const LINE_START = Symbol("line-start"); +type TextPart = + | string + | typeof CELL_START + | typeof CELL_END + | typeof LINE_START + | { fallback: string }; const TRUNCATED = "\n\n[Extracted text truncated at document extraction limits.]"; // Parts the document never displays: the XHTML head, tracked deletions and moves, field codes, @@ -257,6 +263,7 @@ function* paragraphs(node: XmlNode): Generator { yield* text(child); yield "\n"; } else { + if (node.name === "li" && ["ol", "ul"].includes(child.name)) yield LINE_START; yield* paragraphs(child); if (["li", "div", "section", "dt", "dd"].includes(child.name)) yield "\n"; } @@ -946,16 +953,24 @@ async function* document(path: string, extension: string): AsyncGenerator { let result = ""; let remaining = MAX_OUTPUT; let cellDepth = 0; let started = false; let space = false; + let midLine = false; let truncated = false; try { // Charge raw text before normalization so repeated whitespace also exhausts the budget. - for await (const part of document(path, extension)) { + for await (let part of document(path, extension)) { if (part === CELL_START) { if (cellDepth++ === 0) { started = false; @@ -968,6 +983,11 @@ export async function extractDocumentText(path: string, extension: string): Prom if (cellDepth > 0 && started) space = true; continue; } + if (part === LINE_START) { + // A nested list starts its own line unless its parent item's text already ended one. + if (!midLine) continue; + part = "\n"; + } if (typeof part !== "string" && started) continue; const raw = typeof part === "string" ? part : part.fallback; let value = raw.slice(0, remaining).replaceAll("\0", ""); @@ -978,9 +998,13 @@ export async function extractDocumentText(path: string, extension: string): Prom if (trimmed) { result += (started && (space || value.startsWith(" ")) ? " " : "") + trimmed; started = true; + midLine = true; } space = value.endsWith(" ") || (!value && space); - } else result += value; + } else { + result += value; + midLine = endsMidLine(value) ?? midLine; + } if (remaining === 0) throw new Truncation("Output budget"); } } catch (error) { diff --git a/apps/server/src/provider/userInputAttachments.test.ts b/apps/server/src/provider/userInputAttachments.test.ts index ea61fab1ce990..c7f3a2e9a1cc7 100644 --- a/apps/server/src/provider/userInputAttachments.test.ts +++ b/apps/server/src/provider/userInputAttachments.test.ts @@ -1497,7 +1497,8 @@ describe("question answer paths", () => { "OEBPS/a.xhtml": '

    Last chapter

    Price 10 8 old

    ', "OEBPS/b.xhtml": - 'My Novel

    First chapter

    Larkspur

    Direct div
    Direct section
  • Direct item emphasis trailing
  • Account: A
    Balance: 731Currency: USD
    HeadingTotal
    Important value731
    Before
    Inner
    After
    Neighbor
    Port
    443
    Timeout
    30 seconds

    Prefixed note

    ', + 'My Novel

    First chapter

    Larkspur

    Direct div
    Direct section
  • Direct item emphasis trailing
  • Account: A
    Balance: 731Currency: USD
    HeadingTotal
    Important value731
    Before
    Inner
    After
    Neighbor
    Port
    443
    Timeout
    30 seconds

    Prefixed note

    1. Before boarding
      • Check passports
        1. Compare names
      • Confirm gate
    2. Board promptly
    3. Before landing

      • Collect bags
    ' + + "
    1. Indented\n
      • Alpha
    ", "OEBPS/c.xhtml": '

    Root hidden

    ', }, expected: [ @@ -1513,6 +1514,9 @@ describe("question answer paths", () => { "Before Inner After\tNeighbor", "Port\n443\nTimeout\n30 seconds", "Findable note\nDecorative note\nPrefixed note", + "Before boarding\nCheck passports\nCompare names\n\nConfirm gate\n\nBoard promptly", + "Before landing\nCollect bags", + "Indented\n Alpha", "## Chapter 2", "Last chapter", "Price 10 8 old", From 0f55a0dc37aa0e79846106f9cf9f4df88cdb8b7c Mon Sep 17 00:00:00 2001 From: Victor Date: Wed, 25 Nov 2026 09:49:26 -0600 Subject: [PATCH 055/238] fix(web): empty files and folders in archive previews show 0 bytes instead of 1 KB (#42900) Co-authored-by: Julius Marminge --- 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 + .../AttachmentFilePreview.browser.test.tsx | 27 +++++++++++++++++++ .../src/state/attachments.test.ts | 2 ++ .../client-runtime/src/state/attachments.ts | 1 + 13 files changed, 40 insertions(+) diff --git a/apps/mobile/src/i18n/translations/de.json b/apps/mobile/src/i18n/translations/de.json index 3b62045baa01e..9efa66206a9cc 100644 --- a/apps/mobile/src/i18n/translations/de.json +++ b/apps/mobile/src/i18n/translations/de.json @@ -686,6 +686,7 @@ "56b4ff3993c93eca": "{host} hat eine inkompatible Serverkonfiguration gesendet.", "368c4d4f99c66bfb": "Aktualisiere Client und Server auf kompatible Versionen.", "e5fd422e445391fc": "Upload fehlgeschlagen. Zum Wiederholen tippen.", + "13b14784f8707ddd": "0 Byte", "b2bc6bd92ea24e5c": "{size} MB", "88f84178edbb7f57": "{size} KB", "5a78fd0a1d8e9945": "{count} MB", diff --git a/apps/mobile/src/i18n/translations/en.json b/apps/mobile/src/i18n/translations/en.json index 2e482d69aa7f4..223ace0c6dd48 100644 --- a/apps/mobile/src/i18n/translations/en.json +++ b/apps/mobile/src/i18n/translations/en.json @@ -686,6 +686,7 @@ "56b4ff3993c93eca": "{host} sent an incompatible server configuration.", "368c4d4f99c66bfb": "Update the client and server to compatible versions.", "e5fd422e445391fc": "Upload failed. Tap to retry.", + "13b14784f8707ddd": "0 bytes", "b2bc6bd92ea24e5c": "{size} MB", "88f84178edbb7f57": "{size} KB", "5a78fd0a1d8e9945": "{count} MB", diff --git a/apps/mobile/src/i18n/translations/es.json b/apps/mobile/src/i18n/translations/es.json index 9f513dfccd516..26a58f6c58f64 100644 --- a/apps/mobile/src/i18n/translations/es.json +++ b/apps/mobile/src/i18n/translations/es.json @@ -686,6 +686,7 @@ "56b4ff3993c93eca": "{host} envió una configuración del servidor incompatible.", "368c4d4f99c66bfb": "Actualiza el cliente y el servidor a versiones compatibles.", "e5fd422e445391fc": "Error al subir. Toca para reintentar.", + "13b14784f8707ddd": "0 bytes", "b2bc6bd92ea24e5c": "{size} MB", "88f84178edbb7f57": "{size} KB", "5a78fd0a1d8e9945": "{count} MB", diff --git a/apps/mobile/src/i18n/translations/fr.json b/apps/mobile/src/i18n/translations/fr.json index 63a62d7f03188..bf46c964394e1 100644 --- a/apps/mobile/src/i18n/translations/fr.json +++ b/apps/mobile/src/i18n/translations/fr.json @@ -686,6 +686,7 @@ "56b4ff3993c93eca": "{host} a envoyé une configuration de serveur incompatible.", "368c4d4f99c66bfb": "Mettez à jour le client et le serveur vers des versions compatibles.", "e5fd422e445391fc": "Échec de l’envoi. Touchez pour réessayer.", + "13b14784f8707ddd": "0 octet", "b2bc6bd92ea24e5c": "{size} Mo", "88f84178edbb7f57": "{size} Ko", "5a78fd0a1d8e9945": "{count} Mo", diff --git a/apps/mobile/src/i18n/translations/ja.json b/apps/mobile/src/i18n/translations/ja.json index f0c24995414d9..480c4e959f147 100644 --- a/apps/mobile/src/i18n/translations/ja.json +++ b/apps/mobile/src/i18n/translations/ja.json @@ -686,6 +686,7 @@ "56b4ff3993c93eca": "{host} から互換性のないサーバー設定が送信されました。", "368c4d4f99c66bfb": "クライアントとサーバーを互換性のあるバージョンに更新してください。", "e5fd422e445391fc": "アップロードに失敗しました。タップして再試行してください。", + "13b14784f8707ddd": "0 バイト", "b2bc6bd92ea24e5c": "{size} MB", "88f84178edbb7f57": "{size} KB", "5a78fd0a1d8e9945": "{count} MB", diff --git a/apps/mobile/src/i18n/translations/ko.json b/apps/mobile/src/i18n/translations/ko.json index e0c188e8c878d..34fe2af053545 100644 --- a/apps/mobile/src/i18n/translations/ko.json +++ b/apps/mobile/src/i18n/translations/ko.json @@ -686,6 +686,7 @@ "56b4ff3993c93eca": "{host}에서 호환되지 않는 서버 구성을 보냈습니다.", "368c4d4f99c66bfb": "클라이언트와 서버를 호환되는 버전으로 업데이트하세요.", "e5fd422e445391fc": "업로드에 실패했습니다. 탭하여 다시 시도하세요.", + "13b14784f8707ddd": "0바이트", "b2bc6bd92ea24e5c": "{size}MB", "88f84178edbb7f57": "{size} KB", "5a78fd0a1d8e9945": "{count} MB", diff --git a/apps/mobile/src/i18n/translations/pt-BR.json b/apps/mobile/src/i18n/translations/pt-BR.json index 386b5dc53afbf..72870adc6d774 100644 --- a/apps/mobile/src/i18n/translations/pt-BR.json +++ b/apps/mobile/src/i18n/translations/pt-BR.json @@ -686,6 +686,7 @@ "56b4ff3993c93eca": "{host} enviou uma configuração de servidor incompatível.", "368c4d4f99c66bfb": "Atualize o cliente e o servidor para versões compatíveis.", "e5fd422e445391fc": "Falha no envio. Toque para tentar novamente.", + "13b14784f8707ddd": "0 bytes", "b2bc6bd92ea24e5c": "{size} MB", "88f84178edbb7f57": "{size} KB", "5a78fd0a1d8e9945": "{count} MB", diff --git a/apps/mobile/src/i18n/translations/ru.json b/apps/mobile/src/i18n/translations/ru.json index c3197052b5fa7..7a48ee5eafdd1 100644 --- a/apps/mobile/src/i18n/translations/ru.json +++ b/apps/mobile/src/i18n/translations/ru.json @@ -686,6 +686,7 @@ "56b4ff3993c93eca": "{host} отправил несовместимую конфигурацию сервера.", "368c4d4f99c66bfb": "Обновите клиент и сервер до совместимых версий.", "e5fd422e445391fc": "Ошибка загрузки. Нажмите, чтобы повторить.", + "13b14784f8707ddd": "0 байт", "b2bc6bd92ea24e5c": "{size} МБ", "88f84178edbb7f57": "{size} КБ", "5a78fd0a1d8e9945": "{count} МБ", diff --git a/apps/mobile/src/i18n/translations/sv.json b/apps/mobile/src/i18n/translations/sv.json index fa0454bb9f430..a79f24906759e 100644 --- a/apps/mobile/src/i18n/translations/sv.json +++ b/apps/mobile/src/i18n/translations/sv.json @@ -686,6 +686,7 @@ "56b4ff3993c93eca": "{host} skickade en inkompatibel serverkonfiguration.", "368c4d4f99c66bfb": "Uppdatera klienten och servern till kompatibla versioner.", "e5fd422e445391fc": "Uppladdningen misslyckades. Tryck för att försöka igen.", + "13b14784f8707ddd": "0 byte", "b2bc6bd92ea24e5c": "{size} MB", "88f84178edbb7f57": "{size} kB", "5a78fd0a1d8e9945": "{count} MB", diff --git a/apps/mobile/src/i18n/translations/zh.json b/apps/mobile/src/i18n/translations/zh.json index 5eb155844e938..58c5f8b4e70cd 100644 --- a/apps/mobile/src/i18n/translations/zh.json +++ b/apps/mobile/src/i18n/translations/zh.json @@ -686,6 +686,7 @@ "56b4ff3993c93eca": "{host} 发送了不兼容的服务器配置。", "368c4d4f99c66bfb": "请将客户端和服务器更新到兼容的版本。", "e5fd422e445391fc": "上传失败。点按以重试。", + "13b14784f8707ddd": "0 字节", "b2bc6bd92ea24e5c": "{size} MB", "88f84178edbb7f57": "{size} KB", "5a78fd0a1d8e9945": "{count} MB", diff --git a/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx b/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx index 83da950e44993..0a7dc74c1f691 100644 --- a/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx +++ b/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx @@ -289,6 +289,33 @@ describe("bounded binary previews", () => { } }); + it("shows 0 bytes for empty archive entries and folders", async () => { + const zip = new JSZip(); + zip.file("empty.txt", ""); + zip.folder("empty-dir"); + zip.file("pkg/__init__.py", ""); + zip.file("readme.txt", "hello"); + const bytes = await zip.generateAsync({ type: "arraybuffer" }); + const src = URL.createObjectURL(new Blob([bytes])); + try { + await using screen = await render(); + const rows = () => + [...screen.container.querySelectorAll("tbody tr")].map((row) => + [...row.querySelectorAll("td")].slice(0, 2).map((cell) => cell.textContent?.trim()), + ); + await vi.waitFor(() => { + expect(rows()).toEqual([ + ["empty-dir", "0 bytes"], + ["pkg", "0 bytes"], + ["empty.txt", "0 bytes"], + ["readme.txt", "1 KB"], + ]); + }, 10_000); + } finally { + URL.revokeObjectURL(src); + } + }); + it("uses a PAX size override for the following TAR payload and bounds it", async () => { const archive = (size: string) => { const header = (name: string, size: number, type: string) => { diff --git a/packages/client-runtime/src/state/attachments.test.ts b/packages/client-runtime/src/state/attachments.test.ts index 0860e7fde5eb8..2c26ad67317e3 100644 --- a/packages/client-runtime/src/state/attachments.test.ts +++ b/packages/client-runtime/src/state/attachments.test.ts @@ -145,6 +145,8 @@ describe("verifyPersistedAttachmentUpload", () => { describe("formatAttachmentSize", () => { it.each([ + [0, "0 bytes"], + [1, "1 KB"], [1_047_552, "1023 KB"], [1_047_553, "1.0 MB"], [1_048_575, "1.0 MB"], diff --git a/packages/client-runtime/src/state/attachments.ts b/packages/client-runtime/src/state/attachments.ts index 03494e139f1f6..8bca7348d867b 100644 --- a/packages/client-runtime/src/state/attachments.ts +++ b/packages/client-runtime/src/state/attachments.ts @@ -208,6 +208,7 @@ export function formatAttachmentSize( sizeBytes: number, resolve: MFunctionType = mFallback, ): string { + if (sizeBytes === 0) return resolve(msg("0 bytes")); const kilobytes = Math.max(1, Math.ceil(sizeBytes / 1024)); // Pick the unit after rounding, so 1023.5 KB reads "1.0 MB", not "1024 KB". return kilobytes >= 1024 From 9e385083d6255d4f4a94153ed25533f309f0da16 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 25 Nov 2026 07:52:14 -0800 Subject: [PATCH 056/238] fix(client-runtime): a composer send right after Stop queues instead of failing to steer (#42918) --- .../src/state/use-thread-composer-state.ts | 10 +++- .../src/state/threadWorkflows.test.ts | 59 ++++++++++--------- .../src/state/threadWorkflows.ts | 12 ++++ 3 files changed, 52 insertions(+), 29 deletions(-) diff --git a/apps/mobile/src/state/use-thread-composer-state.ts b/apps/mobile/src/state/use-thread-composer-state.ts index 5033ef4e8e894..278b9eb67599b 100644 --- a/apps/mobile/src/state/use-thread-composer-state.ts +++ b/apps/mobile/src/state/use-thread-composer-state.ts @@ -7,7 +7,10 @@ import { readEnvironmentScope } from "./session"; import { useAtomValue } from "@effect/atom-react"; import { compactBeforeSendTokens } from "@t3tools/client-runtime/state/context-window"; import { threadRuntimeIsActive } from "@t3tools/client-runtime/state/shell"; -import { threadSteersDuringCompaction } from "@t3tools/client-runtime/state/thread-workflows"; +import { + runStopRequested, + threadSteersDuringCompaction, +} from "@t3tools/client-runtime/state/thread-workflows"; import { resolvePendingHandoff } from "@t3tools/client-runtime/handoff"; import { announcedRun, @@ -421,7 +424,10 @@ export function useThreadComposerState(input: { run: selectedThreadProjection?.projection.runs.find((run) => run.id === activeRunId), messages: selectedThreadMessages, }); - const canSteerActiveTurn = queueWorkflow?.canPromoteToSteer === true && !compactionBlocksSteer; + const canSteerActiveTurn = + queueWorkflow?.canPromoteToSteer === true && + !compactionBlocksSteer && + !runStopRequested(selectedThreadProjection?.projection, activeRunId); // A stop or a restart holds the queue, completion wakes included, until it // is resumed; the queue sheet lists only the user's own messages. const queueHeld = queueWorkflow?.isHeld === true; diff --git a/packages/client-runtime/src/state/threadWorkflows.test.ts b/packages/client-runtime/src/state/threadWorkflows.test.ts index fd8092a996a66..d3e522e3cd7cb 100644 --- a/packages/client-runtime/src/state/threadWorkflows.test.ts +++ b/packages/client-runtime/src/state/threadWorkflows.test.ts @@ -35,33 +35,38 @@ const capabilities = (input?: { describe("thread workflows", () => { it.each([ - ["queue only", { queued: true }, false, false], - ["session still attaching", undefined, false, true], - ["native steering", { steer: true }, false, true], - ["interrupt and restart", { interrupt: true, restartSteer: true }, false, true], - ["restart without interrupt", { restartSteer: true }, false, false], - ["explicit compaction", { steer: true }, true, false], - ] as const)("gates composer steering for %s", (_, turns, compactCommandIsActive, expected) => { - const projection = { - thread: { id: "thread", activeProviderThreadId: "provider-thread" }, - runs: [{ id: "active", status: "running", providerThreadId: "provider-thread" }], - providerThreads: [{ id: "provider-thread", providerSessionId: "session" }], - providerSessions: [ - ...(turns === undefined - ? [] - : [{ id: "session", status: "running", capabilities: capabilities(turns) }]), - { id: "other", status: "ready", capabilities: capabilities({ steer: true }) }, - ], - messages: [], - } as unknown as OrchestrationV2ThreadProjection; - expect( - threadCanSteer(projection, { - compactCommandIsActive, - compactionRunning: false, - activeRunId: projection.runs[0]!.id, - }), - ).toBe(expected); - }); + ["queue only", { queued: true }, false, false, false], + ["session still attaching", undefined, false, false, true], + ["native steering", { steer: true }, false, false, true], + ["interrupt and restart", { interrupt: true, restartSteer: true }, false, false, true], + ["restart without interrupt", { restartSteer: true }, false, false, false], + ["explicit compaction", { steer: true }, true, false, false], + ["a run Stop has reached", { steer: true }, false, true, false], + ] as const)( + "gates composer steering for %s", + (_, turns, compactCommandIsActive, stopRequested, expected) => { + const projection = { + thread: { id: "thread", activeProviderThreadId: "provider-thread" }, + runs: [{ id: "active", status: "running", providerThreadId: "provider-thread" }], + providerThreads: [{ id: "provider-thread", providerSessionId: "session" }], + providerSessions: [ + ...(turns === undefined + ? [] + : [{ id: "session", status: "running", capabilities: capabilities(turns) }]), + { id: "other", status: "ready", capabilities: capabilities({ steer: true }) }, + ], + messages: [], + turnItems: stopRequested ? [{ runId: "active", type: "run_interrupt_request" }] : [], + } as unknown as OrchestrationV2ThreadProjection; + expect( + threadCanSteer(projection, { + compactCommandIsActive, + compactionRunning: false, + activeRunId: projection.runs[0]!.id, + }), + ).toBe(expected); + }, + ); it("skips message history classification when no runs are queued", () => { let metadataReads = 0; diff --git a/packages/client-runtime/src/state/threadWorkflows.ts b/packages/client-runtime/src/state/threadWorkflows.ts index 9e3d1eb4512b2..2931a93ec8fdb 100644 --- a/packages/client-runtime/src/state/threadWorkflows.ts +++ b/packages/client-runtime/src/state/threadWorkflows.ts @@ -110,6 +110,17 @@ function supportsSteering(turns: OrchestrationV2ProviderCapabilities["turns"]): ); } +/** The server rejects a steer into a run that Stop has reached, though the run still reads as running. */ +export function runStopRequested( + projection: Pick | null | undefined, + runId: Run["id"] | null | undefined, +): boolean { + if (projection == null || runId == null) return false; + return projection.turnItems.some( + (item) => item.runId === runId && item.type === "run_interrupt_request", + ); +} + export function threadCanSteer( projection: Projection | null, input: { @@ -121,6 +132,7 @@ export function threadCanSteer( const turns = projection && resolveThreadProviderSession(projection)?.capabilities.turns; // A steer submitted before the session attaches can wait for its provider turn. if (turns && !supportsSteering(turns)) return false; + if (runStopRequested(projection, input.activeRunId)) return false; return !compactionBlocksSteering({ compactCommandIsActive: input.compactCommandIsActive, compactionRunning: input.compactionRunning, From 67918f51ccf79e8873349f3dc35c839689dba884 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 25 Nov 2026 08:03:47 -0800 Subject: [PATCH 057/238] fix(web): Show more in Thread Details keeps every repository listed (#42919) --- .../chat/ThreadDetailsCard.browser.test.tsx | 68 ++++++++++++++++++- .../src/components/chat/ThreadDetailsCard.tsx | 4 +- .../chat/ThreadRepositorySections.tsx | 5 +- 3 files changed, 72 insertions(+), 5 deletions(-) diff --git a/apps/web/src/components/chat/ThreadDetailsCard.browser.test.tsx b/apps/web/src/components/chat/ThreadDetailsCard.browser.test.tsx index b03b58e10f4e2..7d5fa03cf1879 100644 --- a/apps/web/src/components/chat/ThreadDetailsCard.browser.test.tsx +++ b/apps/web/src/components/chat/ThreadDetailsCard.browser.test.tsx @@ -1,6 +1,6 @@ import { StrictMode } from "react"; -import { EnvironmentId, ThreadId, type ScopedThreadRef } from "@t3tools/contracts"; -import { expect, it } from "vite-plus/test"; +import { EnvironmentId, ProjectId, ThreadId, type ScopedThreadRef } from "@t3tools/contracts"; +import { expect, it, vi } from "vite-plus/test"; import { page } from "vite-plus/test/browser"; import { act, render } from "../../../test/render"; import { selectThreadPanelOpen, useRightPanelStore } from "../../rightPanelStore"; @@ -8,6 +8,13 @@ import { PopoverCreateHandle } from "../ui/popover"; import { ChatCanvasContext } from "./ChatCanvasContext"; import { resolveChatCanvasLayout } from "./chatCanvasLayout"; import { ThreadDetailsCard } from "./ThreadDetailsCard"; +import { ThreadRepositorySections } from "./ThreadRepositorySections"; +import { useThreadRepositoryPinsStore } from "../../threadRepositoryPinsStore"; + +vi.mock(import("~/state/query"), async (original) => ({ + ...(await original()), + useEnvironmentQuery: () => ({ data: null, error: null }) as never, +})); const threadA: ScopedThreadRef = { environmentId: EnvironmentId.make("environment"), @@ -212,3 +219,60 @@ it("stays full while expanded issue rows overflow", async () => { .element(page.getByRole("region", { name: "Thread details" })) .toHaveAttribute("data-density", "full"); }); + +it("keeps the repository list reachable after Show more expands it", async () => { + using fixture = setup(); + for (let index = 1; index <= 30; index++) { + useThreadRepositoryPinsStore + .getState() + .pin(threadB, { repositoryPath: `/repos/repo-${index}`, name: `repo-${index}` }); + } + await using _screen = await render( + + {}, + measureDetailsCard: () => {}, + detailsCardTopInset: 0, + preferredDetailsCard: placement, + detailsCardPlacement: placement, + }} + > + + {(density) => + // As ThreadDetailsPanel does, essential density drops the repository section. + density === "essential" ? null : ( + {}} + explainsEmpty={false} + showActions={false} + /> + ) + } + + + , + ); + await page.getByRole("button", { name: "Show 26 more" }).click(); + + await expect.element(page.getByRole("button", { name: "Show fewer" })).toBeVisible(); + await expect + .element(page.getByRole("region", { name: "Thread details" })) + .not.toHaveAttribute("data-density", "essential"); +}); diff --git a/apps/web/src/components/chat/ThreadDetailsCard.tsx b/apps/web/src/components/chat/ThreadDetailsCard.tsx index aadb47d0724ce..87fae983e4163 100644 --- a/apps/web/src/components/chat/ThreadDetailsCard.tsx +++ b/apps/web/src/components/chat/ThreadDetailsCard.tsx @@ -80,10 +80,10 @@ export function ThreadDetailsCard({ const measure = () => { const frame = element.closest("[data-thread-details-card]"); const next = element.offsetHeight + (frame ? frame.offsetHeight - frame.clientHeight : 0); - // PR and issue lists, servers, lineage, side chats and automations scroll as they grow. + // PR and issue lists, servers, repositories, lineage, side chats and automations scroll as they grow. // Counting them toward density would hide the section and workspace controls when the user asks to see more. const lists = element.querySelectorAll( - "[data-thread-relationships-panel], [data-thread-side-chats-panel], [data-thread-details-pr-list], [data-thread-details-issue-list], [data-thread-automations-panel], [data-thread-details-server-overflow]", + "[data-thread-relationships-panel], [data-thread-side-chats-panel], [data-thread-details-pr-list], [data-thread-details-issue-list], [data-thread-automations-panel], [data-thread-details-server-overflow], [data-thread-details-repository-overflow]", ); const fittingHeight = next - Array.from(lists).reduce((sum, list) => sum + list.offsetHeight, 0); diff --git a/apps/web/src/components/chat/ThreadRepositorySections.tsx b/apps/web/src/components/chat/ThreadRepositorySections.tsx index f984037d5a96e..1aece09919816 100644 --- a/apps/web/src/components/chat/ThreadRepositorySections.tsx +++ b/apps/web/src/components/chat/ThreadRepositorySections.tsx @@ -77,6 +77,7 @@ const RepositorySection = memo(function RepositorySection(props: { cwd: string; removable: boolean; expanded: boolean; + overflow: boolean; owner: { readonly threadId?: ThreadId; readonly projectId?: ProjectId }; showActions: boolean; onToggle: (key: string) => void; @@ -99,6 +100,7 @@ const RepositorySection = memo(function RepositorySection(props: {
    setExpandedKey((current) => (current === key ? null : key)); const remove = (key: string) => unpin(threadRef, key); - const renderSection = (section: ThreadRepositorySection) => ( + const renderSection = (section: ThreadRepositorySection, index: number) => ( = THREAD_REPOSITORY_SECTIONS_VISIBLE} owner={owner} showActions={props.showActions} onToggle={toggle} From a76e5547844b11688454f8f41095597d196eccfe Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Wed, 25 Nov 2026 08:26:40 -0800 Subject: [PATCH 058/238] test(web): Files panel Refresh test no longer fails on a late tree render (#42935) Co-authored-by: Claude Opus 5.5 --- .../web/src/components/files/FileBrowserPanel.browser.test.tsx | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/apps/web/src/components/files/FileBrowserPanel.browser.test.tsx b/apps/web/src/components/files/FileBrowserPanel.browser.test.tsx index ecf51be124491..c7c58e689431d 100644 --- a/apps/web/src/components/files/FileBrowserPanel.browser.test.tsx +++ b/apps/web/src/components/files/FileBrowserPanel.browser.test.tsx @@ -373,9 +373,10 @@ describe("FileBrowserPanel", () => { await vi.waitFor(() => expect(findTreeRow("src/")!.getAttribute("aria-expanded")).toBe("true")); // Refresh revalidates the folders behind the rows on screen: the open one and the root. + // The tree can render its rows again at any time, so compare folders, not calls. revalidate.mockClear(); await userEvent.click(page.getByRole("button", { name: "Refresh workspace files" })); - expect(revalidate.mock.calls).toEqual([["src"], [""]]); + expect(new Set(revalidate.mock.calls.flat())).toEqual(new Set(["src", ""])); }); describe("revealing a folder while folders above it are still loading", () => { const roots = Array.from({ length: 12 }, (_, index): ProjectEntry => { From 867a9f0aec31d3629b779fb3dc70b2c4ade8e867 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Wed, 25 Nov 2026 17:32:31 +0100 Subject: [PATCH 059/238] fix(terminal): keep line breaks when joining a running terminal (#42927) Co-authored-by: Julius Marminge --- packages/contracts/src/terminal.test.ts | 25 +++++++++++ packages/contracts/src/terminal.ts | 55 ++++++++++++++++++++----- 2 files changed, 70 insertions(+), 10 deletions(-) diff --git a/packages/contracts/src/terminal.test.ts b/packages/contracts/src/terminal.test.ts index 16b3ed1d38eb9..dcbb338ccf789 100644 --- a/packages/contracts/src/terminal.test.ts +++ b/packages/contracts/src/terminal.test.ts @@ -4,16 +4,41 @@ import { describe, expect, it } from "vite-plus/test"; import { chunkTerminalWrite, DEFAULT_TERMINAL_ID, + retainTerminalSnapshotHistory, + skipTerminalSnapshotContinuation, TERMINAL_WRITE_MAX_LENGTH, TerminalError, TerminalOpenInput, TerminalProviderEnvironmentError, + terminalSequenceStateAfter, } from "./terminal.ts"; import { ProviderInstanceId } from "./providerInstance.ts"; const encodeTerminalError = Schema.encodeUnknownSync(TerminalError); const decodeTerminalError = Schema.decodeUnknownSync(TerminalError); +describe("terminal snapshot replay after an omitted DCS", () => { + const pendingDcs = "\u001bPz"; + const state = terminalSequenceStateAfter(0, pendingDcs); + + it.each([ + ["a next-line control", "\u0085ready", "\u001bEready"], + ["a tab stop before carriage return and tab", "\u0088\r\tready", "\u001bH\r\tready"], + ["a byte after a string terminator", "\u1700ready", "\ufffdready"], + ])("preserves %s in a continuation", (_name, data, replay) => { + expect(skipTerminalSnapshotContinuation(state, data)).toEqual({ state: 0, data: replay }); + }); + + it.each([ + [8, "\u0085ready", "\u001bEready"], + [8, "\u2140ready", "\u001bEready"], + [10, "\u2140ready", "\u001bE\ufffdready"], + ])("keeps the line break within a %i-byte history budget", (budget, rest, replay) => { + const history = pendingDcs + "z".repeat(50) + rest; + expect(retainTerminalSnapshotHistory(history, budget)).toEqual({ history: replay }); + }); +}); + function decodeSync(schema: S, input: unknown): Schema.Schema.Type { return Schema.decodeUnknownSync(schema as never)(input) as Schema.Schema.Type; } diff --git a/packages/contracts/src/terminal.ts b/packages/contracts/src/terminal.ts index 0043f87d0eaed..be05d30a7aa1e 100644 --- a/packages/contracts/src/terminal.ts +++ b/packages/contracts/src/terminal.ts @@ -19,7 +19,11 @@ const SEQUENCE_SOS_PM_APC = 5; const SEQUENCE_OSC = 6; // Bits above the low three hold a high surrogate until its other half arrives. -function nextTerminalSequenceState(state: number, unit: number): number { +function nextTerminalSequenceState( + state: number, + unit: number, + onC1ReturnToGround?: (byte: number, remainingBytes: number) => void, +): number { if (unit === 0x1b) return SEQUENCE_ESCAPE; if (state === TERMINAL_SEQUENCE_GROUND || unit === 0x18 || unit === 0x1a) { return TERMINAL_SEQUENCE_GROUND; @@ -62,7 +66,10 @@ function nextTerminalSequenceState(state: number, unit: number): number { if (byte === 0x90) mode = SEQUENCE_DCS; else if (byte === 0x9b) mode = SEQUENCE_CSI; else if (byte === 0x98 || byte >= 0x9e) mode = SEQUENCE_SOS_PM_APC; - else return TERMINAL_SEQUENCE_GROUND; + else { + onC1ReturnToGround?.(byte, shift / 6); + return TERMINAL_SEQUENCE_GROUND; + } } return mode; } @@ -97,6 +104,25 @@ export function terminalSequenceEnd(state: number, text: string): number { return index; } +function scanSnapshotContinuation(state: number, data: string, limit = data.length) { + let control = ""; + let replacementCount = 0; + const replayC1 = (byte: number, remainingBytes: number) => { + // Replay IND, NEL, HTS and RI from ground. Any bytes parsed after the control + // are now stray UTF-8 continuation bytes. + if (byte === 0x84 || byte === 0x85 || byte === 0x88 || byte === 0x8d) { + control = "\u001b" + String.fromCharCode(byte - 0x40); + } + replacementCount = remainingBytes; + }; + let end = 0; + while (state !== TERMINAL_SEQUENCE_GROUND && end < limit) { + state = nextTerminalSequenceState(state, data.charCodeAt(end), replayC1); + end += 1; + } + return { state, end, control, replacementCount }; +} + /** Skip the continuation of an omitted snapshot prefix, retaining any new escape sequence. */ export function skipTerminalSnapshotContinuation(state: number, data: string) { if (data.length === 0) return { state, data }; @@ -108,17 +134,20 @@ export function skipTerminalSnapshotContinuation(state: number, data: string) { } const escape = data.indexOf("\u001b"); - const prefix = escape < 0 ? data : data.slice(0, escape); - const end = terminalSequenceEnd(state, prefix); - const next = terminalSequenceStateAfter(state, prefix, 0, end); - if (next === TERMINAL_SEQUENCE_GROUND || escape < 0) { - return { state: next, data: data.slice(end) }; + const { + state: next, + end, + control, + replacementCount, + } = scanSnapshotContinuation(state, data, escape < 0 ? data.length : escape); + if (next === TERMINAL_SEQUENCE_GROUND || end === data.length) { + return { state: next, data: control + "\ufffd".repeat(replacementCount) + data.slice(end) }; } // Hold a final ESC until we know whether it starts a new sequence or completes ST. - if (escape + 1 === data.length) return { state: SEQUENCE_ESCAPE, data: "" }; + if (end + 1 === data.length) return { state: SEQUENCE_ESCAPE, data: "" }; return { state: TERMINAL_SEQUENCE_GROUND, - data: data.slice(data[escape + 1] === "\\" ? escape + 2 : escape), + data: data.slice(data[end + 1] === "\\" ? end + 2 : end), }; } @@ -152,7 +181,13 @@ export function retainedTerminalHistory(history: string, maxBytes: number): stri 0, history.length - retained.length, ); - return retained.slice(terminalSequenceEnd(state, retained)); + const { end, control, replacementCount } = scanSnapshotContinuation(state, retained); + const tail = retained.slice(end); + if (replacementCount === 0) return control + tail; + // The two-byte ESC form fits where the consumed code point did. Each replacement + // glyph takes three bytes, so keep only as many as fit alongside the control and tail. + const available = maxBytes - historyEncoder.encode(tail).byteLength - control.length; + return control + "\ufffd".repeat(Math.min(replacementCount, Math.floor(available / 3))) + tail; } /** Keep a whole unfinished prefix when possible, or skip its continuation during replay. */ From 4122ddbb16d7b08e0edfd40683003d0de2819a0e Mon Sep 17 00:00:00 2001 From: Simone Date: Wed, 25 Nov 2026 17:42:22 +0100 Subject: [PATCH 060/238] fix(server): separate ruby readings in EPUB attachment text (#42911) Co-authored-by: Simone <185146821+Lucenx9@users.noreply.github.com> Co-authored-by: Julius Marminge --- apps/server/src/provider/documentTextWorker.ts | 18 ++++++++++++++++++ .../src/provider/userInputAttachments.test.ts | 3 ++- 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/apps/server/src/provider/documentTextWorker.ts b/apps/server/src/provider/documentTextWorker.ts index 0e9604c300bed..8d0688b551373 100644 --- a/apps/server/src/provider/documentTextWorker.ts +++ b/apps/server/src/provider/documentTextWorker.ts @@ -93,6 +93,22 @@ function collapseOdfWhitespace(paragraph: XmlNode) { if (tail && afterSpace) tail.node.children[tail.index] = tail.value.slice(0, -1); } +function separateRubyReadings(ruby: XmlNode) { + const parts = ruby.children.filter((part) => + typeof part === "string" + ? part.trim() !== "" + : !HIDDEN.has(part.name) && (part.name !== "rp" || part.hasText), + ); + const isFallback = (part: XmlNode | string | undefined) => + typeof part !== "string" && part?.name === "rp"; + for (const [index, part] of parts.entries()) { + if (typeof part === "string" || part.name !== "rt" || !part.hasText) continue; + if (isFallback(parts[index - 1]) || isFallback(parts[index + 1])) continue; + part.children.unshift("("); + part.children.push(")"); + } +} + function xml(source: string, extension: string): XmlNode { const odf = [".odt", ".ods", ".odp"].includes(extension); const root: XmlNode = { name: "root", attrs: {}, children: [] }; @@ -146,6 +162,8 @@ function xml(source: string, extension: string): XmlNode { parent.children.pop(); return; } + if (extension === ".epub" && node.name === "ruby" && stack[1]?.name === "html") + separateRubyReadings(node); if (node.name === "Fallback" && !retainCompatibilityFallback(parent, node)) return; if (HIDDEN.has(node.name) || (!node.hasText && node.name !== "noBreakHyphen")) return; parent.hasText = true; diff --git a/apps/server/src/provider/userInputAttachments.test.ts b/apps/server/src/provider/userInputAttachments.test.ts index c7f3a2e9a1cc7..824a9f48422e7 100644 --- a/apps/server/src/provider/userInputAttachments.test.ts +++ b/apps/server/src/provider/userInputAttachments.test.ts @@ -1495,7 +1495,7 @@ describe("question answer paths", () => { "OEBPS/book.opf": '', "OEBPS/a.xhtml": - '

    Last chapter

    Price 10 8 old

    ', + '

    Last chapter

    Price 10 8 old

    山路やまみちを歩く。東京(とうきょう)に着く。川を見る。海うみ まで。

    ', "OEBPS/b.xhtml": 'My Novel

    First chapter

    Larkspur

    Direct div
    Direct section
  • Direct item emphasis trailing
  • Account: A
    Balance: 731Currency: USD
    HeadingTotal
    Important value731
    Before
    Inner
    After
    Neighbor
    Port
    443
    Timeout
    30 seconds

    Prefixed note

    1. Before boarding
      • Check passports
        1. Compare names
      • Confirm gate
    2. Board promptly
    3. Before landing

      • Collect bags
    ' + "
    1. Indented\n
      • Alpha
    ", @@ -1520,6 +1520,7 @@ describe("question answer paths", () => { "## Chapter 2", "Last chapter", "Price 10 8 old", + "山路(やまみち)を歩く。東京(とうきょう)に着く。川を見る。海(うみ) まで。", "## Chapter 3", ], absent: [ From 4568a1b7414585f9eae82a955a0d123da3d1ed47 Mon Sep 17 00:00:00 2001 From: Victor Date: Wed, 25 Nov 2026 10:47:09 -0600 Subject: [PATCH 061/238] fix(web): unsupported file preview no longer calls extensionless filenames a file type (#42932) Co-authored-by: Julius Marminge --- .../AttachmentFilePreview.browser.test.tsx | 19 +++++++++++++++++++ .../files/AttachmentFilePreview.tsx | 11 ++++++++--- apps/web/src/i18n/translations/de.json | 2 +- apps/web/src/i18n/translations/en.json | 2 +- apps/web/src/i18n/translations/es.json | 2 +- apps/web/src/i18n/translations/fr.json | 2 +- apps/web/src/i18n/translations/ja.json | 2 +- apps/web/src/i18n/translations/ko.json | 2 +- apps/web/src/i18n/translations/pt-BR.json | 2 +- apps/web/src/i18n/translations/ru.json | 2 +- apps/web/src/i18n/translations/sv.json | 2 +- apps/web/src/i18n/translations/zh.json | 2 +- 12 files changed, 37 insertions(+), 13 deletions(-) diff --git a/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx b/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx index 0a7dc74c1f691..46af0f57af84c 100644 --- a/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx +++ b/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx @@ -2340,3 +2340,22 @@ it.each([ `Unsupported PDF ${directory} asset.`, ); }); + +it.each([ + ["firmware", "Save it to open in an app that supports this format."], + [".cache", "Save it to open in an app that supports this format."], + ["a.dir/firmware", "Save it to open in an app that supports this format."], + ["blob.foo", "Save it to open in an app that supports foo files."], +] as const)( + "describes unsupported binary attachment %s without misreading its name as an extension", + async (name, expected) => { + const file = new Blob([new Uint8Array([0, 1, 2, 3])], { type: "application/octet-stream" }); + await using screen = await render( + , + ); + await expect + .element(screen.getByText("No preview for this file", { exact: true })) + .toBeVisible(); + await expect.element(screen.getByText(expected, { exact: true })).toBeVisible(); + }, +); diff --git a/apps/web/src/components/files/AttachmentFilePreview.tsx b/apps/web/src/components/files/AttachmentFilePreview.tsx index ba2b69ad7c783..4c7abcc34e0df 100644 --- a/apps/web/src/components/files/AttachmentFilePreview.tsx +++ b/apps/web/src/components/files/AttachmentFilePreview.tsx @@ -284,6 +284,11 @@ export function AttachmentFilePreview(props: { }); }; + const basename = props.name.split(/[\\/]/).at(-1) ?? ""; + const dotIndex = basename.lastIndexOf("."); + const extension = + dotIndex > 0 && dotIndex < basename.length - 1 ? basename.slice(dotIndex + 1) : null; + const body = failure ? ( No preview for this file

    - {props.name.split(".").at(-1) ? ( + {extension ? ( - Save it to open in an app that supports {props.name.split(".").at(-1)} files. + Save it to open in an app that supports {extension} files. ) : ( - Save it to open in an app that supports this format files. + Save it to open in an app that supports this format. )}

    diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 24dc666ae6301..c6af3d3c04e4b 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -5574,7 +5574,7 @@ }, "-Dateien unterstützt." ], - "774654575f014b55": "Speichere sie, um sie in einer App zu öffnen, die dieses Dateiformat unterstützt.", + "d3170aa2bb08efbd": "Speichere sie, um sie in einer App zu öffnen, die dieses Dateiformat unterstützt.", "46f943a30e259620": "Audio nicht verfügbar. {name} öffnen", "e2cf6b944d1d095d": "Audio nicht verfügbar. {name} erneut versuchen", "f08fb460ad4617d6": "{name} wird geladen", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index bc506f66b3252..9c06b25632e08 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -5575,7 +5575,7 @@ }, " files." ], - "774654575f014b55": "Save it to open in an app that supports this format files.", + "d3170aa2bb08efbd": "Save it to open in an app that supports this format.", "46f943a30e259620": "Audio unavailable. Open {name}", "e2cf6b944d1d095d": "Audio unavailable. Retry {name}", "f08fb460ad4617d6": "Loading {name}", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index 23551a07bf28e..578276a00e78d 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -5573,7 +5573,7 @@ }, "." ], - "774654575f014b55": "Guárdalo para abrirlo en una app compatible con este formato de archivo.", + "d3170aa2bb08efbd": "Guárdalo para abrirlo en una app compatible con este formato de archivo.", "46f943a30e259620": "Audio no disponible. Abrir {name}", "e2cf6b944d1d095d": "Audio no disponible. Reintentar {name}", "f08fb460ad4617d6": "Cargando {name}", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index 91cbcc50b21da..3a26b9305572b 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -5574,7 +5574,7 @@ }, "." ], - "774654575f014b55": "Enregistrez-le pour l’ouvrir dans une app qui prend en charge ce format de fichier.", + "d3170aa2bb08efbd": "Enregistrez-le pour l’ouvrir dans une app qui prend en charge ce format de fichier.", "46f943a30e259620": "Audio indisponible. Ouvrir {name}", "e2cf6b944d1d095d": "Audio indisponible. Réessayer {name}", "f08fb460ad4617d6": "Chargement de {name}", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index c1556ac19d8a7..1fb5dfff0591d 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -5555,7 +5555,7 @@ }, " ファイルに対応したアプリで開くには、保存してください。" ], - "774654575f014b55": "この形式のファイルに対応したアプリで開くには、保存してください。", + "d3170aa2bb08efbd": "この形式のファイルに対応したアプリで開くには、保存してください。", "46f943a30e259620": "音声を利用できません。{name} を開く", "e2cf6b944d1d095d": "音声を利用できません。{name} を再試行", "f08fb460ad4617d6": "{name} を読み込んでいます", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index e871b3772a96f..a0ac24a5a0c26 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -5553,7 +5553,7 @@ }, " 파일을 지원하는 앱에서 여세요." ], - "774654575f014b55": "저장한 후 이 형식을 지원하는 앱에서 여세요.", + "d3170aa2bb08efbd": "저장한 후 이 형식을 지원하는 앱에서 여세요.", "46f943a30e259620": "오디오를 사용할 수 없음. {name} 열기", "e2cf6b944d1d095d": "오디오를 사용할 수 없음. {name} 다시 시도", "f08fb460ad4617d6": "{name} 불러오는 중", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index b70fc50ee9b57..23f825cfae590 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -5573,7 +5573,7 @@ }, "." ], - "774654575f014b55": "Salve-o para abrir em um app compatível com este formato.", + "d3170aa2bb08efbd": "Salve-o para abrir em um app compatível com este formato.", "46f943a30e259620": "Áudio indisponível. Abrir {name}", "e2cf6b944d1d095d": "Áudio indisponível. Tentar {name} novamente", "f08fb460ad4617d6": "Carregando {name}", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 94ab0714d3c77..cae6ba120f711 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -5573,7 +5573,7 @@ }, "." ], - "774654575f014b55": "Сохраните его, чтобы открыть в приложении, поддерживающем файлы этого формата.", + "d3170aa2bb08efbd": "Сохраните его, чтобы открыть в приложении, поддерживающем файлы этого формата.", "46f943a30e259620": "Аудио недоступно. Открыть {name}", "e2cf6b944d1d095d": "Аудио недоступно. Повторить {name}", "f08fb460ad4617d6": "Загрузка {name}", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index ee4146130336a..811c6ceabd7fe 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -5574,7 +5574,7 @@ }, "-filer." ], - "774654575f014b55": "Spara den för att öppna den i en app som stöder det här filformatet.", + "d3170aa2bb08efbd": "Spara den för att öppna den i en app som stöder det här filformatet.", "46f943a30e259620": "Ljudet är inte tillgängligt. Öppna {name}", "e2cf6b944d1d095d": "Ljudet är inte tillgängligt. Försök igen med {name}", "f08fb460ad4617d6": "Läser in {name}", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index bd2e9e6692961..5f4d8cfc31658 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -5579,7 +5579,7 @@ }, " 文件的应用中打开。" ], - "774654575f014b55": "保存后可在支持此格式文件的应用中打开。", + "d3170aa2bb08efbd": "保存后可在支持此格式文件的应用中打开。", "46f943a30e259620": "音频不可用。打开 {name}", "e2cf6b944d1d095d": "音频不可用。重试 {name}", "f08fb460ad4617d6": "正在加载 {name}", From 41d5875e5de1e1e790fccb945369df23a1d8dd2d Mon Sep 17 00:00:00 2001 From: Marcus Takagi Date: Thu, 26 Nov 2026 00:55:36 +0800 Subject: [PATCH 062/238] fix(server): Antigravity live sessions no longer overwrite default thinking levels (#42931) Co-authored-by: huyuetian Co-authored-by: Julius Marminge --- apps/server/scripts/acp-mock-agent.ts | 36 ++++ .../Adapters/AntigravityAdapterV2.ts | 16 +- .../src/provider/AntigravityProvider.test.ts | 169 ++++++++++++++++++ .../src/provider/AntigravityProvider.ts | 90 ++++++++-- .../Drivers/AntigravityDriver.test.ts | 165 +++++++++++++++++ .../src/provider/Drivers/AntigravityDriver.ts | 8 +- apps/server/src/provider/ProviderRegistry.ts | 20 ++- 7 files changed, 482 insertions(+), 22 deletions(-) diff --git a/apps/server/scripts/acp-mock-agent.ts b/apps/server/scripts/acp-mock-agent.ts index a27eaac473810..567df6929e5dd 100644 --- a/apps/server/scripts/acp-mock-agent.ts +++ b/apps/server/scripts/acp-mock-agent.ts @@ -18,6 +18,8 @@ import { beginAcpMockPrompt } from "./acpMockCancellationState.ts"; const requestLogPath = process.env.T3_ACP_REQUEST_LOG_PATH; const antigravityProfile = process.env.T3_ACP_ANTIGRAVITY === "1"; +const antigravityThoughtLevel = process.env.T3_ACP_ANTIGRAVITY_THOUGHT_LEVEL === "1"; +const antigravityResumeThoughtLevel = process.env.T3_ACP_RESUME_THOUGHT_LEVEL; // GitHub Copilot CLI advertises URL-shaped session mode ids. const copilotModesProfile = process.env.T3_ACP_COPILOT_MODES === "1"; const copilotModeId = (name: string) => @@ -124,6 +126,7 @@ let currentModeId = antigravityProfile ? copilotModeId("agent") : "ask"; let currentModelId = antigravityProfile ? "gemini-test-low" : "default"; +let currentAntigravityThoughtLevel = "high"; let parameterizedModelPicker = false; let currentReasoning = "medium"; let currentContext = "272k"; @@ -180,6 +183,30 @@ function configOptions(): ReadonlyArray { currentValue: currentModeId, options: availableModes.map((mode) => ({ value: mode.id, name: mode.name })), }, + ...(antigravityThoughtLevel + ? [ + { + configId: "thought_level", + name: "Thinking Level", + category: "thought_level", + type: "select" as const, + currentValue: currentAntigravityThoughtLevel, + options: + currentModelId === "gemini-test-high" + ? [ + { value: "low", name: "Low" }, + { value: "medium", name: "Medium" }, + { value: "high", name: "High" }, + ] + : [ + { value: "low", name: "Low" }, + { value: "medium", name: "Medium" }, + { value: "high", name: "High" }, + { value: "xhigh", name: "Extra" }, + ], + }, + ] + : []), ]; } if (parameterizedModelPicker) { @@ -665,6 +692,9 @@ const program = Effect.gen(function* () { }, }); if (antigravityProfile) { + if (antigravityResumeThoughtLevel) { + currentAntigravityThoughtLevel = antigravityResumeThoughtLevel; + } yield* publishAntigravityCommands(request.sessionId); } return { @@ -893,6 +923,12 @@ const program = Effect.gen(function* () { } if (request.configId === "model" && typeof request.value === "string") { currentModelId = request.value; + if (antigravityProfile && antigravityThoughtLevel) { + currentAntigravityThoughtLevel = request.value === "gemini-test-high" ? "medium" : "high"; + } + } + if (request.configId === "thought_level" && typeof request.value === "string") { + currentAntigravityThoughtLevel = request.value; } if (request.configId === "agent" && typeof request.value === "string") { currentAgent = request.value; diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts index b8174495e28c7..a2e53801a3b24 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts @@ -101,6 +101,7 @@ export interface AntigravityAdapterV2Options { readonly onSessionStarted?: ( started: AcpSessionRuntime.AcpSessionRuntimeStartResult, cwd: string, + session?: { readonly resumed: boolean }, ) => Effect.Effect; readonly onSessionEvent?: AcpAdapterV2Flavor["onSessionEvent"]; readonly nativeLogging?: Parameters[0]["nativeLogging"]; @@ -204,13 +205,16 @@ export function makeAntigravityAcpAdapterFlavor( }); }, start: () => - runtime - .start() - .pipe( - Effect.tap( - (started) => options.onSessionStarted?.(started, input.cwd) ?? Effect.void, - ), + runtime.start().pipe( + Effect.tap( + (started) => + options.onSessionStarted?.(started, input.cwd, { + resumed: + input.resumeSessionId !== undefined && + started.sessionId === input.resumeSessionId, + }) ?? Effect.void, ), + ), } satisfies typeof runtime; }, Effect.provideService(SecureRandom.SecureRandom, options.random), diff --git a/apps/server/src/provider/AntigravityProvider.test.ts b/apps/server/src/provider/AntigravityProvider.test.ts index 219b4c0f5dbbd..9a2e5b1443060 100644 --- a/apps/server/src/provider/AntigravityProvider.test.ts +++ b/apps/server/src/provider/AntigravityProvider.test.ts @@ -589,6 +589,175 @@ it.layer(layerTest)("Antigravity provider snapshots", (it) => { }), ); + it.effect( + "does not let live session thinking-level or model changes overwrite catalog defaults", + () => + Effect.gen(function* () { + const harness = yield* makeHarness(); + yield* harness.initialize; + const thinking = ( + currentValue: string, + levels: ReadonlyArray = ["low", "medium", "high", "xhigh"], + ) => + ({ + id: "thought_level", + name: "Thinking Level", + category: "thought_level", + type: "select", + currentValue, + options: levels.map((value) => ({ value, name: value })), + }) satisfies EffectAcpSchema.SessionConfigOption; + const catalogModels = { + ...modelConfig, + currentValue: "neon", + options: [ + { value: "neon", name: "Neon" }, + { value: "carbon", name: "Carbon" }, + ], + } satisfies EffectAcpSchema.SessionConfigOption; + yield* harness.provider.onSessionStarted( + { + ...started, + sessionSetupResult: { + sessionId: "session-fresh", + configOptions: [catalogModels, thinking("high")], + }, + }, + "/workspace", + ); + + // A live chat session setting thought_level=xhigh must not pollute the catalog default. + yield* harness.provider.onConfigOptionsUpdated([catalogModels, thinking("xhigh")]); + // A live chat session switching to another model with a custom level must neither move + // isDefault nor overwrite cached thinking defaults for that model. + const switchedToCarbon = { + ...catalogModels, + currentValue: "carbon", + } satisfies EffectAcpSchema.SessionConfigOption; + yield* harness.provider.onConfigOptionsUpdated([ + switchedToCarbon, + thinking("low", ["low", "medium", "high"]), + ]); + + const snapshot = yield* harness.provider.snapshot.getSnapshot; + const neon = snapshot.models.find((model) => model.slug === "neon"); + const carbon = snapshot.models.find((model) => model.slug === "carbon"); + expect(neon?.isDefault).toBe(true); + expect(neon?.aliases).toContain(ANTIGRAVITY_DEFAULT_MODEL); + expect(neon?.capabilities?.optionDescriptors?.[0]).toMatchObject({ + id: "thought_level", + currentValue: "high", + }); + expect(carbon?.isDefault).toBeUndefined(); + expect(carbon?.capabilities?.optionDescriptors).toEqual([]); + + // Updating an observed model's choices keeps its recorded default while still offered, + // and falls back if the agent removes that default. + yield* harness.provider.onConfigOptionsUpdated([ + catalogModels, + thinking("max", ["low", "medium", "high", "xhigh", "max"]), + ]); + const expanded = (yield* harness.provider.snapshot.getSnapshot).models.find( + (model) => model.slug === "neon", + )?.capabilities?.optionDescriptors?.[0]; + expect(expanded).toMatchObject({ + id: "thought_level", + currentValue: "high", + options: [ + { id: "low" }, + { id: "medium" }, + { id: "high" }, + { id: "xhigh" }, + { id: "max" }, + ], + }); + + yield* harness.provider.onConfigOptionsUpdated([ + catalogModels, + thinking("medium", ["low", "medium"]), + ]); + const narrowed = (yield* harness.provider.snapshot.getSnapshot).models.find( + (model) => model.slug === "neon", + )?.capabilities?.optionDescriptors?.[0]; + expect(narrowed).toMatchObject({ + id: "thought_level", + currentValue: "medium", + options: [{ id: "low" }, { id: "medium" }], + }); + + // A catalog probe records each model's default level and keeps the default model intact. + yield* harness.provider.onConfigOptionsUpdated( + [switchedToCarbon, thinking("medium", ["low", "medium", "high"])], + { fromCatalogProbe: true }, + ); + const probed = yield* harness.provider.snapshot.getSnapshot; + expect(probed.models.find((model) => model.slug === "neon")?.isDefault).toBe(true); + expect( + probed.models.find((model) => model.slug === "carbon")?.capabilities + ?.optionDescriptors?.[0], + ).toMatchObject({ id: "thought_level", currentValue: "medium" }); + + // After a restart, resuming a session on another model at xhigh leaves unobserved + // models and default identity unset so the registry retains the cached defaults. + const restarted = yield* makeHarness(); + yield* restarted.initialize; + yield* restarted.provider.onSessionStarted( + { + ...started, + sessionSetupResult: { + sessionId: "session-resumed", + configOptions: [switchedToCarbon, thinking("xhigh")], + }, + }, + "/workspace", + { resumed: true }, + ); + const merged = mergeProviderSnapshot( + probed, + yield* restarted.provider.snapshot.getSnapshot, + ); + const mergedNeon = merged.models.find((model) => model.slug === "neon"); + const mergedCarbon = merged.models.find((model) => model.slug === "carbon"); + expect(mergedNeon?.isDefault).toBe(true); + expect(mergedNeon?.aliases).toContain(ANTIGRAVITY_DEFAULT_MODEL); + expect(mergedNeon?.capabilities?.optionDescriptors?.[0]).toMatchObject({ + id: "thought_level", + currentValue: "medium", + }); + expect(mergedCarbon?.isDefault).toBeUndefined(); + expect(mergedCarbon?.aliases).toBeUndefined(); + expect(mergedCarbon?.capabilities?.optionDescriptors?.[0]).toMatchObject({ + id: "thought_level", + currentValue: "medium", + }); + + // A later authoritative session start replaces the cached default model. + yield* restarted.provider.onSessionStarted( + { + ...started, + sessionSetupResult: { + sessionId: "session-fresh-after-restart", + configOptions: [switchedToCarbon, thinking("low", ["low", "medium", "high"])], + }, + }, + "/workspace", + ); + const updatedAfterFresh = mergeProviderSnapshot( + merged, + yield* restarted.provider.snapshot.getSnapshot, + ); + expect(updatedAfterFresh.models.find((model) => model.slug === "neon")?.isDefault).toBe( + undefined, + ); + expect(updatedAfterFresh.models.find((model) => model.slug === "carbon")?.isDefault).toBe( + true, + ); + expect( + updatedAfterFresh.models.find((model) => model.slug === "carbon")?.aliases, + ).toContain(ANTIGRAVITY_DEFAULT_MODEL); + }), + ); + it.effect("does not guess a version before a custom launcher's first handshake", () => Effect.gen(function* () { const harness = yield* makeHarness(); diff --git a/apps/server/src/provider/AntigravityProvider.ts b/apps/server/src/provider/AntigravityProvider.ts index 434a81a5123eb..2c23ea821f54a 100644 --- a/apps/server/src/provider/AntigravityProvider.ts +++ b/apps/server/src/provider/AntigravityProvider.ts @@ -15,6 +15,7 @@ import * as Context from "effect/Context"; import * as DateTime from "effect/DateTime"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; +import * as Equal from "effect/Equal"; import * as FiberHandle from "effect/FiberHandle"; import * as Option from "effect/Option"; import * as Predicate from "effect/Predicate"; @@ -73,9 +74,38 @@ function thinkingCapabilities(config: ThinkingConfig | null | undefined) { return createModelCapabilities({ optionDescriptors: [descriptor] }); } +function selectOptionValues(config: ThinkingConfig): ReadonlyArray { + return config.options.flatMap((entry) => + "value" in entry ? [entry.value] : entry.options.map((option) => option.value), + ); +} + +function mergeLiveThinkingConfig( + existing: ThinkingConfig | null | undefined, + next: ThinkingConfig | null, +): ThinkingConfig | null | undefined { + if (existing === undefined) return undefined; + if (next === null) return null; + if (existing === null) return undefined; + return selectOptionValues(next).includes(existing.currentValue) + ? { ...next, currentValue: existing.currentValue } + : next; +} + +function sessionModelSlug(setup: SessionSetupResult): string | undefined { + const config = setup.configOptions?.find( + (option) => option.id === "model" || option.category === "model", + ); + return config?.type === "select" ? config.currentValue : setup.models?.currentModelId; +} + export function buildAntigravityModelsFromSession( setup: SessionSetupResult, thinkingLevels: AntigravityThinkingLevels = new Map(), + options?: { + readonly defaultModel?: string | undefined; + readonly authoritative?: boolean; + }, ): ReadonlyArray { const config = setup.configOptions?.find( (option) => option.id === "model" || option.category === "model", @@ -91,6 +121,15 @@ export function buildAntigravityModelsFromSession( name: model.name, })) ?? []) : []; + const authoritative = options?.authoritative ?? true; + const defaultModel = + options?.defaultModel !== undefined + ? entries.some((entry) => entry.value === options.defaultModel) + ? options.defaultModel + : currentValue + : authoritative + ? currentValue + : undefined; const currentThinking = antigravityThinkingConfig(setup.configOptions); const seen = new Set(); // The agent can list two IDs under one name; label the later ones so the picker tells them apart. @@ -102,13 +141,15 @@ export function buildAntigravityModelsFromSession( const name = names.has(baseName) ? `${baseName} (${entry.value})` : baseName; names.add(baseName); const observed = - entry.value === currentValue ? (currentThinking ?? null) : thinkingLevels.get(entry.value); + authoritative && entry.value === currentValue + ? (currentThinking ?? null) + : thinkingLevels.get(entry.value); return [ { slug: entry.value, name, isCustom: false, - ...(entry.value === currentValue + ...(entry.value === defaultModel ? { isDefault: true, aliases: [ANTIGRAVITY_DEFAULT_MODEL] } : {}), // Levels differ per model; an unobserved model reports none so the registry keeps its cached ones. @@ -235,14 +276,23 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func // Preserve disk-discovered skills when callbacks replace workspace commands; the registry will not rescan them. const discoveredSkills = new Map(); const thinkingLevels = new Map(); + let defaultModelSlug: string | undefined; const observeThinkingLevels = ( configOptions: ReadonlyArray | null | undefined, + authoritative: boolean, ) => { const model = configOptions?.find( (option) => option.id === "model" || option.category === "model", ); - if (model?.type === "select" && model.currentValue) { - thinkingLevels.set(model.currentValue, antigravityThinkingConfig(configOptions) ?? null); + if (model?.type !== "select" || !model.currentValue) return; + const next = antigravityThinkingConfig(configOptions) ?? null; + if (authoritative) { + thinkingLevels.set(model.currentValue, next); + return; + } + const merged = mergeLiveThinkingConfig(thinkingLevels.get(model.currentValue), next); + if (merged !== undefined) { + thinkingLevels.set(model.currentValue, merged); } }; const rememberRuntimeModes = Effect.fn("AntigravityProvider.rememberRuntimeModes")(function* ( @@ -401,9 +451,15 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func const onSessionStarted = Effect.fn("AntigravityProvider.onSessionStarted")(function* ( started: AcpSessionRuntime.AcpSessionRuntimeStartResult, cwd?: string, + session?: { readonly resumed?: boolean }, ) { if (!settings.enabled) return; - observeThinkingLevels(started.sessionSetupResult.configOptions); + const authoritative = session?.resumed !== true; + if (authoritative) { + const modelSlug = sessionModelSlug(started.sessionSetupResult); + if (modelSlug) defaultModelSlug = modelSlug; + } + observeThinkingLevels(started.sessionSetupResult.configOptions, authoritative); const before = yield* SubscriptionRef.get(metadata); const supportsTextGeneration = yield* options.supportsTextGeneration; const updatedAt = DateTime.formatIso(yield* DateTime.now); @@ -431,7 +487,10 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func label: options.auth?.label ?? "Google account", }, checkedAt: updatedAt, - models: buildAntigravityModelsFromSession(started.sessionSetupResult, thinkingLevels), + models: buildAntigravityModelsFromSession(started.sessionSetupResult, thinkingLevels, { + defaultModel: defaultModelSlug, + authoritative, + }), supportedRuntimeModes, supportsTextGeneration, ...(cwd @@ -457,12 +516,20 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func const onConfigOptionsUpdated = Effect.fn("AntigravityProvider.onConfigOptionsUpdated")(function* ( configOptions: ReadonlyArray, + update?: { readonly fromCatalogProbe?: boolean }, ) { - observeThinkingLevels(configOptions); - const models = buildAntigravityModelsFromSession({ configOptions }, thinkingLevels); - yield* SubscriptionRef.update(metadata, (state) => { - if (state.draft.auth.status !== "authenticated") return state; - return { ...state, draft: { ...state.draft, models } }; + // Only catalog probes report a model's default level; live sessions carry per-thread overrides. + const authoritative = update?.fromCatalogProbe === true; + observeThinkingLevels(configOptions, authoritative); + const models = buildAntigravityModelsFromSession({ configOptions }, thinkingLevels, { + defaultModel: defaultModelSlug, + authoritative, + }); + yield* SubscriptionRef.updateSome(metadata, (state) => { + if (state.draft.auth.status !== "authenticated" || Equal.equals(state.draft.models, models)) { + return Option.none(); + } + return Option.some({ ...state, draft: { ...state.draft, models } }); }); }); @@ -531,6 +598,7 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func yield* rememberRuntimeModes(previousModes, RUNTIME_MODES_WITHOUT_AUTO); discoveredSkills.clear(); thinkingLevels.clear(); + defaultModelSlug = undefined; }); const snapshotForCwd = Effect.fn("AntigravityProvider.snapshotForCwd")(function* ( diff --git a/apps/server/src/provider/Drivers/AntigravityDriver.test.ts b/apps/server/src/provider/Drivers/AntigravityDriver.test.ts index 38fbf987d7a88..19451dd10ce16 100644 --- a/apps/server/src/provider/Drivers/AntigravityDriver.test.ts +++ b/apps/server/src/provider/Drivers/AntigravityDriver.test.ts @@ -4,19 +4,27 @@ import { expect, it } from "@effect/vitest"; import { ANTIGRAVITY_DEFAULT_MODEL, EnvironmentId, + MessageId, + NodeId, + ProjectId, ProviderDriverKind, ProviderInstanceId, ProviderSessionId, + RunAttemptId, + RunId, ThreadId, type AntigravitySettings, + type ServerProvider, } from "@t3tools/contracts"; import * as HostProcess from "@t3tools/shared/HostProcess"; +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 * as Path from "effect/Path"; import * as Redacted from "effect/Redacted"; import * as Schema from "effect/Schema"; +import * as Stream from "effect/Stream"; import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; import { HttpClient } from "effect/http"; @@ -703,4 +711,161 @@ it.layer(layerTest)("AntigravityDriver", (it) => { expect(yield* fs.exists(legacyRoot)).toBe(false); }), ); + + it.effect.skipIf(windowsHost)( + "keeps catalog default thinking levels when a chat session selects another level", + () => + Effect.gen(function* () { + const h = yield* makeHarness({ + environment: [ + { name: "T3_ACP_ANTIGRAVITY_THOUGHT_LEVEL", value: "1" }, + { name: "T3_ACP_RESUME_THOUGHT_LEVEL", value: "xhigh" }, + ], + }); + yield* h.refresh(); + const levelOf = (snapshot: ServerProvider, slug: string) => { + const option = snapshot.models + .find((model) => model.slug === slug) + ?.capabilities?.optionDescriptors?.find( + (descriptor) => descriptor.id === "thought_level", + ); + return option?.type === "select" ? option.currentValue : undefined; + }; + + const refreshed = yield* h.instance.snapshot.getSnapshot; + expect(levelOf(refreshed, "gemini-test-low")).toBe("high"); + expect(levelOf(refreshed, "gemini-test-high")).toBe("medium"); + + const threadId = ThreadId.make("thread-antigravity-thought-level"); + const xhighSelection = { + instanceId: h.instance.instanceId, + model: "gemini-test-low", + options: [{ id: "thought_level", value: "xhigh" }], + }; + const nativeSessionId = yield* Effect.scoped( + Effect.gen(function* () { + const workspace = yield* h.fs.makeTempDirectoryScoped({ prefix: "t3-ag-thought-" }); + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "approval-required", + interactionMode: "default", + cwd: workspace, + }); + const session = yield* h.instance.orchestrationAdapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make( + "provider-session-antigravity-thought-level", + ), + modelSelection: xhighSelection, + runtimePolicy, + }); + const providerThread = yield* session.ensureThread({ + threadId, + modelSelection: xhighSelection, + runtimePolicy, + }); + const now = yield* DateTime.now; + yield* session.startTurn({ + appThread: { + createdBy: "user", + creationSource: "web", + id: threadId, + projectId: ProjectId.make("project-antigravity-thought-level"), + title: "Antigravity thought level", + providerInstanceId: h.instance.instanceId, + modelSelection: xhighSelection, + runtimeMode: "approval-required", + interactionMode: "default", + branch: null, + worktreePath: null, + activeProviderThreadId: providerThread.id, + lineage: { + parentThreadId: null, + relationshipToParent: null, + rootThreadId: threadId, + }, + forkedFrom: null, + createdAt: now, + updatedAt: now, + archivedAt: null, + settledOverride: null, + settledAt: null, + lastVisitedAt: null, + deletedAt: null, + }, + threadId, + runId: RunId.make("run-antigravity-thought-level"), + runOrdinal: 1, + providerTurnOrdinal: 1, + attemptId: RunAttemptId.make("attempt-antigravity-thought-level"), + rootNodeId: NodeId.make("node-antigravity-thought-level"), + providerThread, + message: { + createdBy: "user", + creationSource: "web", + messageId: MessageId.make("message-antigravity-thought-level"), + text: "Say ok.", + attachments: [], + }, + modelSelection: xhighSelection, + runtimePolicy, + }); + yield* session.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runDrain, + ); + const nativeId = providerThread.nativeThreadRef?.nativeId; + if (!nativeId) { + return yield* Effect.die("Expected Antigravity session to have a native thread id"); + } + return nativeId; + }), + ); + + const afterLiveSession = yield* h.instance.snapshot.getSnapshot; + expect(levelOf(afterLiveSession, "gemini-test-low")).toBe("high"); + expect(levelOf(afterLiveSession, "gemini-test-high")).toBe("medium"); + expect( + afterLiveSession.models.find((model) => model.slug === "gemini-test-low")?.isDefault, + ).toBe(true); + expect( + (yield* h.readRequests) + .filter( + (request) => + request.method === "session/set_config_option" && + request.params?.configId === "thought_level", + ) + .map((request) => request.params?.value), + ).toEqual(["xhigh"]); + + // Resuming a session whose saved level is xhigh must also keep the catalog default. + yield* Effect.scoped( + Effect.gen(function* () { + const workspace = yield* h.fs.makeTempDirectoryScoped({ + prefix: "t3-ag-thought-resume-", + }); + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "approval-required", + interactionMode: "default", + cwd: workspace, + }); + const resumed = yield* h.instance.orchestrationAdapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make( + "provider-session-antigravity-thought-level-resumed", + ), + modelSelection: xhighSelection, + runtimePolicy, + initialNativeThreadId: nativeSessionId, + }); + yield* resumed.ensureThread({ + threadId, + modelSelection: xhighSelection, + runtimePolicy, + }); + }), + ); + expect(levelOf(yield* h.instance.snapshot.getSnapshot, "gemini-test-low")).toBe("high"); + yield* h.assertClosed; + }), + ); }); diff --git a/apps/server/src/provider/Drivers/AntigravityDriver.ts b/apps/server/src/provider/Drivers/AntigravityDriver.ts index fa1c5fffa3233..36c8e68123c08 100644 --- a/apps/server/src/provider/Drivers/AntigravityDriver.ts +++ b/apps/server/src/provider/Drivers/AntigravityDriver.ts @@ -507,7 +507,7 @@ export const AntigravityDriver: ProviderDriver< return Deferred.succeed(event.acknowledge, undefined).pipe(Effect.asVoid); } if (event._tag === "ConfigOptionsUpdated") { - return provider.onConfigOptionsUpdated(event.configOptions); + return provider.onConfigOptionsUpdated(event.configOptions, { fromCatalogProbe: true }); } return event._tag === "AvailableCommandsUpdated" ? provider.onAvailableCommands(event.availableCommands) @@ -631,8 +631,10 @@ export const AntigravityDriver: ProviderDriver< ), ), profileDirectory, - onSessionStarted: (started, cwd) => - provider.onSessionStarted(started, cwd).pipe(Effect.andThen(authFlow.onSignedInElsewhere)), + onSessionStarted: (started, cwd, session) => + provider + .onSessionStarted(started, cwd, session) + .pipe(Effect.andThen(authFlow.onSignedInElsewhere)), onSessionEvent: (event, cwd) => { if (event._tag === "ConfigOptionsUpdated") { return provider.onConfigOptionsUpdated(event.configOptions); diff --git a/apps/server/src/provider/ProviderRegistry.ts b/apps/server/src/provider/ProviderRegistry.ts index 27401b64e64d8..0ef0c74cefe5b 100644 --- a/apps/server/src/provider/ProviderRegistry.ts +++ b/apps/server/src/provider/ProviderRegistry.ts @@ -289,14 +289,30 @@ const mergeProviderModels = ( } const previousBySlug = new Map(previousModels.map((model) => [model.slug, model] as const)); + const preserveDefault = + nextModels.length > 0 && !nextModels.some((model) => model.isDefault === true); const mergedModels = nextModels.map((model) => { const previousModel = previousBySlug.get(model.slug); - if (!previousModel || hasModelCapabilities(model) || !hasModelCapabilities(previousModel)) { + if (!previousModel) { return model; } + const retainCapabilities = !hasModelCapabilities(model) && hasModelCapabilities(previousModel); + const retainDefault = preserveDefault && previousModel.isDefault === true; + if (!retainCapabilities && !retainDefault) { + return model; + } + const aliases = retainDefault + ? [...new Set([...(model.aliases ?? []), ...(previousModel.aliases ?? [])])] + : undefined; return { ...model, - capabilities: previousModel.capabilities, + ...(retainCapabilities ? { capabilities: previousModel.capabilities } : {}), + ...(retainDefault + ? { + isDefault: true, + ...(aliases && aliases.length > 0 ? { aliases } : {}), + } + : {}), }; }); const nextSlugs = new Set(nextModels.map((model) => model.slug)); From a3a4592cf53e070aa4dc6f82f6c66ea977f03318 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Wed, 25 Nov 2026 18:01:48 +0100 Subject: [PATCH 063/238] fix(web): release terminal reply ownership when the drawer closes (#42897) Co-authored-by: Julius Marminge --- apps/server/src/terminal/Manager.test.ts | 34 ++++ apps/server/src/terminal/Manager.ts | 15 +- .../ThreadTerminalDrawer.browser.test.tsx | 163 ++++++++++++++---- .../src/components/ThreadTerminalDrawer.tsx | 73 +++++--- .../terminal/terminalInputWriter.ts | 16 +- .../src/state/terminalSession.ts | 12 ++ packages/contracts/src/terminal.ts | 9 + .../terminal-query-after-viewer-closes.e2e.ts | 156 +++++++++++++++++ 8 files changed, 419 insertions(+), 59 deletions(-) create mode 100644 scripts/scenarios/terminal-query-after-viewer-closes.e2e.ts diff --git a/apps/server/src/terminal/Manager.test.ts b/apps/server/src/terminal/Manager.test.ts index dbc3bb95e8adf..9773e2dd19350 100644 --- a/apps/server/src/terminal/Manager.test.ts +++ b/apps/server/src/terminal/Manager.test.ts @@ -1013,6 +1013,40 @@ it.layer( }), ); + it.effect("rejects conditional paste chunks when the process has gone", () => + Effect.gen(function* () { + const { manager, ptyAdapter } = yield* createManager(); + const input = openInput(); + const original = yield* manager.open(input); + if (original.pid === null) throw new Error("Expected a running terminal"); + expect(original.supportsConditionalWrites).toBe(true); + const pasteChunk = { + threadId: input.threadId, + terminalId: original.terminalId, + data: "\x1b[200~paste", + expectedPid: original.pid, + }; + yield* manager.write(pasteChunk); + yield* manager.close({ threadId: input.threadId, terminalId: original.terminalId }); + expect(yield* manager.write(pasteChunk).pipe(Effect.flip)).toMatchObject({ + _tag: "TerminalProcessChangedError", + }); + yield* manager.open(input); + expect(yield* manager.write(pasteChunk).pipe(Effect.flip)).toMatchObject({ + _tag: "TerminalProcessChangedError", + }); + yield* manager.write({ + threadId: input.threadId, + terminalId: original.terminalId, + data: "after", + }); + expect(ptyAdapter.processes.map(({ writes }) => writes)).toEqual([ + [pasteChunk.data], + ["after"], + ]); + }), + ); + it.effect("supports multiple terminals per thread independently", () => Effect.gen(function* () { const { manager, ptyAdapter } = yield* createManager(); diff --git a/apps/server/src/terminal/Manager.ts b/apps/server/src/terminal/Manager.ts index 9aa897b970410..d71f4e2266c9a 100644 --- a/apps/server/src/terminal/Manager.ts +++ b/apps/server/src/terminal/Manager.ts @@ -16,6 +16,7 @@ import { TerminalError, TerminalHistoryError, TerminalNotRunningError, + TerminalProcessChangedError, TerminalProviderInstanceNotFoundError, TerminalProviderEnvironmentError, TerminalResizeError, @@ -421,6 +422,7 @@ function snapshot( worktreePath: session.worktreePath, status: session.status, pid: session.pid, + supportsConditionalWrites: true, ...snapshotHistory(session, supportsSnapshotSequenceState), exitCode: session.exitCode, exitSignal: session.exitSignal, @@ -3878,8 +3880,19 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func const write: TerminalManager["Service"]["write"] = Effect.fn("terminal.write")( function* (input, viewerId) { const terminalId = input.terminalId; - const session = yield* requireSession(input.threadId, terminalId); + const found = yield* getSession(input.threadId, terminalId); + if (Option.isNone(found)) { + if (input.expectedPid !== undefined) return yield* new TerminalProcessChangedError(); + return yield* new TerminalSessionLookupError({ threadId: input.threadId, terminalId }); + } + const session = found.value; const process = session.process; + if ( + input.expectedPid !== undefined && + (process?.pid !== input.expectedPid || session.status !== "running") + ) { + return yield* new TerminalProcessChangedError(); + } if (!process || session.status !== "running") { if (session.status === "exited") return; return yield* new TerminalNotRunningError({ diff --git a/apps/web/src/components/ThreadTerminalDrawer.browser.test.tsx b/apps/web/src/components/ThreadTerminalDrawer.browser.test.tsx index 7632d01b5f907..ce66728a146ff 100644 --- a/apps/web/src/components/ThreadTerminalDrawer.browser.test.tsx +++ b/apps/web/src/components/ThreadTerminalDrawer.browser.test.tsx @@ -5,9 +5,11 @@ import { import { EnvironmentId, ThreadId, + TerminalProcessChangedError, type ScopedThreadRef, type FilesystemEntryMetadata, type ResolvedKeybindingsConfig, + type TerminalSummary, } from "@t3tools/contracts"; import { Cause } from "effect"; import { compileResolvedKeybindingsConfig, DEFAULT_KEYBINDINGS } from "@t3tools/shared/keybindings"; @@ -23,23 +25,34 @@ import ThreadTerminalDrawer from "./ThreadTerminalDrawer"; const fixture = vi.hoisted(() => ({ statusByThreadId: new Map(), + supportsConditionalWrites: true, pendingSurfaces: [] as Array<() => void>, typeIntoSurface: null as ((data: string) => void) | null, pressKey: null as ((event: KeyboardEvent) => boolean) | null, - writes: [] as Array<{ threadId: string; data: string }>, + writes: [] as Array<{ threadId: string; data: string; expectedPid?: number }>, messages: [] as string[], resetSessions: () => {}, + terminalMetadata: ( + _environmentId: EnvironmentId, + ): Atom.Atom>> => + Atom.make(AsyncResult.success([])), + setMetadataPid: (_thread: ScopedThreadRef, _pid: number) => {}, setSession: ( _thread: ScopedThreadRef, _status: "closed" | "starting" | "running", _version: number, _generation?: number, ) => {}, - sessionEvent: (_thread: ScopedThreadRef, _type: "snapshot" | "restarted", _pid = 123) => {}, + sessionEvent: ( + _thread: ScopedThreadRef, + _type: "snapshot" | "restarted" | "closed", + _pid = 123, + ) => {}, surfaceOptions: [] as GhosttyTerminalSurfaceOptions[], reportedSize: null as { cols: number; rows: number } | null, resizeCommand: {}, - runWrite: (): Promise<{ _tag: "Success" }> => Promise.resolve({ _tag: "Success" }), + runWrite: (): Promise<{ _tag: "Success" } | AsyncResult.Failure> => + Promise.resolve({ _tag: "Success" }), runResize: (_input: unknown): Promise> => Promise.resolve(AsyncResult.success(undefined)), metadata: new Map< @@ -97,6 +110,8 @@ vi.mock("../state/terminalSessions", async () => { Atom.make({ ...EMPTY_TERMINAL_SESSION_STATE, summary: summary(threadId, 123), + pid: 123, + supportsConditionalWrites: fixture.supportsConditionalWrites, status: fixture.statusByThreadId.get(threadId) ?? "closed", version: 1, }); @@ -110,6 +125,17 @@ vi.mock("../state/terminalSessions", async () => { fixture.resetSessions = () => { sessions = new Map(); }; + const metadata = Atom.family((_environmentId: EnvironmentId) => + Atom.make>>( + AsyncResult.waiting(AsyncResult.success([])), + ).pipe(Atom.keepAlive), + ); + fixture.terminalMetadata = metadata; + fixture.setMetadataPid = (thread, pid) => + appAtomRegistry.set( + metadata(thread.environmentId), + AsyncResult.waiting(AsyncResult.success([summary(thread.threadId, pid)])), + ); fixture.setSession = (thread, status, version, generation) => { appAtomRegistry.set(session(thread.environmentId, thread.threadId), { ...EMPTY_TERMINAL_SESSION_STATE, @@ -125,24 +151,28 @@ vi.mock("../state/terminalSessions", async () => { const current = appAtomRegistry.get(atom); appAtomRegistry.set(atom, { ...current, - summary: summary(thread.threadId, pid), ...applyTerminalAttachStreamEvent(current, { - type, threadId: thread.threadId, terminalId: "term-1", - snapshot: { - threadId: thread.threadId, - terminalId: "term-1", - cwd: "/repo", - worktreePath: null, - status: "running", - pid, - history: "", - exitCode: null, - exitSignal: null, - label: "Terminal 1", - updatedAt: "2026-11-15T00:00:00.000Z", - }, + ...(type === "closed" + ? { type } + : { + type, + snapshot: { + threadId: thread.threadId, + terminalId: "term-1", + cwd: "/repo", + worktreePath: null, + status: "running", + pid, + supportsConditionalWrites: fixture.supportsConditionalWrites, + history: "", + exitCode: null, + exitSignal: null, + label: "Terminal 1", + updatedAt: "2026-11-15T00:00:00.000Z", + }, + }), }), }); }; @@ -157,10 +187,16 @@ vi.mock("../state/session", () => ({ })); vi.mock("../state/use-atom-command", () => ({ useAtomCommand: - (command: object) => async (args: { input: { threadId: string; data?: string } }) => { + (command: object) => + async (args: { input: { threadId: string; data?: string; expectedPid?: number } }) => { if (command === fixture.resizeCommand) return fixture.runResize(args); if (args.input.data !== undefined) { - fixture.writes.push({ threadId: args.input.threadId, data: args.input.data }); + const { threadId, data, expectedPid } = args.input; + fixture.writes.push({ + threadId, + data, + ...(expectedPid === undefined ? {} : { expectedPid }), + }); return fixture.runWrite(); } return { _tag: "Success" }; @@ -173,7 +209,12 @@ vi.mock("../state/server", async () => { return { serverEnvironment: { configValueAtom: () => config } }; }); vi.mock("../state/terminal", () => ({ - terminalEnvironment: { write: {}, resize: fixture.resizeCommand }, + terminalEnvironment: { + write: {}, + resize: fixture.resizeCommand, + metadata: ({ environmentId }: { environmentId: EnvironmentId }) => + fixture.terminalMetadata(environmentId), + }, })); vi.mock("../state/preview", () => ({ previewEnvironment: { open: {} } })); vi.mock("../state/projects", async () => { @@ -264,6 +305,7 @@ function setup(originalStatus: "starting" | "exited" = "exited") { fixture.reportedSize = null; fixture.runResize = () => Promise.resolve(AsyncResult.success(undefined)); fixture.runWrite = () => Promise.resolve({ _tag: "Success" }); + fixture.supportsConditionalWrites = true; fixture.metadata.clear(); useRightPanelStore.setState(useRightPanelStore.getInitialState()); useTerminalUiStateStore.setState(useTerminalUiStateStore.getInitialState()); @@ -450,12 +492,16 @@ it("drops the rest of a split paste when the shell restarts mid-paste", async () }); it.each([ - { pid: 123, closes: true }, - { pid: 456, closes: false }, + { pid: 123, guarded: true, recovers: true }, + { pid: 456, guarded: true, recovers: true }, + { pid: 123, guarded: false, recovers: true }, + { pid: 456, guarded: false, recovers: false }, ])( - "closes interrupted bracket framing only for its process (PID $pid)", - async ({ pid, closes }) => { + "recovers interrupted paste with conditional writes $guarded and attachment PID $pid", + async ({ pid, guarded, recovers }) => { const { other: threadRef } = setup(); + fixture.supportsConditionalWrites = guarded; + if (!guarded) fixture.setMetadataPid(threadRef, 123); let settleWrite = () => {}; fixture.runWrite = () => new Promise((resolve) => { @@ -480,14 +526,73 @@ it.each([ expect( fixture.messages.filter((message) => message.includes("paste interrupted")), ).toHaveLength(1); - expect(fixture.writes.map(({ data }) => data)).toEqual([ - large.slice(0, 65_536), - ...(closes ? ["\x1b[201~"] : []), - "after", + const identity = guarded ? { expectedPid: 123 } : {}; + expect(fixture.writes.map(({ threadId: _, ...write }) => write)).toEqual([ + { data: large.slice(0, 65_536), ...identity }, + ...(recovers ? [{ data: "\x1b[201~", ...identity }] : []), + { data: "after" }, ]); }, ); +it.each(["metadata first", "closed"] as const)( + "clears legacy paste recovery when the process is gone (%s)", + async (change) => { + const { other: threadRef } = setup(); + fixture.supportsConditionalWrites = false; + fixture.setMetadataPid(threadRef, 123); + let failWrite = () => {}; + fixture.runWrite = () => + new Promise((resolve) => { + failWrite = () => { + fixture.runWrite = () => Promise.resolve({ _tag: "Success" }); + resolve(AsyncResult.failure(Cause.die(new Error("acknowledgement lost")))); + }; + }); + await using _screen = await render( {}} />); + await act(async () => { + fixture.pendingSurfaces.shift()?.(); + }); + const paste = `\x1b[200~${"p".repeat(70_000)}\x1b[201~`; + fixture.typeIntoSurface?.(paste); + await act(async () => { + if (change === "closed") fixture.sessionEvent(threadRef, "closed"); + else fixture.setMetadataPid(threadRef, 456); + failWrite(); + }); + expect(fixture.writes.map(({ data }) => data)).toEqual([paste.slice(0, 65_536)]); + await act(async () => { + // After close, reopen without a PID change to expose any stale recovery obligation. + fixture.sessionEvent(threadRef, "snapshot", change === "closed" ? 123 : 456); + fixture.typeIntoSurface?.("after"); + }); + expect(fixture.writes.map(({ data }) => data)).toEqual([paste.slice(0, 65_536), "after"]); + }, +); + +it("stops a split paste on its original process once that process is replaced", async () => { + const { other: threadRef } = setup(); + fixture.runWrite = async () => + fixture.writes.length >= 2 && fixture.writes.at(-1)?.expectedPid !== undefined + ? AsyncResult.failure(Cause.fail(new TerminalProcessChangedError())) + : { _tag: "Success" }; + await using _screen = await render( {}} />); + await act(async () => { + fixture.pendingSurfaces.shift()?.(); + }); + const paste = `\x1b[200~${"p".repeat(140_000)}\x1b[201~`; + await act(async () => { + fixture.typeIntoSurface?.(paste); + fixture.typeIntoSurface?.("after"); + }); + expect(fixture.writes.map(({ data, expectedPid }) => ({ data, expectedPid }))).toEqual([ + { data: paste.slice(0, 65_536), expectedPid: 123 }, + { data: paste.slice(65_536, 131_072), expectedPid: 123 }, + { data: "\x1b[201~", expectedPid: 123 }, + { data: "after", expectedPid: undefined }, + ]); +}); + it("closes an interrupted paste after disposal before input from a remounted view", async () => { const { other: threadRef } = setup(); let settleWrite = () => {}; diff --git a/apps/web/src/components/ThreadTerminalDrawer.tsx b/apps/web/src/components/ThreadTerminalDrawer.tsx index b3871f5b28970..9bc43233585d7 100644 --- a/apps/web/src/components/ThreadTerminalDrawer.tsx +++ b/apps/web/src/components/ThreadTerminalDrawer.tsx @@ -29,6 +29,7 @@ import { AuthFilesystemReadScope, AuthOrchestrationOperateScope, AuthTerminalOperateScope, + TerminalProcessChangedError, type ContextMenuItem, type ProviderInstanceId, type ResolvedKeybindingsConfig, @@ -451,6 +452,8 @@ function terminalContextMenuItems(options: { ]; } +const isTerminalProcessChanged = Schema.is(TerminalProcessChangedError); + /** * A writable session's output generation. A new one is a fresh PTY (or a * reconnect) that has not seen the surface's grid yet. @@ -962,14 +965,17 @@ function TerminalSessionViewport({ } }; - const readInputSession = () => appAtomRegistry.get(terminalSessionAtom); const canWriteInput = () => readEnvironmentScope(environmentId, AuthTerminalOperateScope); - const writeInputChunk = (data: string, kind?: "binary" | "reply") => + const writeInputChunk = (data: string, kind?: "binary" | "reply", expectedPid?: number) => retainedTerminalWrite.current({ environmentId, - input: kind - ? { threadId, terminalId, data, [kind]: true } - : { threadId, terminalId, data }, + input: { + threadId, + terminalId, + data, + ...(kind === undefined ? {} : { [kind]: true }), + ...(expectedPid === undefined ? {} : { expectedPid }), + }, }); const sendTerminalInput = ( data: string, @@ -984,7 +990,6 @@ function TerminalSessionViewport({ if (generation === null) return; const writeInput = terminalInputWriter( JSON.stringify([environmentId, threadId, terminalId]), - () => appAtomRegistry.mount(terminalSessionAtom), ); let reported = false; const report = (message: string) => { @@ -994,35 +999,63 @@ function TerminalSessionViewport({ }; return writeInput( data, - async (chunk) => { - const currentSession = readInputSession(); + async (chunk, split) => { + if (terminalRef.current !== terminal) return "not-dispatched"; + const currentSession = appAtomRegistry.get(terminalSessionAtom); if ( - terminalRef.current !== terminal || currentSession.lifecycleVersion !== lifecycleVersion || writableSessionGeneration(currentSession, canWriteInput()) !== generation ) { return "not-dispatched"; } - const result = await writeInputChunk(chunk, kind); + const expectedPid = + split && session.supportsConditionalWrites ? session.pid : undefined; + if (expectedPid === null) return "not-dispatched"; + const result = await writeInputChunk(chunk, kind, expectedPid); if (result._tag === "Success") return true; + const error = squashAtomCommandFailure(result); + if (isTerminalProcessChanged(error)) return "not-dispatched"; if (terminalRef.current === terminal && !isAtomCommandInterrupted(result)) { - const error = squashAtomCommandFailure(result); report(thrownErrorMessage(error, m) ?? fallbackError); } return false; }, - // Close the bracket only for the process that saw it open; wait while its pid is unknown. + // The attachment's PID stays with the paste even after the viewport detaches. async () => { - const pid = session.summary?.pid ?? null; - const current = readInputSession(); - const currentPid = current.summary?.pid ?? null; - if (currentPid === null) return false; - if (pid !== null && currentPid !== pid) return true; - if (writableSessionGeneration(current, canWriteInput()) === null) return false; - const result = await writeInputChunk("\x1b[201~"); + if (session.pid === null) return true; + if (!canWriteInput()) return false; + if (!session.supportsConditionalWrites) { + const attached = + terminalRef.current === terminal ? appAtomRegistry.get(terminalSessionAtom) : null; + if (attached && attached.version > 0) { + if (attached.status === "closed" || attached.status === "exited") return true; + if (attached.pid !== null && attached.pid !== session.pid) return true; + } + const metadata = appAtomRegistry.get( + terminalEnvironment.metadata({ environmentId, input: null }), + ); + if (!AsyncResult.isSuccess(metadata)) return false; + const current = metadata.value.find( + (item) => item.threadId === threadId && item.terminalId === terminalId, + ); + if (current?.pid == null) return false; + if (attached) { + // An unguarded write needs both streams to agree the original PTY is running. + if (attached.status !== "running" || attached.pid !== current.pid) return false; + } else if (current.pid !== session.pid || current.status === "exited") { + return true; + } + if (current.status !== "running" || current.pid !== session.pid) return false; + } + const result = await writeInputChunk( + "\x1b[201~", + undefined, + session.supportsConditionalWrites ? session.pid : undefined, + ); if (result._tag === "Success") return true; + const error = squashAtomCommandFailure(result); + if (isTerminalProcessChanged(error)) return true; if (!isAtomCommandInterrupted(result)) { - const error = squashAtomCommandFailure(result); report(thrownErrorMessage(error, m) ?? m(msg("Failed to close interrupted paste"))); } return false; diff --git a/apps/web/src/components/terminal/terminalInputWriter.ts b/apps/web/src/components/terminal/terminalInputWriter.ts index 4d269ae86eab4..ab7e7033ee7e2 100644 --- a/apps/web/src/components/terminal/terminalInputWriter.ts +++ b/apps/web/src/components/terminal/terminalInputWriter.ts @@ -1,7 +1,7 @@ import { chunkTerminalWrite } from "@t3tools/contracts"; /** Sends one chunk of terminal input; resolves false when it failed and the rest should drop. */ -type SendTerminalChunk = (chunk: string) => Promise; +type SendTerminalChunk = (chunk: string, split: boolean) => Promise; /** * Orders one terminal's input into writes that fit `terminal.write`. A split write goes one chunk @@ -30,15 +30,15 @@ export function createTerminalInputWriter(onIdle = () => {}) { interrupted(); return; } - const bracketed = - chunks.length > 1 && data.startsWith("\x1b[200~") && data.endsWith("\x1b[201~"); + const split = chunks.length > 1; + const bracketed = split && data.startsWith("\x1b[200~") && data.endsWith("\x1b[201~"); let opened = false; try { for (const chunk of chunks) { - const result = await send(chunk); + const result = await send(chunk, split); if (result !== true) { if (result !== "not-dispatched") opened = bracketed; - if (chunks.length > 1) interrupted(); + if (split) interrupted(); return; } opened = bracketed; @@ -55,7 +55,7 @@ export function createTerminalInputWriter(onIdle = () => {}) { return ( data: string, send: SendTerminalChunk, - recover: () => Promise = async () => (await send("\x1b[201~")) === true, + recover: () => Promise = async () => (await send("\x1b[201~", true)) === true, interrupted = () => {}, ): Promise => { const idle = () => { @@ -93,13 +93,11 @@ export function createTerminalInputWriter(onIdle = () => {}) { const writers = new Map>(); /** Retain ordering and framing obligations until acknowledged, across terminal view remounts. */ -export function terminalInputWriter(key: string, retain: () => () => void) { +export function terminalInputWriter(key: string) { const existing = writers.get(key); if (existing) return existing; - const release = retain(); const writer = createTerminalInputWriter(() => { if (writers.get(key) === writer) writers.delete(key); - release(); }); writers.set(key, writer); return writer; diff --git a/packages/client-runtime/src/state/terminalSession.ts b/packages/client-runtime/src/state/terminalSession.ts index 4eb84e9b192ae..6ad955c32afc9 100644 --- a/packages/client-runtime/src/state/terminalSession.ts +++ b/packages/client-runtime/src/state/terminalSession.ts @@ -34,6 +34,8 @@ export interface TerminalGrid { export interface TerminalSessionState { readonly summary: TerminalSummary | null; + readonly pid: number | null; + readonly supportsConditionalWrites: boolean; readonly output: TerminalOutputState; /** Null when the server predates shared terminal geometry. */ readonly grid: TerminalGrid | null; @@ -46,6 +48,8 @@ export interface TerminalSessionState { } export interface TerminalBufferState { + readonly pid: number | null; + readonly supportsConditionalWrites: boolean; readonly output: TerminalOutputState; readonly grid: TerminalGrid | null; readonly status: TerminalSessionSnapshot["status"] | "closed"; @@ -75,6 +79,8 @@ export function selectRunningSubprocessTerminalIds( } export const EMPTY_TERMINAL_BUFFER_STATE = Object.freeze({ + pid: null, + supportsConditionalWrites: false, output: EMPTY_TERMINAL_OUTPUT_STATE, grid: null, status: "closed", @@ -86,6 +92,8 @@ export const EMPTY_TERMINAL_BUFFER_STATE = Object.freeze({ export const EMPTY_TERMINAL_SESSION_STATE = Object.freeze({ summary: null, + pid: null, + supportsConditionalWrites: false, output: EMPTY_TERMINAL_OUTPUT_STATE, grid: null, status: "closed", @@ -115,6 +123,8 @@ function terminalBufferStateFromSnapshot( current: TerminalBufferState = EMPTY_TERMINAL_BUFFER_STATE, ): TerminalBufferState { return { + pid: snapshot.pid, + supportsConditionalWrites: snapshot.supportsConditionalWrites === true, output: resetOutput(current.output, snapshot, maxBufferBytes), grid: nextGrid(current.grid, snapshot), status: snapshot.status, @@ -147,6 +157,8 @@ export function combineTerminalSessionState( ): TerminalSessionState { return { summary, + pid: buffer.pid, + supportsConditionalWrites: buffer.supportsConditionalWrites, output: buffer.output, grid: buffer.grid, status: buffer.version > 0 ? buffer.status : (summary?.status ?? buffer.status), diff --git a/packages/contracts/src/terminal.ts b/packages/contracts/src/terminal.ts index be05d30a7aa1e..93d5164e9b98b 100644 --- a/packages/contracts/src/terminal.ts +++ b/packages/contracts/src/terminal.ts @@ -283,6 +283,8 @@ export const TerminalWriteInput = Schema.Struct({ // A renderer's answer to a terminal query (DA, DSR, DECRQM). Every attached renderer // answers, so the server passes on one viewer's replies; older servers ignore it. reply: Schema.optionalKey(Schema.Boolean), + // Reject the write if the process that owns the paste has gone. + expectedPid: Schema.optionalKey(Schema.Int.check(Schema.isGreaterThan(0))), }); export type TerminalWriteInput = Schema.Codec.Encoded; @@ -329,6 +331,7 @@ export const TerminalSessionSnapshot = Schema.Struct({ worktreePath: Schema.NullOr(TrimmedNonEmptyStringSchema), status: TerminalSessionStatus, pid: Schema.NullOr(Schema.Int.check(Schema.isGreaterThan(0))), + supportsConditionalWrites: Schema.optional(Schema.Boolean), history: Schema.String, // Parser state of an unfinished prefix omitted after the replayable history. historySequenceState: Schema.optional( @@ -605,6 +608,11 @@ export class TerminalResizeError extends Schema.TaggedError } } +export class TerminalProcessChangedError extends Schema.TaggedError()( + "TerminalProcessChangedError", + {}, +) {} + export const TerminalError = Schema.Union([ TerminalCwdError, TerminalHistoryError, @@ -612,6 +620,7 @@ export const TerminalError = Schema.Union([ TerminalProviderInstanceNotFoundError, TerminalProviderEnvironmentError, TerminalNotRunningError, + TerminalProcessChangedError, TerminalWriteError, TerminalResizeError, ]); diff --git a/scripts/scenarios/terminal-query-after-viewer-closes.e2e.ts b/scripts/scenarios/terminal-query-after-viewer-closes.e2e.ts new file mode 100644 index 0000000000000..d51087e0641cc --- /dev/null +++ b/scripts/scenarios/terminal-query-after-viewer-closes.e2e.ts @@ -0,0 +1,156 @@ +/// +import { expect } from "e2e"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; + +import { runPromise, test, WEB } from "./t3.ts"; + +const PROBE = String.raw`import { existsSync, writeFileSync } from "node:fs"; +const file = (name) => new URL(name, import.meta.url); +const ask = () => process.stdout.write("\x1b[6n"); +let buffer = ""; +let secondQuery = false; +process.stdin.setRawMode(true); +process.stdin.on("data", (chunk) => { + buffer += chunk.toString(); + if (buffer.includes("s")) writeFileSync(file("second-ready"), "ready"); + if (!/\x1b\[\d+;\d+R/.test(buffer)) return; + buffer = buffer.replace(/\x1b\[\d+;\d+R/, ""); + if (secondQuery) { + writeFileSync(file("answer"), "reply received"); + process.stdout.write("\r\nReply received\r\n"); + } else { + writeFileSync(file("first-ready"), "ready"); + } +}); +ask(); +const timer = setInterval(() => { + if (!existsSync(file("ask-again"))) return; + clearInterval(timer); + secondQuery = true; + process.stdout.write("\r\nWaiting for cursor position...\r\n"); + ask(); +}, 50); +`; + +test( + "A second viewer answers terminal queries after the first viewer closes during a pending write", + WEB, + async ({ t3, app, browser, screen }) => { + await browser.emulateMedia({ colorScheme: "dark" }); + const project = await t3.project("demo", { "cursor-probe.mjs": PROBE }); + const thread = await t3.thread({ project, title: "Shared terminal", messages: ["hello"] }); + const read = (name: string) => + runPromise( + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + return yield* fs.readFileString(`${project}/${name}`); + }).pipe(Effect.orElseSucceed(() => "")), + ); + + // Delay one ordinary keystroke on the first connection to model a write in flight. + await browser.addInitScript(() => { + if (window !== window.top) return; + const send = WebSocket.prototype.send; + WebSocket.prototype.send = function (data) { + if ( + document.body?.dataset.holdTerminalWrite === "true" && + typeof data === "string" && + data.includes('"data":"x"') + ) { + document.body.dataset.terminalWritePending = "true"; + const socket = this; + window.addEventListener("release-terminal-write", () => send.call(socket, data), { + once: true, + }); + return; + } + return send.call(this, data); + }; + }); + + await t3.open(thread); + const toggle = screen.getByRole("button", "Toggle terminal drawer"); + const first = screen.getByLabel("Terminal input"); + await browser.evaluate(() => { + const frame = document.createElement("iframe"); + frame.id = "second-viewer"; + frame.src = location.pathname; + frame.style.cssText = + "position:fixed;inset:0;width:100%;height:100%;border:0;z-index:2147483647"; + document.body.append(frame); + return null; + }); + const second = browser.frameLocator("#second-viewer"); + const secondInput = second.getByLabel("Terminal input"); + const secondToggle = second.getByRole("button", "Toggle terminal drawer"); + await secondToggle.waitFor(); + const showSecond = (show: boolean) => + browser.evaluate((visible) => { + document.querySelector("#second-viewer")!.style.display = visible + ? "" + : "none"; + return null; + }, show); + await showSecond(false); + await toggle.tap(); + await expect + .poll( + async () => { + await first.focus(); + await browser.keyboard.type(`echo ready > '${project}/shell-ready'`); + await browser.keyboard.press("Enter"); + return read("shell-ready"); + }, + { timeout: 20_000 }, + ) + .toBe("ready\n"); + await browser.keyboard.type(`'${process.execPath}' '${project}/cursor-probe.mjs'`); + await browser.keyboard.press("Enter"); + await expect.poll(() => read("first-ready")).toBe("ready"); + + await showSecond(true); + await secondToggle.tap(); + await secondInput.waitFor(); + await expect + .poll(async () => { + await secondInput.focus(); + await browser.keyboard.type("s"); + return read("second-ready"); + }) + .toBe("ready"); + + await showSecond(false); + await first.focus(); + await browser.evaluate(() => { + document.body.dataset.holdTerminalWrite = "true"; + return null; + }); + await browser.keyboard.type("x"); + await expect + .poll(() => browser.evaluate(() => document.body.dataset.terminalWritePending ?? "")) + .toBe("true"); + + try { + await toggle.tap(); + await first.waitFor({ state: "hidden" }); + await showSecond(true); + await runPromise( + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + yield* fs.writeFileString(`${project}/ask-again`, ""); + }), + ); + try { + await expect.poll(() => read("answer")).toBe("reply received"); + } finally { + await app.screenshot("query-after-first-viewer-closes"); + } + } finally { + await browser.evaluate(() => { + window.dispatchEvent(new Event("release-terminal-write")); + return null; + }); + } + }, +); From 1c4622955aa6f961eddf7e024a741c0993013cbe Mon Sep 17 00:00:00 2001 From: xandev641 <143331243+xandev641@users.noreply.github.com> Date: Wed, 25 Nov 2026 18:02:29 +0100 Subject: [PATCH 064/238] fix(mobile): keep CSV headings below the iPad navigation bar (#42928) Co-authored-by: Xander von Itzenplitz Co-authored-by: Julius Marminge --- apps/mobile/src/features/files/DelimitedFilePreview.tsx | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/apps/mobile/src/features/files/DelimitedFilePreview.tsx b/apps/mobile/src/features/files/DelimitedFilePreview.tsx index 281f4a3a8fdaa..c07cce86bb78c 100644 --- a/apps/mobile/src/features/files/DelimitedFilePreview.tsx +++ b/apps/mobile/src/features/files/DelimitedFilePreview.tsx @@ -3,6 +3,7 @@ import { useGT } from "gt-react-native"; import { ScrollView, View } from "react-native"; import type { parseDelimitedPreview } from "@t3tools/shared/delimitedPreview"; import { AppText as Text } from "../../components/ui/AppText"; +import { NativeScrollView } from "../../native/NativeScrollViewMarker"; import { FilePreviewNotice } from "./FilePreviewFeedback"; export function DelimitedFilePreview(props: { @@ -10,7 +11,7 @@ export function DelimitedFilePreview(props: { }) { const gt = useGT(); return ( - + {props.table.truncated ? ( {gt("Table limited to the first 100 rows and 30 columns. Source shows the rest.")} @@ -38,6 +39,6 @@ export function DelimitedFilePreview(props: { ))} - + ); } From 6bb4e3d9d647cc5bf8ea15751a0caab931ae064f Mon Sep 17 00:00:00 2001 From: Shadman Taqi <61359614+iamshadmantaqi@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:06:24 +0600 Subject: [PATCH 065/238] fix(web): comment timestamps follow 'Open links in' (#42873) Co-authored-by: Julius Marminge --- .../issue/IssueDetailPanel.browser.test.tsx | 51 ++++++++++++++++--- .../src/components/issue/IssueDetailPanel.tsx | 4 ++ .../PullRequestSummaryTab.browser.test.tsx | 45 ++++++++++++++++ .../pullRequest/PullRequestSummaryTab.tsx | 18 +++++-- 4 files changed, 107 insertions(+), 11 deletions(-) diff --git a/apps/web/src/components/issue/IssueDetailPanel.browser.test.tsx b/apps/web/src/components/issue/IssueDetailPanel.browser.test.tsx index 7b9755435a1e9..064add4ebeeb3 100644 --- a/apps/web/src/components/issue/IssueDetailPanel.browser.test.tsx +++ b/apps/web/src/components/issue/IssueDetailPanel.browser.test.tsx @@ -68,18 +68,26 @@ vi.mock(import("~/state/issues"), async (original) => { import { IssueDetailPanel } from "./IssueDetailPanel"; +const reference = { + projectId: "project-1" as never, + tracker: "github" as never, + scope: "owner/repo", + key: "7", +}; + +function setComments(comments: IssueDetail["comments"]) { + state.openLink.mockClear(); + (detail as { comments: unknown }).comments = comments; +} + describe("IssueDetailPanel", () => { it("opens the issue number through the link-target setting, not a popup", async () => { + setComments([]); const threadRef = { environmentId: "env-1", threadId: "thread-1" } as never; await using screen = await render( , ); @@ -91,4 +99,35 @@ describe("IssueDetailPanel", () => { expect(state.openLink).toHaveBeenCalledOnce(); expect(state.openLink).toHaveBeenCalledWith(url, { event: expect.anything() }); }); + + it("opens a comment's timestamp through the link-target setting, not a popup", async () => { + const commentUrl = `${url}#issuecomment-1`; + setComments([ + { + id: "1", + author: null, + body: "Same here", + createdAt: "2026-01-02T00:00:00.000Z", + url: commentUrl, + }, + ]); + await using screen = await render( + , + ); + const link = await vi.waitFor(() => { + const found = screen.container.querySelector(`a[href="${commentUrl}"]`); + expect(found).not.toBeNull(); + return found!; + }); + const click = new MouseEvent("click", { bubbles: true, cancelable: true }); + link.dispatchEvent(click); + + expect(click.defaultPrevented).toBe(true); + expect(state.openLink).toHaveBeenCalledOnce(); + expect(state.openLink).toHaveBeenCalledWith(commentUrl, { event: expect.anything() }); + }); }); diff --git a/apps/web/src/components/issue/IssueDetailPanel.tsx b/apps/web/src/components/issue/IssueDetailPanel.tsx index 38d803e896779..9bdc1cd820a6a 100644 --- a/apps/web/src/components/issue/IssueDetailPanel.tsx +++ b/apps/web/src/components/issue/IssueDetailPanel.tsx @@ -902,6 +902,10 @@ export function IssueDetailPanel({ render={ } + onClick={(event) => { + event.preventDefault(); + void openLink(item.comment.url!, { event }).catch(console.error); + }} > {formatRelativeTimeLabel(item.comment.createdAt, undefined, messages)} diff --git a/apps/web/src/components/pullRequest/PullRequestSummaryTab.browser.test.tsx b/apps/web/src/components/pullRequest/PullRequestSummaryTab.browser.test.tsx index d44830dc03c0b..a74b8f716604f 100644 --- a/apps/web/src/components/pullRequest/PullRequestSummaryTab.browser.test.tsx +++ b/apps/web/src/components/pullRequest/PullRequestSummaryTab.browser.test.tsx @@ -11,8 +11,11 @@ const state = vi.hoisted(() => ({ update: vi.fn(), canUpdate: true, timestampFormat: "locale" as "locale" | "12-hour" | "24-hour", + openLink: vi.fn(async () => {}), })); +vi.mock(import("~/browser/useOpenLink"), () => ({ useOpenLink: () => state.openLink })); + vi.mock(import("~/state/use-atom-command"), async (original) => ({ ...(await original()), useAtomCommand: (() => state.update) as never, @@ -51,6 +54,7 @@ function setup() { state.update.mockResolvedValue({ _tag: "Success", value: undefined }); state.canUpdate = true; state.timestampFormat = "locale"; + state.openLink.mockClear(); } import "~/index.css"; @@ -349,3 +353,44 @@ it("scrolls from the keyboard after a click inside it", async () => { await userEvent.keyboard("{PageDown}"); await vi.waitFor(() => expect(scroller.scrollTop).toBeGreaterThan(0)); }); + +it("opens comment timestamps through the link-target setting, not a popup", async () => { + setup(); + const author = { login: "reviewer", name: null, avatarUrl: null }; + const comment = (id: string, reviewState: string | null) => ({ + id, + kind: "review" as const, + body: `Remark ${id}`, + author, + createdAt: `2026-09-0${id}T00:00:00Z`, + url: `${detail.url}#review-${id}`, + path: null, + reviewState, + }); + // The dismissed review renders as a collapsed card; show it with the resolved filter on. + localStorage.setItem( + "t3code:pull-request-comment-filter:v1", + JSON.stringify({ bots: false, resolved: true }), + ); + try { + await using screen = await render({ + ...detail, + comments: [comment("1", null), comment("2", "DISMISSED")], + commentCount: 2, + }); + for (const id of ["1", "2"]) { + const href = `${detail.url}#review-${id}`; + const link = screen.container.querySelector(`a[href="${href}"]`); + expect(link, href).not.toBeNull(); + state.openLink.mockClear(); + const click = new MouseEvent("click", { bubbles: true, cancelable: true }); + link!.dispatchEvent(click); + + expect(click.defaultPrevented).toBe(true); + expect(state.openLink).toHaveBeenCalledOnce(); + expect(state.openLink).toHaveBeenCalledWith(href, { event: expect.anything() }); + } + } finally { + localStorage.removeItem("t3code:pull-request-comment-filter:v1"); + } +}); diff --git a/apps/web/src/components/pullRequest/PullRequestSummaryTab.tsx b/apps/web/src/components/pullRequest/PullRequestSummaryTab.tsx index 32a84ba235cf5..5df3b61feece4 100644 --- a/apps/web/src/components/pullRequest/PullRequestSummaryTab.tsx +++ b/apps/web/src/components/pullRequest/PullRequestSummaryTab.tsx @@ -119,11 +119,15 @@ function reviewerKey(login: string): string { function CommentIdentity({ comment, detail, + threadRef, }: { comment: PullRequestComment; detail: PullRequestDetailView; + threadRef: ScopedThreadRef | null; }) { const gt = useGT(); + const openLink = useOpenLink(threadRef); + const url = comment.url; const timestampFormat = useClientSettings((settings) => settings.timestampFormat); const actor = comment.author; const profileUrl = actor @@ -134,12 +138,16 @@ function CommentIdentity({ { + event.preventDefault(); + void openLink(url, { event }).catch(console.error); + }} /> ) : ( @@ -148,7 +156,7 @@ function CommentIdentity({ label={ <> {formatFullTimestamp(comment.createdAt, timestampFormat)} - {comment.url ? ` · ${gt("Open comment on host")}` : ""} + {url ? ` · ${gt("Open comment on host")}` : ""} } > @@ -320,7 +328,7 @@ function CollapsedComment({
    - + {replyCount > 0 ? ( {gt("{count, plural, one {{count} reply} other {{count} replies}}", { @@ -826,7 +834,7 @@ export const PullRequestSummaryTab = memo(function PullRequestSummaryTab({ >
    - + {outcome ? ( ) : comment.reviewState ? ( From e36800e61babed824d055393d62fedc961e26e3b Mon Sep 17 00:00:00 2001 From: Victor Date: Wed, 25 Nov 2026 11:13:34 -0600 Subject: [PATCH 066/238] fix(web): SQLite 1-byte BLOB previews show "[blob: 1 byte]" (#42950) Co-authored-by: Julius Marminge --- .../files/binaryPreview.worker.test.ts | 55 ++++++++++++++----- .../components/files/binaryPreview.worker.ts | 2 +- 2 files changed, 43 insertions(+), 14 deletions(-) diff --git a/apps/web/src/components/files/binaryPreview.worker.test.ts b/apps/web/src/components/files/binaryPreview.worker.test.ts index caaef354c51a0..99e089ff0ce79 100644 --- a/apps/web/src/components/files/binaryPreview.worker.test.ts +++ b/apps/web/src/components/files/binaryPreview.worker.test.ts @@ -6,6 +6,22 @@ import { type BinaryWorkerResult, } from "./binaryPreviewProtocol"; +async function startWorker() { + const worker = new EventTarget(); + let receive = (_result: BinaryWorkerResult) => {}; + vi.stubGlobal( + "self", + Object.assign(worker, { postMessage: (result: BinaryWorkerResult) => receive(result) }), + ); + vi.resetModules(); + await import("./binaryPreview.worker"); + return (input: BinaryWorkerRequest) => + new Promise((resolve) => { + receive = resolve; + worker.dispatchEvent(new MessageEvent("message", { data: input })); + }); +} + it.each([ARCHIVE_ENTRY_MAX_BYTES, ARCHIVE_ENTRY_MAX_BYTES + 1])( "only copies previewable TAR payloads with a %i-byte entry", async (size) => { @@ -47,20 +63,8 @@ it.each([ARCHIVE_ENTRY_MAX_BYTES, ARCHIVE_ENTRY_MAX_BYTES + 1])( offset += 512 + Math.ceil(entry.bytes.length / 512) * 512; } - const worker = new EventTarget(); - let receive = (_result: BinaryWorkerResult) => {}; - vi.stubGlobal( - "self", - Object.assign(worker, { postMessage: (result: BinaryWorkerResult) => receive(result) }), - ); try { - vi.resetModules(); - await import("./binaryPreview.worker"); - const request = (input: BinaryWorkerRequest) => - new Promise((resolve) => { - receive = resolve; - worker.dispatchEvent(new MessageEvent("message", { data: input })); - }); + const request = await startWorker(); using copies = vi.spyOn(Uint8Array.prototype, "slice"); expect( await request({ type: "open", kind: "archive", name: "mixed.tar", bytes: bytes.buffer }), @@ -104,3 +108,28 @@ it.each([ARCHIVE_ENTRY_MAX_BYTES, ARCHIVE_ENTRY_MAX_BYTES + 1])( } }, ); + +it("formats singular and plural byte labels for SQLite BLOB cells", async () => { + const { default: initSqlJs } = await import("sql.js"); + const SQL = await initSqlJs(); + const db = new SQL.Database(); + db.run( + "CREATE TABLE blobs(empty BLOB, one BLOB, four BLOB); INSERT INTO blobs VALUES (X'', X'FF', X'DEADBEEF');", + ); + const bytes = db.export().slice().buffer; + db.close(); + + try { + const request = await startWorker(); + await request({ type: "open", kind: "sqlite", name: "blobs.sqlite", bytes }); + expect(await request({ type: "rows", table: "blobs", page: 0 })).toEqual({ + type: "rows", + table: "blobs", + page: 0, + columns: ["empty", "one", "four"], + rows: [["[blob: 0 bytes]", "[blob: 1 byte]", "[blob: 4 bytes]"]], + }); + } finally { + vi.unstubAllGlobals(); + } +}); diff --git a/apps/web/src/components/files/binaryPreview.worker.ts b/apps/web/src/components/files/binaryPreview.worker.ts index 4c67d2826976f..d661c4eade9f3 100644 --- a/apps/web/src/components/files/binaryPreview.worker.ts +++ b/apps/web/src/components/files/binaryPreview.worker.ts @@ -180,7 +180,7 @@ async function handle(input: BinaryWorkerRequest) { .slice(0, 50) ?? []; const fields = columns.map((name) => { const field = quote(name); - return `CASE WHEN typeof(${field}) = 'blob' THEN '[blob: ' || length(${field}) || ' bytes]' ELSE substr(CAST(${field} AS TEXT), 1, 1024) END`; + return `CASE WHEN typeof(${field}) = 'blob' THEN '[blob: ' || length(${field}) || CASE length(${field}) WHEN 1 THEN ' byte]' ELSE ' bytes]' END ELSE substr(CAST(${field} AS TEXT), 1, 1024) END`; }); const result = database.exec( `SELECT ${fields.join(",")} FROM ${quote(input.table)} LIMIT ${SQLITE_PAGE_SIZE} OFFSET ${input.page * SQLITE_PAGE_SIZE}`, From 3b827b4fb358e820f8871daeafbaaf3f1a2d57a9 Mon Sep 17 00:00:00 2001 From: Simone Date: Wed, 25 Nov 2026 18:23:49 +0100 Subject: [PATCH 067/238] fix(server): preserve image descriptions in EPUB attachment text (#42925) Co-authored-by: Simone <185146821+Lucenx9@users.noreply.github.com> Co-authored-by: Julius Marminge --- apps/server/src/provider/documentTextWorker.ts | 13 +++++++++++++ .../src/provider/userInputAttachments.test.ts | 7 ++++++- 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/apps/server/src/provider/documentTextWorker.ts b/apps/server/src/provider/documentTextWorker.ts index 8d0688b551373..6f5a52030aa57 100644 --- a/apps/server/src/provider/documentTextWorker.ts +++ b/apps/server/src/provider/documentTextWorker.ts @@ -165,6 +165,19 @@ function xml(source: string, extension: string): XmlNode { if (extension === ".epub" && node.name === "ruby" && stack[1]?.name === "html") separateRubyReadings(node); if (node.name === "Fallback" && !retainCompatibilityFallback(parent, node)) return; + const alt = tag.attributes.alt; + if ( + extension === ".epub" && + node.name === "img" && + stack[1]?.name === "html" && + alt?.trim() && + !/(?:^|;)\s*(?:display\s*:\s*none|visibility\s*:\s*(?:hidden|collapse))\s*(?:!important\s*)?(?:;|$)/i.test( + String(tag.attributes.style ?? ""), + ) + ) { + node.children.push(alt); + node.hasText = true; + } if (HIDDEN.has(node.name) || (!node.hasText && node.name !== "noBreakHyphen")) return; parent.hasText = true; if (node.name === "Choice") parent.hasTextChoice = true; diff --git a/apps/server/src/provider/userInputAttachments.test.ts b/apps/server/src/provider/userInputAttachments.test.ts index 824a9f48422e7..0b3a55bd51fad 100644 --- a/apps/server/src/provider/userInputAttachments.test.ts +++ b/apps/server/src/provider/userInputAttachments.test.ts @@ -1497,7 +1497,7 @@ describe("question answer paths", () => { "OEBPS/a.xhtml": '

    Last chapter

    Price 10 8 old

    山路やまみちを歩く。東京(とうきょう)に着く。川を見る。海うみ まで。

    ', "OEBPS/b.xhtml": - 'My Novel

    First chapter

    Larkspur

    Direct div
    Direct section
  • Direct item emphasis trailing
  • Account: A
    Balance: 731Currency: USD
    HeadingTotal
    Important value731
    Before
    Inner
    After
    Neighbor
    Port
    443
    Timeout
    30 seconds

    Prefixed note

    1. Before boarding
      • Check passports
        1. Compare names
      • Confirm gate
    2. Board promptly
    3. Before landing

      • Collect bags
    ' + + 'My Novel

    First chapter

    Larkspur

    Map: North & south piers open.

    Cover art
    Display none imageInvisible image
    Direct div
    Direct section
  • Direct item emphasis trailing
  • Account: A
    Balance: 731Currency: USD
    HeadingTotal
    Important value731
    Before
    Inner
    After
    Neighbor
    Port
    443
    Timeout
    30 seconds

    Prefixed note

    1. Before boarding
      • Check passports
        1. Compare names
      • Confirm gate
    2. Board promptly
    3. Before landing

      • Collect bags
    ' + "
    1. Indented\n
      • Alpha
    ", "OEBPS/c.xhtml": '

    Root hidden

    ', }, @@ -1505,6 +1505,8 @@ describe("question answer paths", () => { "## Chapter 1", "\n# First chapter", "Larkspur", + "Map: North & south piers open.", + "Cover art", "Direct div", "Direct section", "Direct item emphasis trailing", @@ -1529,6 +1531,9 @@ describe("question answer paths", () => { "Draft note", "Hidden block", "Hidden nested", + "Hidden image text", + "Display none image", + "Invisible image", "Root hidden", ], }, From 9df77f2125aaa3d442ee15beb43759bef3ab5f28 Mon Sep 17 00:00:00 2001 From: Soroush Baraouf Date: Wed, 25 Nov 2026 12:25:36 -0500 Subject: [PATCH 068/238] fix(server): expired buffered signals no longer wake workflows (#42952) Co-authored-by: Julius Marminge --- apps/server/src/workflows/WorkflowEngine.ts | 5 +- .../src/workflows/WorkflowStore.test.ts | 53 ++++++++ apps/server/src/workflows/WorkflowStore.ts | 11 +- apps/server/src/workflows/Workflows.test.ts | 127 +++++++++++------- 4 files changed, 143 insertions(+), 53 deletions(-) diff --git a/apps/server/src/workflows/WorkflowEngine.ts b/apps/server/src/workflows/WorkflowEngine.ts index 4e87304c63b81..853b7181a2b25 100644 --- a/apps/server/src/workflows/WorkflowEngine.ts +++ b/apps/server/src/workflows/WorkflowEngine.ts @@ -1079,8 +1079,9 @@ const make = Effect.fn("WorkflowEngine.make")(function* ( yield* wake(late, answered); return "delivered" as const; } - // The kept copy went to a wait that opened, or was dropped as already delivered. - if (outcome === "gone") return "delivered" as const; + if (outcome === "claimed") continue; + if (yield* store.signalSeen(options.id)) return "delivered" as const; + return yield* new WorkflowInputError({ problem: "Buffered signal expired or was removed." }); } }); const signal: Workflows["Service"]["signal"] = Effect.fn("Workflows.signal")( diff --git a/apps/server/src/workflows/WorkflowStore.test.ts b/apps/server/src/workflows/WorkflowStore.test.ts index 1f295eed968f9..abc8d2c6e74c6 100644 --- a/apps/server/src/workflows/WorkflowStore.test.ts +++ b/apps/server/src/workflows/WorkflowStore.test.ts @@ -452,6 +452,59 @@ it.effect("one buffered signal goes to one wait, and a claimed wait keeps what w ), ); +it.effect.each([999, 1000])("buffered mail with a 1s TTL claimed after %i ms", (elapsed) => + withStore( + Effect.gen(function* () { + const store = yield* WorkflowStore.WorkflowStore; + const address = { workflow: "gate", channel: "ready" }; + yield* store.waitOpened({ + runId: "r1", + name: "go", + workflow: address.workflow, + key: address.channel, + token: "token", + schemaJson: "{}", + requestJson: null, + watchJson: null, + deadline: null, + }); + yield* store.mailPut({ + signalId: "first", + address, + valueJson: "1", + expiresAt: "1970-01-01T00:00:01.000Z", + sender, + }); + yield* store.mailPut({ + signalId: "second", + address, + valueJson: "2", + expiresAt: "1970-01-01T00:00:02.000Z", + sender, + }); + const selected = yield* store.mailNext([address]); + assert.equal(selected?.signalId, "first"); + yield* TestClock.adjust(elapsed); + const live = elapsed < 1000; + assert.deepStrictEqual( + { + next: (yield* store.mailNext([address]))?.signalId, + claim: yield* store.mailDeliver(selected!.signalId, "r1", "go", { + expired: false, + value: 1, + }), + waitOpen: (yield* store.waitAt({ runId: "r1", wait: "go" })) !== undefined, + receipt: yield* store.signalSeen("first"), + rowPresent: (yield* store.mailSender("first")) !== undefined, + }, + live + ? { next: "first", claim: "delivered", waitOpen: false, receipt: true, rowPresent: false } + : { next: "second", claim: "gone", waitOpen: true, receipt: false, rowPresent: true }, + ); + }), + ), +); + it.effect("tells the milestone hub of each run and question transition once", () => withStore( Effect.gen(function* () { diff --git a/apps/server/src/workflows/WorkflowStore.ts b/apps/server/src/workflows/WorkflowStore.ts index 5e41a16ca1670..9ec9201feff79 100644 --- a/apps/server/src/workflows/WorkflowStore.ts +++ b/apps/server/src/workflows/WorkflowStore.ts @@ -268,7 +268,7 @@ export class WorkflowStore extends Context.Service< readonly waitsClaimed: (runId: string) => Effect.Effect>; /** * Hands one buffered signal to one wait, or to none: the claim and the removal happen - * together. `gone` when another wait took the signal, `claimed` when the wait was already woken. + * together. `gone` when the signal is expired or absent, `claimed` when the wait was already woken. */ readonly mailDeliver: ( signalId: string, @@ -972,10 +972,11 @@ export const make = Effect.gen(function* () { `.pipe(Effect.orDie); }), mailDeliver: Effect.fn("WorkflowStore.mailDeliver")(function* (signalId, runId, name, woke) { - const at = yield* now; + let at = ""; const outcome = yield* sql .withTransaction( Effect.gen(function* () { + at = yield* now; // A kept copy of an id that already woke a wait straight is spent: it is dropped, so // it wakes no second wait and is not offered again. const seen = yield* sql`SELECT 1 FROM workflow_signals WHERE signal_id = ${signalId}`; @@ -990,7 +991,8 @@ export const make = Effect.gen(function* () { `; if (claimed.length === 0) return "claimed" as const; const taken = yield* sql<{ expires_at: string }>` - DELETE FROM workflow_mail WHERE signal_id = ${signalId} RETURNING expires_at + DELETE FROM workflow_mail + WHERE signal_id = ${signalId} AND expires_at > ${at} RETURNING expires_at `; // Failing undoes the claim: the wait stays open for a signal that is still there. const copy = taken[0]; @@ -1288,6 +1290,7 @@ export const make = Effect.gen(function* () { .pipe(Effect.orDie); }), mailNext: Effect.fn("WorkflowStore.mailNext")(function* (addresses, passed = new Set()) { + const at = yield* now; for (const address of addresses) { const rows = yield* sql<{ signal_id: string; @@ -1295,7 +1298,7 @@ export const make = Effect.gen(function* () { sender_json: string | null; }>` SELECT signal_id, value_json, sender_json FROM workflow_mail - WHERE address = ${mailAddress(address)} ORDER BY rowid + WHERE address = ${mailAddress(address)} AND expires_at > ${at} ORDER BY rowid `.pipe(Effect.orDie); const mail = rows.find((row) => !passed.has(row.signal_id)); if (mail !== undefined) { diff --git a/apps/server/src/workflows/Workflows.test.ts b/apps/server/src/workflows/Workflows.test.ts index abb8bedb7aaf9..40411db749969 100644 --- a/apps/server/src/workflows/Workflows.test.ts +++ b/apps/server/src/workflows/Workflows.test.ts @@ -1244,54 +1244,87 @@ it.effect("a signal sent before its wait opens is delivered when it does", () => }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), ); -it.effect("a signal buffered as its wait opens is still delivered to that wait", () => - Effect.gen(function* () { - const looked = yield* Deferred.make(); - const opened = yield* Deferred.make(); - const checked = yield* Deferred.make(); - // Holds the signal between finding no wait and buffering, while the wait opens and finds no mail. - const store = Layer.effect( - WorkflowStore.WorkflowStore, - Effect.gen(function* () { - const real = yield* WorkflowStore.make; - let first = true; - return WorkflowStore.WorkflowStore.of({ - ...real, - waitAt: (address) => - Effect.tap(real.waitAt(address), () => { - if (!("channel" in address) || address.channel !== "c9" || !first) return Effect.void; - first = false; - return Effect.andThen(Deferred.succeed(looked, undefined), Deferred.await(opened)); - }), - mailNext: (addresses, passed) => - Effect.tap(real.mailNext(addresses, passed), (mail) => - mail === undefined && !first ? Deferred.succeed(checked, undefined) : Effect.void, +it.effect.each(["stays live", "expires", "is delivered concurrently"] as const)( + "a signal buffered as its wait opens %s", + (how) => + Effect.gen(function* () { + const looked = yield* Deferred.make(); + const opened = yield* Deferred.make(); + const checked = yield* Deferred.make(); + const claiming = yield* Deferred.make(); + const claim = yield* Deferred.make(); + // Holds the signal between finding no wait and buffering, while the wait opens and finds no mail. + const store = Layer.effect( + WorkflowStore.WorkflowStore, + Effect.gen(function* () { + const real = yield* WorkflowStore.make; + let first = true; + return WorkflowStore.WorkflowStore.of({ + ...real, + waitAt: (address) => + Effect.tap(real.waitAt(address), () => { + if (!("channel" in address) || address.channel !== "c9" || !first) + return Effect.void; + first = false; + return Effect.andThen(Deferred.succeed(looked, undefined), Deferred.await(opened)); + }), + mailNext: (addresses, passed) => + Effect.tap(real.mailNext(addresses, passed), (mail) => + mail === undefined && !first ? Deferred.succeed(checked, undefined) : Effect.void, + ), + mailDeliver: (id, runId, name, woke) => + Effect.andThen( + Effect.andThen(Deferred.succeed(claiming, undefined), Deferred.await(claim)), + real.mailDeliver(id, runId, name, woke), + ), + }); + }), + ); + const { boot, clock, database } = yield* harness(store); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + const address = { workflow: "review", channel: "c9" }; + const send = workflows.signal(address, { merge: true }, { id: "s9", ttl: "1 millis" }); + const sent = yield* Effect.forkChild( + send.pipe( + Effect.match({ onFailure: (error) => error._tag, onSuccess: (outcome) => outcome }), ), - }); - }), - ); - const { boot } = yield* harness(store); - yield* boot( - Effect.gen(function* () { - const workflows = yield* Workflows.Workflows; - const sent = yield* Effect.forkChild( - workflows.signal({ workflow: "review", channel: "c9" }, { merge: true }, { id: "s9" }), - ); - yield* Deferred.await(looked); - const { runId } = yield* workflows.start( - "review", - { change: "c9" }, - { idempotencyKey: "c9" }, - ); - // Released once the open wait has looked for mail and found none. - yield* Deferred.await(checked); - yield* Deferred.succeed(opened, undefined); - assert.equal(yield* Fiber.join(sent), "delivered"); - const done = yield* workflows.waitFor(runId, status("completed")); - assert.equal(done.result, "2 checks, merge: true"); - }), - ); - }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), + ); + yield* Deferred.await(looked); + const { runId } = yield* workflows.start( + "review", + { change: "c9" }, + { idempotencyKey: "c9" }, + ); + // Released once the open wait has looked for mail and found none. + yield* Deferred.await(checked); + yield* clock.close; + yield* TestClock.adjust(0); + yield* Deferred.succeed(opened, undefined); + yield* Deferred.await(claiming); + if (how === "expires") yield* TestClock.adjust("1 millis"); + if (how === "is delivered concurrently") assert.equal(yield* send, "delivered"); + yield* Deferred.succeed(claim, undefined); + assert.equal( + yield* Fiber.join(sent), + how === "expires" ? "WorkflowInputError" : "delivered", + ); + if (how === "expires") { + const sql = yield* Effect.provide(SqlClient.SqlClient, database); + assert.lengthOf(yield* sql`SELECT 1 FROM workflow_mail WHERE signal_id = 's9'`, 1); + assert.lengthOf(yield* sql`SELECT 1 FROM workflow_signals WHERE signal_id = 's9'`, 0); + assert.equal( + yield* workflows.signal(address, { merge: false }, { id: "replacement" }), + "delivered", + ); + } + yield* clock.open; + const done = yield* workflows.waitFor(runId, status("completed")); + assert.equal(done.result, `2 checks, merge: ${how !== "expires"}`); + }).pipe(Effect.ensuring(clock.open)), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), ); it.effect("a wait another signal claimed first wakes with that signal's value", () => From b1360538c1c8a01329c2bc816a8a45a7fc325517 Mon Sep 17 00:00:00 2001 From: Victor Date: Wed, 25 Nov 2026 11:27:55 -0600 Subject: [PATCH 069/238] fix(server): DOCX merged table cells no longer shift later columns in attachment text (#42955) Co-authored-by: Julius Marminge --- .../server/src/provider/documentTextWorker.ts | 11 +++++++++-- .../src/provider/userInputAttachments.test.ts | 19 +++++++++++++++++++ 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/apps/server/src/provider/documentTextWorker.ts b/apps/server/src/provider/documentTextWorker.ts index 6f5a52030aa57..45b8acba01527 100644 --- a/apps/server/src/provider/documentTextWorker.ts +++ b/apps/server/src/provider/documentTextWorker.ts @@ -366,11 +366,18 @@ function* table(node: XmlNode): Generator { for (let index = 0; index < repeat; index++) { if (++rowCount > 10_000) throw new Truncation("Row limit"); let column = 0; + let gap = 0; for (const cell of cells) { const count = repeatCount(cell.attrs["number-columns-repeated"]); + // Word emits no cell for columns covered by w:gridSpan; pad before the next cell. + const tcPr = cell.name === "tc" ? children(cell).find((c) => c.name === "tcPr") : undefined; + const val = tcPr && children(tcPr).find((c) => c.name === "gridSpan")?.attrs.val; + const span = val ? Math.max(1, Number.parseInt(val, 10) || 1) : 1; for (let i = 0; i < count; i++) { - if (column >= 512) throw new Truncation("Column limit"); - if (column++) yield "\t"; + column += span; + if (column > 512) throw new Truncation("Column limit"); + if (gap) yield "\t".repeat(gap); + gap = span; // LibreOffice hides the contents a merge covers; the cell still holds its column. if (covered(cell)) continue; yield CELL_START; diff --git a/apps/server/src/provider/userInputAttachments.test.ts b/apps/server/src/provider/userInputAttachments.test.ts index 0b3a55bd51fad..49dcbb9929214 100644 --- a/apps/server/src/provider/userInputAttachments.test.ts +++ b/apps/server/src/provider/userInputAttachments.test.ts @@ -961,6 +961,25 @@ describe("question answer paths", () => { "Before Inner After\tNeighbor\t\u2011\n\u2011\nDemoted\nIntro. # Box title", ], }, + { + ext: "docx", + bounded: true, + parts: { + "word/document.xml": + '' + + "ABC" + + 'TailEnd' + + 'MergedTotal' + + 'ZeroNext' + + 'Wide' + + "", + }, + expected: [ + "A\tB\tC\nTail\tEnd\nMerged\t\tTotal\nZero\tNext", + "[Extracted text truncated at document extraction limits.]", + ], + absent: ["Wide"], + }, { ext: "docx", bounded: true, From 7d8c03fd999467843c70178fe655e05eeab2aeb5 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Wed, 25 Nov 2026 18:36:33 +0100 Subject: [PATCH 070/238] fix(terminal): keep other input out of large bracketed pastes (#42948) Co-authored-by: Julius Marminge --- .../terminal/ThreadTerminalRouteScreen.tsx | 36 ++--- .../features/terminal/terminalPaste.test.ts | 47 +++++- .../src/features/terminal/terminalPaste.ts | 64 ++++++-- apps/server/src/terminal/Manager.test.ts | 121 ++++++++++++++ apps/server/src/terminal/Manager.ts | 138 ++++++++++++++-- .../src/components/ThreadTerminalDrawer.tsx | 40 +++-- .../terminal/terminalInputWriter.test.ts | 22 ++- .../terminal/terminalInputWriter.ts | 38 +++-- packages/contracts/src/terminal.ts | 19 ++- ...e-keeps-input-from-other-client-out.e2e.ts | 153 ++++++++++++++++++ 10 files changed, 597 insertions(+), 81 deletions(-) create mode 100644 scripts/scenarios/terminal-paste-keeps-input-from-other-client-out.e2e.ts diff --git a/apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx b/apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx index 2136bb020ae5e..6068c6a60db33 100644 --- a/apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx +++ b/apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx @@ -3,7 +3,7 @@ import { m } from "../../i18n/messages"; import { AuthTerminalReadScope, AuthTerminalOperateScope, - chunkTerminalWrite, + type TerminalWriteInput, DEFAULT_TERMINAL_ID, EnvironmentId, ThreadId, @@ -649,7 +649,10 @@ function ThreadTerminal(props: { messages, ); - const writeInput = async (data: string): Promise => { + const writeInput = async ( + data: string, + plainWrite?: TerminalWriteInput["plainWrite"], + ): Promise => { if ( !isRunning || !readEnvironmentScope(selectedThread.environmentId, AuthTerminalOperateScope) @@ -657,21 +660,16 @@ function ThreadTerminal(props: { return false; } - // Android's IME delivers a system paste as one input, which can exceed one write. - const isSameShell = pasteSession.liveness(); - for (const chunk of chunkTerminalWrite(data)) { - if (!isSameShell()) return false; - const result = await writeTerminal({ - environmentId: selectedThread.environmentId, - input: { - threadId: selectedThread.id, - terminalId, - data: chunk, - }, - }); - if (result._tag !== "Success") return false; - } - return true; + const result = await writeTerminal({ + environmentId: selectedThread.environmentId, + input: { + threadId: selectedThread.id, + terminalId, + data, + ...(plainWrite ? { plainWrite } : {}), + }, + }); + return result._tag === "Success"; }; const pasteText = async (readText: () => Promise) => { @@ -686,7 +684,7 @@ function ThreadTerminal(props: { const writeModifiedInput = (data: string) => { if (pendingModifier === null) { - void writeInput(data); + void pasteSession.write(data, writeInput); return; } @@ -700,7 +698,7 @@ function ThreadTerminal(props: { void pasteText(Clipboard.getStringAsync); return; } - void writeInput(resolved.data); + void pasteSession.write(resolved.data, writeInput); }; const handleInput = (data: string) => { diff --git a/apps/mobile/src/features/terminal/terminalPaste.test.ts b/apps/mobile/src/features/terminal/terminalPaste.test.ts index 2545085137916..c34c9c09e087a 100644 --- a/apps/mobile/src/features/terminal/terminalPaste.test.ts +++ b/apps/mobile/src/features/terminal/terminalPaste.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "vite-plus/test"; -import { TERMINAL_WRITE_MAX_LENGTH } from "@t3tools/contracts"; +import { TERMINAL_WRITE_MAX_LENGTH, type TerminalWriteInput } from "@t3tools/contracts"; import { createTerminalPasteSession } from "./terminalPaste"; function deferred() { @@ -50,9 +50,11 @@ describe("terminal paste session", () => { const firstWrite = deferred(); const firstWriteStarted = deferred(); const writes: string[] = []; + const phases: Array = []; let activeWrites = 0; let maximumActiveWrites = 0; - const write = async (data: string) => { + const write = async (data: string, phase?: TerminalWriteInput["plainWrite"]) => { + phases.push(phase); writes.push(data); activeWrites += 1; maximumActiveWrites = Math.max(maximumActiveWrites, activeWrites); @@ -84,8 +86,45 @@ describe("terminal paste session", () => { firstWrite.resolve(true); await Promise.all([olderPaste, newerPaste]); - expect(writes.map((chunk) => chunk.length)).toEqual([TERMINAL_WRITE_MAX_LENGTH, 5]); - expect(writes[1]).toBe("newer"); + expect(writes.map((chunk) => chunk.length)).toEqual([TERMINAL_WRITE_MAX_LENGTH, 0, 5]); + expect(writes[2]).toBe("newer"); + expect(phases).toEqual(["start", "abort", undefined]); expect(maximumActiveWrites).toBe(1); }); + it("keeps a keystroke behind a queued split write", async () => { + const session = createTerminalPasteSession(); + session.reset(true); + const firstChunk = deferred(); + const started = deferred(); + const writes: string[] = []; + const send = async (data: string) => { + writes.push(data); + if (writes.length === 1) { + started.resolve(); + return firstChunk.promise; + } + return true; + }; + const a = "a".repeat(TERMINAL_WRITE_MAX_LENGTH); + const b = "b".repeat(TERMINAL_WRITE_MAX_LENGTH); + const first = session.write(a + "1", send); + await started.promise; + const second = session.write(b + "2", send); + const key = session.write("k", send); + expect(writes).toEqual([a]); + + firstChunk.resolve(true); + await Promise.all([first, second, key]); + expect(writes).toEqual([a, "1", b, "2", "k"]); + }); + + it("sends a keystroke typed before the first attach snapshot", async () => { + const session = createTerminalPasteSession(); + const writes: string[] = []; + await session.write("k", async (data) => { + writes.push(data); + return true; + }); + expect(writes).toEqual(["k"]); + }); }); diff --git a/apps/mobile/src/features/terminal/terminalPaste.ts b/apps/mobile/src/features/terminal/terminalPaste.ts index b09e365587d57..28c176f65cf20 100644 --- a/apps/mobile/src/features/terminal/terminalPaste.ts +++ b/apps/mobile/src/features/terminal/terminalPaste.ts @@ -1,10 +1,16 @@ -import { chunkTerminalWrite } from "@t3tools/contracts"; +import { + chunkTerminalWrite, + terminalWritePhase, + type TerminalWriteInput, +} from "@t3tools/contracts"; import { encodeTerminalPaste } from "./terminalInput"; +type WriteChunk = (data: string, phase?: TerminalWriteInput["plainWrite"]) => Promise; + interface TerminalPasteInput { readonly readText: () => Promise; - readonly write: (data: string) => Promise; + readonly write: WriteChunk; readonly onReadError: (cause: unknown) => void; } @@ -12,13 +18,45 @@ export interface TerminalPasteSession { readonly reset: (active: boolean) => void; /** True until the terminal's liveness changes (stop, start or restart) after this call. */ readonly liveness: () => () => boolean; + readonly write: (data: string, send: WriteChunk) => Promise; readonly paste: (input: TerminalPasteInput) => Promise; } export function createTerminalPasteSession(): TerminalPasteSession { let liveTarget: object | null = null; let latestRequest = 0; - let writeTail: Promise = Promise.resolve(); + let writeTail: Promise | null = null; + + const writeChunks = ( + data: string, + send: WriteChunk, + isCurrent: () => boolean, + queueSingle: boolean, + ) => { + const chunks = chunkTerminalWrite(data); + const run = async () => { + let started = false; + try { + for (const [index, chunk] of chunks.entries()) { + if (!isCurrent()) return; + const phase = terminalWritePhase(index, chunks.length); + started ||= phase === "start"; + if (!(await send(chunk, phase))) return; + } + started = false; + } finally { + if (started) await send("", "abort"); + } + }; + if (writeTail === null && !queueSingle && chunks.length <= 1) return run(); + const pending = (writeTail ?? Promise.resolve()).then(run, run); + writeTail = pending; + const clear = () => { + if (writeTail === pending) writeTail = null; + }; + void pending.then(clear, clear); + return pending; + }; return { reset(active) { @@ -30,6 +68,12 @@ export function createTerminalPasteSession(): TerminalPasteSession { return () => liveTarget === target; }, + async write(data, send) { + // Input can arrive before the first attach snapshot sets liveness; the caller gates on running. + const target = liveTarget; + await writeChunks(data, send, () => liveTarget === target, false); + }, + async paste({ readText, write, onReadError }) { const target = liveTarget; if (target === null) { @@ -50,19 +94,7 @@ export function createTerminalPasteSession(): TerminalPasteSession { return; } - const writePaste = async () => { - for (const chunk of chunkTerminalWrite(encodeTerminalPaste(text))) { - if (!isCurrent() || !(await write(chunk))) { - return; - } - } - }; - const queuedWrite = writeTail.then(writePaste, writePaste); - writeTail = queuedWrite.then( - () => undefined, - () => undefined, - ); - await queuedWrite; + await writeChunks(encodeTerminalPaste(text), write, isCurrent, true); }, }; } diff --git a/apps/server/src/terminal/Manager.test.ts b/apps/server/src/terminal/Manager.test.ts index 9773e2dd19350..649eb097a654f 100644 --- a/apps/server/src/terminal/Manager.test.ts +++ b/apps/server/src/terminal/Manager.test.ts @@ -5,6 +5,9 @@ import { assert, it } from "@effect/vitest"; import { DEFAULT_MAX_TERMINAL_BUFFER_BYTES, DEFAULT_TERMINAL_ID, + TERMINAL_BRACKETED_PASTE_START, + TERMINAL_BRACKETED_PASTE_END, + type TerminalWriteInput, ProjectId, ThreadId, TerminalCwdNotFoundError, @@ -877,6 +880,124 @@ it.layer( }), ); + it.effect.each(["complete", "abort", "timeout", "close"] as const)( + "releases pending terminal input after paste %s", + (interruption) => + Effect.gen(function* () { + const { manager, ptyAdapter } = yield* createManager(); + yield* manager.open(openInput()); + const target = { threadId: "thread-1", terminalId: DEFAULT_TERMINAL_ID }; + const process = ptyAdapter.processes[0]!; + process.onKill = () => process.emitExit({ exitCode: 0, signal: 0 }); + const endPrefix = TERMINAL_BRACKETED_PASTE_END.slice(0, -1); + const endSuffix = TERMINAL_BRACKETED_PASTE_END.slice(-1); + const begin = TERMINAL_BRACKETED_PASTE_START + "partial"; + const writePaste = (data: string, bracketedPaste: TerminalWriteInput["bracketedPaste"]) => + manager.write({ ...target, data, ...(bracketedPaste && { bracketedPaste }) }, "paste"); + yield* writePaste(begin, "start"); + const pending = yield* manager + .write({ ...target, data: "next" }, "typing") + .pipe(Effect.forkScoped({ startImmediately: true })); + expect(process.writes).toEqual([begin]); + + if (interruption === "complete") { + const badEnd = yield* writePaste("incomplete end", "end").pipe(Effect.flip); + expect(badEnd._tag).toBe("TerminalWriteError"); + expect(process.writes).toEqual([begin]); + yield* writePaste(endPrefix, "continue"); + yield* writePaste(endSuffix, "end"); + } else if (interruption === "abort") { + yield* writePaste(TERMINAL_BRACKETED_PASTE_END, "abort"); + } else if (interruption === "timeout") { + yield* TestClock.adjust("15 seconds"); + } else { + yield* manager.close(target); + yield* manager.open(openInput()); + const reopened = ptyAdapter.processes[1]!; + reopened.onKill = () => reopened.emitExit({ exitCode: 0, signal: 0 }); + expect(reopened.writes).toEqual([]); + } + if (interruption === "close") { + const error = yield* Fiber.join(pending).pipe(Effect.flip); + expect(error._tag).toBe("TerminalNotRunningError"); + expect(process.writes).toEqual([begin]); + expect(ptyAdapter.processes[1]!.writes).toEqual([]); + } else { + yield* Fiber.join(pending); + expect(process.writes).toEqual( + interruption === "complete" + ? [begin, endPrefix, endSuffix, "next"] + : [begin, TERMINAL_BRACKETED_PASTE_END, "next"], + ); + } + const lateEnd = yield* writePaste(TERMINAL_BRACKETED_PASTE_END, "end").pipe(Effect.exit); + expect(Exit.isFailure(lateEnd)).toBe(true); + }).pipe(Effect.provide(TestClock.layer())), + ); + + it.effect.each(["end", "abort", "timeout"] as const)( + "releases input after a plain split write ends by %s without adding a bracket", + (finish) => + Effect.gen(function* () { + const { manager, ptyAdapter } = yield* createManager(); + yield* manager.open(openInput()); + const target = { threadId: "thread-1", terminalId: DEFAULT_TERMINAL_ID }; + const process = ptyAdapter.processes[0]!; + process.onKill = () => process.emitExit({ exitCode: 0, signal: 0 }); + yield* manager.write({ ...target, data: "first", plainWrite: "start" }, "paste"); + const pending = yield* manager + .write({ ...target, data: "typing" }, "other") + .pipe(Effect.forkScoped({ startImmediately: true })); + expect(process.writes).toEqual(["first"]); + if (finish === "timeout") { + yield* TestClock.adjust("15 seconds"); + } else { + yield* manager.write( + { ...target, data: finish === "end" ? "last" : "", plainWrite: finish }, + "paste", + ); + } + yield* Fiber.join(pending); + expect(process.writes).toEqual( + finish === "end" ? ["first", "last", "typing"] : ["first", "typing"], + ); + }).pipe(Effect.provide(TestClock.layer())), + ); + + it.effect("does not reserve the terminal when writing a paste start fails", () => + Effect.gen(function* () { + const { manager, ptyAdapter } = yield* createManager(); + yield* manager.open(openInput()); + const target = { threadId: "thread-1", terminalId: DEFAULT_TERMINAL_ID }; + const process = ptyAdapter.processes[0]!; + process.onKill = () => process.emitExit({ exitCode: 0, signal: 0 }); + process.writeFailure = new Error("write failed"); + const error = yield* manager + .write( + { + ...target, + data: TERMINAL_BRACKETED_PASTE_START + "paste", + bracketedPaste: "start", + }, + "paste", + ) + .pipe(Effect.flip); + expect(error._tag).toBe("TerminalWriteError"); + + process.writeFailure = undefined; + yield* manager.write( + { + ...target, + data: TERMINAL_BRACKETED_PASTE_END, + bracketedPaste: "abort", + }, + "paste", + ); + yield* manager.write({ ...target, data: "next" }, "typing"); + expect(process.writes).toEqual(["next"]); + }), + ); + it.effect("resumed attaches after close never respawn until the terminal is reopened", () => Effect.gen(function* () { const { manager, ptyAdapter } = yield* createManager(); diff --git a/apps/server/src/terminal/Manager.ts b/apps/server/src/terminal/Manager.ts index d71f4e2266c9a..76b39f86372b8 100644 --- a/apps/server/src/terminal/Manager.ts +++ b/apps/server/src/terminal/Manager.ts @@ -7,6 +7,8 @@ import { DEFAULT_MAX_TERMINAL_BUFFER_BYTES, retainTerminalSnapshotHistory, TERMINAL_SEQUENCE_GROUND, + TERMINAL_BRACKETED_PASTE_END, + TERMINAL_BRACKETED_PASTE_START, terminalSequenceEnd, terminalSequenceStateAfter, TerminalCwdError, @@ -49,6 +51,7 @@ import { SpawnExecutableResolution, mergePathEntries } from "@t3tools/shared/she import { acpRegistryManagedBinaryDirectories } from "@t3tools/provider-acp-registry/server"; import { getTerminalLabel } from "@t3tools/shared/terminalLabels"; +import * as Clock from "effect/Clock"; import * as DateTime from "effect/DateTime"; import * as Deferred from "effect/Deferred"; import * as Context from "effect/Context"; @@ -2030,6 +2033,28 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func const workerScope = yield* Scope.make("sequential"); yield* Effect.addFinalizer(() => Scope.close(workerScope, Exit.void)); + const clock = yield* Clock.Clock; + const pasteIdleMillis = 15_000; + const pasteEndOverlap = TERMINAL_BRACKETED_PASTE_END.length - 1; + const activePastes = new WeakMap< + PtyAdapter.PtyProcess, + { + readonly owner: string; + readonly finished: Deferred.Deferred; + lastWrite: number; + readonly bracketed: boolean; + trailingData: string; + } + >(); + + const releasePaste = (process: PtyAdapter.PtyProcess | null) => { + if (process === null) return; + const paste = activePastes.get(process); + if (!paste) return; + activePastes.delete(process); + Deferred.doneUnsafe(paste.finished, Effect.void); + }; + const publishEvent = /* Provider events include streaming deltas; avoid a span for each update. */ Effect.fnUntraced(function* (event: TerminalEvent) { @@ -2716,6 +2741,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func const process = session.process; cleanupProcessHandles(session); session.process = null; + releasePaste(process); session.pid = null; session.hasRunningSubprocess = false; session.childCommandLabel = null; @@ -2788,6 +2814,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func yield* modifyManagerState((state) => { cleanupProcessHandles(session); session.process = null; + releasePaste(process); session.pid = null; session.hasRunningSubprocess = false; session.childCommandLabel = null; @@ -3880,6 +3907,8 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func const write: TerminalManager["Service"]["write"] = Effect.fn("terminal.write")( function* (input, viewerId) { const terminalId = input.terminalId; + const phase = input.bracketedPaste ?? input.plainWrite; + const bracketed = input.bracketedPaste !== undefined; const found = yield* getSession(input.threadId, terminalId); if (Option.isNone(found)) { if (input.expectedPid !== undefined) return yield* new TerminalProcessChangedError(); @@ -3903,17 +3932,104 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func if (input.reply && !acceptsQueryReply(toSessionKey(input.threadId, terminalId), viewerId)) { return; } - session.inputCount += 1; - yield* Effect.try({ - try: () => process.write(PtyAdapter.ptyInput(input.data, input.binary)), - catch: (cause) => - new TerminalWriteError({ - threadId: input.threadId, - terminalId, - terminalPid: process.pid, - cause, - }), - }); + const writeError = (cause: unknown) => + new TerminalWriteError({ + threadId: input.threadId, + terminalId, + terminalPid: process.pid, + cause, + }); + const writeData = (data: string, binary?: boolean) => + Effect.try({ + try: () => { + session.inputCount += 1; + process.write(PtyAdapter.ptyInput(data, binary)); + }, + catch: writeError, + }); + if ( + phase && + (viewerId === undefined || input.binary || input.reply || (bracketed && input.plainWrite)) + ) { + return yield* writeError("Invalid split terminal write"); + } + if (phase === "continue" || phase === "end" || phase === "abort") { + const paste = activePastes.get(process); + if (!paste || paste.owner !== viewerId || paste.bracketed !== bracketed) { + if (phase === "abort") return; + return yield* writeError("Split terminal write is no longer active"); + } + if ( + bracketed && + phase === "end" && + !(paste.trailingData + input.data).endsWith(TERMINAL_BRACKETED_PASTE_END) + ) { + return yield* writeError("Missing end of bracketed paste"); + } + paste.lastWrite = clock.currentTimeMillisUnsafe(); + if (phase === "continue") { + yield* writeData(input.data); + paste.trailingData = (paste.trailingData + input.data).slice(-pasteEndOverlap); + return; + } + if (phase !== "abort" || bracketed) { + yield* writeData(phase === "abort" ? TERMINAL_BRACKETED_PASTE_END : input.data); + } + return releasePaste(process); + } + + // A write that waits for a paste belongs to the same PTY even if its session restarts. + let active = activePastes.get(process); + while (active) { + if (phase === "start" && active.owner === viewerId) { + return yield* writeError("Split terminal write already active"); + } + yield* Deferred.await(active.finished); + if (session.process !== process || session.status !== "running") { + return yield* new TerminalNotRunningError({ threadId: input.threadId, terminalId }); + } + active = activePastes.get(process); + } + if (phase !== "start" || viewerId === undefined) { + return yield* writeData(input.data, input.binary); + } + if (bracketed && !input.data.startsWith(TERMINAL_BRACKETED_PASTE_START)) { + return yield* writeError("Missing start of bracketed paste"); + } + + const paste = { + owner: viewerId, + bracketed, + finished: Deferred.makeUnsafe(), + lastWrite: clock.currentTimeMillisUnsafe(), + trailingData: input.data.slice(-pasteEndOverlap), + }; + // A disconnected sender cannot close its bracket. Close it on the original PTY + // before releasing queued input, even when the rest of the paste never arrives. + yield* Effect.uninterruptible( + Effect.gen(function* () { + yield* writeData(input.data); + activePastes.set(process, paste); + yield* Effect.gen(function* () { + while (activePastes.get(process) === paste && session.process === process) { + const remaining = paste.lastWrite + pasteIdleMillis - clock.currentTimeMillisUnsafe(); + if (remaining <= 0) { + if (bracketed) { + yield* writeData(TERMINAL_BRACKETED_PASTE_END).pipe( + Effect.ignoreCause({ log: true }), + ); + } + break; + } + const finished = yield* Deferred.await(paste.finished).pipe( + Effect.timeoutOption(Duration.millis(remaining)), + ); + if (Option.isSome(finished)) return; + } + if (activePastes.get(process) === paste) releasePaste(process); + }).pipe(Effect.interruptible, Effect.forkIn(workerScope)); + }), + ); }, ); diff --git a/apps/web/src/components/ThreadTerminalDrawer.tsx b/apps/web/src/components/ThreadTerminalDrawer.tsx index 9bc43233585d7..94b8c160788d2 100644 --- a/apps/web/src/components/ThreadTerminalDrawer.tsx +++ b/apps/web/src/components/ThreadTerminalDrawer.tsx @@ -30,6 +30,7 @@ import { AuthOrchestrationOperateScope, AuthTerminalOperateScope, TerminalProcessChangedError, + type TerminalWriteInput, type ContextMenuItem, type ProviderInstanceId, type ResolvedKeybindingsConfig, @@ -966,7 +967,11 @@ function TerminalSessionViewport({ }; const canWriteInput = () => readEnvironmentScope(environmentId, AuthTerminalOperateScope); - const writeInputChunk = (data: string, kind?: "binary" | "reply", expectedPid?: number) => + const writeInputChunk = ( + data: string, + kind?: "binary" | "reply", + options?: Pick, + ) => retainedTerminalWrite.current({ environmentId, input: { @@ -974,7 +979,7 @@ function TerminalSessionViewport({ terminalId, data, ...(kind === undefined ? {} : { [kind]: true }), - ...(expectedPid === undefined ? {} : { expectedPid }), + ...options, }, }); const sendTerminalInput = ( @@ -999,7 +1004,7 @@ function TerminalSessionViewport({ }; return writeInput( data, - async (chunk, split) => { + async (chunk, framing) => { if (terminalRef.current !== terminal) return "not-dispatched"; const currentSession = appAtomRegistry.get(terminalSessionAtom); if ( @@ -1009,9 +1014,12 @@ function TerminalSessionViewport({ return "not-dispatched"; } const expectedPid = - split && session.supportsConditionalWrites ? session.pid : undefined; + framing && session.supportsConditionalWrites ? session.pid : undefined; if (expectedPid === null) return "not-dispatched"; - const result = await writeInputChunk(chunk, kind, expectedPid); + const result = await writeInputChunk(chunk, kind, { + ...(kind ? {} : framing), + ...(expectedPid === undefined ? {} : { expectedPid }), + }); if (result._tag === "Success") return true; const error = squashAtomCommandFailure(result); if (isTerminalProcessChanged(error)) return "not-dispatched"; @@ -1021,8 +1029,17 @@ function TerminalSessionViewport({ return false; }, // The attachment's PID stays with the paste even after the viewport detaches. - async () => { - if (session.pid === null) return true; + async (bracketed) => { + if (kind || session.pid === null) return true; + const expectedPid = session.supportsConditionalWrites ? session.pid : undefined; + const pidGuard = expectedPid === undefined ? {} : { expectedPid }; + if (!bracketed) { + // Only releases the server's hold, which also ends when that process exits. + const current = appAtomRegistry.get(terminalSessionAtom); + if (current.lifecycleVersion !== lifecycleVersion) return true; + await writeInputChunk("", undefined, { plainWrite: "abort", ...pidGuard }); + return true; + } if (!canWriteInput()) return false; if (!session.supportsConditionalWrites) { const attached = @@ -1047,11 +1064,10 @@ function TerminalSessionViewport({ } if (current.status !== "running" || current.pid !== session.pid) return false; } - const result = await writeInputChunk( - "\x1b[201~", - undefined, - session.supportsConditionalWrites ? session.pid : undefined, - ); + const result = await writeInputChunk("\x1b[201~", undefined, { + bracketedPaste: "abort", + ...pidGuard, + }); if (result._tag === "Success") return true; const error = squashAtomCommandFailure(result); if (isTerminalProcessChanged(error)) return true; diff --git a/apps/web/src/components/terminal/terminalInputWriter.test.ts b/apps/web/src/components/terminal/terminalInputWriter.test.ts index 2670add86a2f3..9d79de03e57b5 100644 --- a/apps/web/src/components/terminal/terminalInputWriter.test.ts +++ b/apps/web/src/components/terminal/terminalInputWriter.test.ts @@ -9,7 +9,12 @@ const fitsWrite = (data: string) => isWriteInput({ threadId: "t", terminalId: "d /** A `send` whose calls stay pending until the test settles them. */ function heldSend() { - const sent: Array<{ readonly chunk: string; readonly settle: (ok: boolean) => void }> = []; + type Framing = Pick; + const sent: Array<{ + readonly chunk: string; + readonly framing: Framing | undefined; + readonly settle: (ok: boolean) => void; + }> = []; const waiters: Array<{ readonly count: number; readonly resolve: () => void }> = []; return { sent, @@ -20,9 +25,9 @@ function heldSend() { if (sent.length >= count) resolve(); else waiters.push({ count, resolve }); }), - send: (chunk: string) => + send: (chunk: string, framing?: Framing) => new Promise((settle) => { - sent.push({ chunk, settle }); + sent.push({ chunk, framing, settle }); for (const waiter of waiters) if (sent.length >= waiter.count) waiter.resolve(); }), }; @@ -162,9 +167,16 @@ describe("createTerminalInputWriter", () => { const pasted = write("q".repeat(140_000), send); void write("next", send); sent[0]!.settle(false); - await pasted; await sends(2); + sent[1]!.settle(true); + await pasted; + await sends(3); - expect(chunks()).toEqual(["q".repeat(65_536), "next"]); + expect(chunks()).toEqual(["q".repeat(65_536), "", "next"]); + expect(sent.map(({ framing }) => framing)).toEqual([ + { plainWrite: "start" }, + { plainWrite: "abort" }, + undefined, + ]); }); }); diff --git a/apps/web/src/components/terminal/terminalInputWriter.ts b/apps/web/src/components/terminal/terminalInputWriter.ts index ab7e7033ee7e2..c44253da4aeaa 100644 --- a/apps/web/src/components/terminal/terminalInputWriter.ts +++ b/apps/web/src/components/terminal/terminalInputWriter.ts @@ -1,7 +1,14 @@ -import { chunkTerminalWrite } from "@t3tools/contracts"; +import { + chunkTerminalWrite, + terminalWritePhase, + type TerminalWriteInput, +} from "@t3tools/contracts"; /** Sends one chunk of terminal input; resolves false when it failed and the rest should drop. */ -type SendTerminalChunk = (chunk: string, split: boolean) => Promise; +type SendTerminalChunk = ( + chunk: string, + framing?: Pick, +) => Promise; /** * Orders one terminal's input into writes that fit `terminal.write`. A split write goes one chunk @@ -23,7 +30,7 @@ export function createTerminalInputWriter(onIdle = () => {}) { data: string, chunks: ReadonlyArray, send: SendTerminalChunk, - recover: () => Promise, + recover: (bracketed: boolean) => Promise, interrupted: () => void, ) => { if (closeInterruptedPaste !== null && !(await closePaste())) { @@ -34,20 +41,28 @@ export function createTerminalInputWriter(onIdle = () => {}) { const bracketed = split && data.startsWith("\x1b[200~") && data.endsWith("\x1b[201~"); let opened = false; try { - for (const chunk of chunks) { - const result = await send(chunk, split); + for (const [index, chunk] of chunks.entries()) { + const phase = terminalWritePhase(index, chunks.length); + const result = await send( + chunk, + phase ? (bracketed ? { bracketedPaste: phase } : { plainWrite: phase }) : undefined, + ); if (result !== true) { - if (result !== "not-dispatched") opened = bracketed; + if (result !== "not-dispatched") opened = split; if (split) interrupted(); return; } - opened = bracketed; + opened = split; } opened = false; } finally { if (opened) { - closeInterruptedPaste = recover; - await closePaste(); + if (bracketed) { + closeInterruptedPaste = () => recover(true); + await closePaste(); + } else { + await recover(false); + } } } }; @@ -55,7 +70,10 @@ export function createTerminalInputWriter(onIdle = () => {}) { return ( data: string, send: SendTerminalChunk, - recover: () => Promise = async () => (await send("\x1b[201~", true)) === true, + recover: (bracketed: boolean) => Promise = async (bracketed) => + (await (bracketed + ? send("\x1b[201~", { bracketedPaste: "abort" }) + : send("", { plainWrite: "abort" }))) === true, interrupted = () => {}, ): Promise => { const idle = () => { diff --git a/packages/contracts/src/terminal.ts b/packages/contracts/src/terminal.ts index 93d5164e9b98b..fb2f9a6a8fe93 100644 --- a/packages/contracts/src/terminal.ts +++ b/packages/contracts/src/terminal.ts @@ -273,11 +273,15 @@ export type TerminalAttachInput = typeof TerminalAttachInput.Type; /** Longest `data` one `terminal.write` carries, in UTF-16 code units. */ export const TERMINAL_WRITE_MAX_LENGTH = 65_536; +export const TERMINAL_BRACKETED_PASTE_START = "\x1b[200~"; +export const TERMINAL_BRACKETED_PASTE_END = "\x1b[201~"; + export const TerminalWriteInput = Schema.Struct({ ...TerminalSessionInput.fields, - data: Schema.String.check(Schema.isNonEmpty()).check( - Schema.isMaxLength(TERMINAL_WRITE_MAX_LENGTH), - ), + data: Schema.String.check(Schema.isMaxLength(TERMINAL_WRITE_MAX_LENGTH)), + // Older servers ignore the phase and still receive the bracket markers in data. + bracketedPaste: Schema.optionalKey(Schema.Literals(["start", "continue", "end", "abort"])), + plainWrite: Schema.optionalKey(Schema.Literals(["start", "continue", "end", "abort"])), // `data` holds one byte per UTF-16 code unit; older servers write it as UTF-8 text. binary: Schema.optionalKey(Schema.Boolean), // A renderer's answer to a terminal query (DA, DSR, DECRQM). Every attached renderer @@ -285,7 +289,9 @@ export const TerminalWriteInput = Schema.Struct({ reply: Schema.optionalKey(Schema.Boolean), // Reject the write if the process that owns the paste has gone. expectedPid: Schema.optionalKey(Schema.Int.check(Schema.isGreaterThan(0))), -}); +}).check( + Schema.makeFilter(({ data, plainWrite }) => (plainWrite === "abort") === (data.length === 0)), +); export type TerminalWriteInput = Schema.Codec.Encoded; /** Splits input into writes that fit `TerminalWriteInput`, never between a surrogate pair. */ @@ -304,6 +310,11 @@ export function chunkTerminalWrite(data: string): ReadonlyArray { return chunks; } +export function terminalWritePhase(index: number, count: number) { + if (count <= 1) return undefined; + return index === 0 ? "start" : index === count - 1 ? "end" : "continue"; +} + export const TerminalResizeInput = Schema.Struct({ ...TerminalSessionInput.fields, cols: TerminalColsSchema, diff --git a/scripts/scenarios/terminal-paste-keeps-input-from-other-client-out.e2e.ts b/scripts/scenarios/terminal-paste-keeps-input-from-other-client-out.e2e.ts new file mode 100644 index 0000000000000..8a3e26008fe7f --- /dev/null +++ b/scripts/scenarios/terminal-paste-keeps-input-from-other-client-out.e2e.ts @@ -0,0 +1,153 @@ +/// +import { DEFAULT_TERMINAL_ID, ThreadId } from "@t3tools/contracts"; +import { expect } from "e2e"; +import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; +import * as FileSystem from "effect/FileSystem"; + +import { T3_HOME } from "../e2e.config.ts"; +import { rpcClient, runPromise, test, WEB } from "./t3.ts"; + +const TAIL = "end-of-first-paste"; +const OTHER_INPUT = "second-client-input"; +const PASTE = "p".repeat(65_536 - 6) + TAIL; + +const PROBE = String.raw`import { writeFileSync } from "node:fs"; +const file = (name) => new URL(name, import.meta.url); +let received = ""; +process.stdin.setRawMode(true); +process.stdin.on("data", (chunk) => { + received += chunk.toString(); + if (!received.includes("\x1b[201~")) return; + const expected = "\x1b[200~" + "p".repeat(65530) + "${TAIL}\x1b[201~"; + const interleaved = "\x1b[200~" + "p".repeat(65530) + "${OTHER_INPUT}${TAIL}\x1b[201~"; + const result = received.startsWith(expected) + ? "Paste arrived intact" + : received.startsWith(interleaved) + ? "Other input landed inside the paste" + : "Paste arrived with unexpected bytes"; + writeFileSync(file("result"), result); + process.stdout.write("\x1b[?2004l\r\n" + result + "\r\n"); + process.exit(0); +}); +process.stdout.write("\x1b[?2004h"); +writeFileSync(file("ready"), "ready"); +`; + +interface PasteGate { + readonly waiting: () => boolean; + readonly release: () => void; +} + +test( + "A second connection cannot insert input inside a web terminal paste", + WEB, + async ({ t3, app, browser, screen }) => { + const cwd = await t3.project("demo", { "paste-probe.mjs": PROBE }); + const thread = await t3.thread({ + project: cwd, + title: "Shared terminal paste", + messages: ["hello"], + }); + const threadId = ThreadId.make(thread.threadId); + const terminalId = DEFAULT_TERMINAL_ID; + const origin = app.baseUrl ?? ""; + const read = (name: string) => + runPromise( + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + return yield* fs.readFileString(`${cwd}/${name}`); + }).pipe(Effect.orElseSucceed(() => "")), + ); + await runPromise( + Effect.gen(function* () { + const client = yield* rpcClient(T3_HOME, origin); + yield* client["terminal.open"]({ threadId, terminalId, cwd }); + }).pipe(Effect.scoped), + ); + + // Hold the next outgoing chunk to reproduce a slow connection after the first was acknowledged. + await browser.addInitScript((tail) => { + let release: (() => void) | undefined; + const nativeSend = WebSocket.prototype.send; + WebSocket.prototype.send = function (data: Parameters[0]) { + if (typeof data === "string" && data.includes('"tag":"terminal.write"')) { + const request = JSON.parse(data) as { payload?: { data?: string } }; + if (request.payload?.data?.endsWith(tail + "\x1b[201~")) { + release = () => nativeSend.call(this, data); + return; + } + } + nativeSend.call(this, data); + }; + (window as unknown as { pasteGate: PasteGate }).pasteGate = { + waiting: () => release !== undefined, + release: () => release?.(), + }; + }, TAIL); + await browser.emulateMedia({ colorScheme: "dark", reducedMotion: "reduce" }); + await t3.open(thread); + await screen.getByRole("button", "Toggle terminal drawer").tap(); + const terminal = screen.getByLabel("Terminal input"); + // The terminal surface can appear before its session can accept keystrokes. + await expect + .poll( + async () => { + await terminal.focus(); + await browser.keyboard.type(`echo ready > '${cwd}/shell-ready'`); + await browser.keyboard.press("Enter"); + return read("shell-ready"); + }, + { timeout: 30_000 }, + ) + .toBe("ready\n"); + + await terminal.focus(); + await browser.keyboard.type(`'${process.execPath}' '${cwd}/paste-probe.mjs'`); + await browser.keyboard.press("Enter"); + await expect.poll(() => read("ready"), { timeout: 15_000 }).toBe("ready"); + + await browser.evaluate((text) => { + const input = document.querySelector('[aria-label="Terminal input"]'); + if (!input) throw new Error("no terminal input"); + const clipboardData = new DataTransfer(); + clipboardData.setData("text/plain", text); + input.dispatchEvent( + new ClipboardEvent("paste", { clipboardData, bubbles: true, cancelable: true }), + ); + return null; + }, PASTE); + await expect + .poll(async () => { + if (await read("result")) return true; + return browser.evaluate(() => + (window as unknown as { pasteGate: PasteGate }).pasteGate.waiting(), + ); + }) + .toBe(true); + + await runPromise( + Effect.gen(function* () { + const client = yield* rpcClient(T3_HOME, origin); + const write = yield* client["terminal.write"]({ + threadId, + terminalId, + data: OTHER_INPUT, + }).pipe(Effect.forkScoped); + // A server that defers the second client's write may acknowledge it after the paste. + yield* Fiber.join(write).pipe(Effect.timeoutOption("3 seconds")); + yield* Effect.promise(() => + browser.evaluate(() => { + (window as unknown as { pasteGate: PasteGate }).pasteGate.release(); + return null; + }), + ); + yield* Fiber.join(write); + }).pipe(Effect.scoped), + ); + + await expect.poll(async () => Boolean(await read("result"))).toBe(true); + await app.screenshot("paste-after-input-from-second-connection"); + expect(await read("result")).toBe("Paste arrived intact"); + }, +); From 2313dfadad3398fd2a3ec9e267518af762ce0374 Mon Sep 17 00:00:00 2001 From: Thanh Hoai Anh Nguyen Date: Wed, 25 Nov 2026 19:46:02 +0200 Subject: [PATCH 071/238] fix(server): resend a Cursor request a restart cut off before its first checkpoint (#42938) Co-authored-by: Julius Marminge --- .../ProviderTurnStartService.ts | 121 ++++++++++++++- .../ProviderSwitch.integration.test.ts | 140 +++++++++++++++++- .../src/server/ProviderAdapter.ts | 8 + .../src/server/adapter.test.ts | 6 + .../provider-cursor/src/server/adapter.ts | 28 ++++ 5 files changed, 294 insertions(+), 9 deletions(-) diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts index 8051a4129095a..33d549f548938 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts @@ -151,6 +151,46 @@ export function abandonedProviderTurns( }); } +const CUT_TURN_SETTLED = "cut-turn-settled"; + +/** + * The previous run's cancelled turn when no adapter said whether it kept the request. A Stop + * settles that as the turn ends; a restart cancels the turn with no adapter left to tell. + */ +function unsettledCancelledProviderTurn( + projection: Pick, + run: Pick, + providerThread: Pick, +) { + const previous = projection.runs.reduce( + (latest, candidate) => + candidate.ordinal < run.ordinal && + candidate.providerThreadId === providerThread.id && + candidate.startedAt !== null && + (latest === undefined || candidate.ordinal > latest.ordinal) + ? candidate + : latest, + undefined, + ); + if (previous?.status !== "cancelled" || previous.activeAttemptId === null) return undefined; + const turn = projection.providerTurns.findLast( + (candidate) => + candidate.runAttemptId === previous.activeAttemptId && + candidate.providerThreadId === providerThread.id, + ); + const nativeTurnId = turn?.nativeTurnRef?.nativeId; + if ( + turn === undefined || + nativeTurnId == null || + turn.status !== "cancelled" || + turn.promptDropped === true || + (turn.nativeThreadRef !== undefined && + turn.nativeThreadRef.nativeId !== providerThread.nativeThreadRef?.nativeId) + ) + return undefined; + return { run: previous, turn, nativeTurnId }; +} + export const isProviderTurnStartError = Schema.is(ProviderTurnStartError); const isProviderAdapterProtocolError = Schema.is(ProviderAdapter.ProviderAdapterProtocolError); const isProviderAdapterTurnStartError = Schema.is(ProviderAdapter.ProviderAdapterTurnStartError); @@ -1063,6 +1103,70 @@ export const layer: Layer.Layer< } const session = sessionResult.success; if (!(yield* isCurrentAttemptInStatus("starting"))) return; + const cutTurn = unsettledCancelledProviderTurn(projection, run, providerThread); + if ( + cutTurn !== undefined && + session.nativeTurnKept !== undefined && + !(yield* ( + session + .nativeTurnKept({ providerThread, nativeTurnId: cutTurn.nativeTurnId }) + // As when the turn ends: an unknown answer resends the request rather than losing it. + .pipe(Effect.orElseSucceed(() => false)) + )) + ) { + // Settle it as a Stop would: mark the request dropped and take back its inline context, so + // this turn resends both. Starting again reads the settled state. + const occurredAt = yield* DateTime.now; + const allocateEventId = () => + idAllocator.allocate.event({ threadId: projection.thread.id }); + // Its attempt starts before it delivers anything, so later inline deliveries are its own, + // including handoffs carried from an earlier run that they still target. + const cutStartedAt = + projection.attempts.find((candidate) => candidate.id === cutTurn.run.activeAttemptId) + ?.startedAt ?? cutTurn.run.startedAt; + const settled = yield* eventSink.writeIfRunCurrent({ + threadId: projection.thread.id, + runId: run.id, + activeAttemptId: attempt.id, + expectedStatus: "starting", + events: [ + { + id: yield* allocateEventId(), + type: "provider-turn.updated" as const, + threadId: projection.thread.id, + runId: cutTurn.run.id, + nodeId: cutTurn.turn.nodeId, + providerInstanceId: cutTurn.run.providerInstanceId, + occurredAt, + payload: { ...cutTurn.turn, promptDropped: true as const }, + }, + ...(yield* Effect.forEach( + projection.contextHandoffs.filter( + (handoff) => + handoff.delivery?.status === "inline" && + handoff.delivery.nativeThreadId === providerThread.nativeThreadRef?.nativeId && + (handoff.targetRunId === cutTurn.run.id || + (cutStartedAt !== null && + DateTime.isGreaterThanOrEqualTo(handoff.updatedAt, cutStartedAt))), + ), + ({ delivery: _delivery, ...handoff }) => + Effect.map(allocateEventId(), (id) => ({ + id, + type: "context-handoff.updated" as const, + threadId: projection.thread.id, + runId: cutTurn.run.id, + providerInstanceId: cutTurn.run.providerInstanceId, + occurredAt, + payload: { ...handoff, updatedAt: occurredAt }, + })), + )), + ], + }); + if (!settled.committed) return; + // The restarted start captures the same baseline; never let the two write at once. + yield* baseline; + return CUT_TURN_SETTLED; + } const loadFromProvider = Effect.fn("ProviderTurnStartService.loadFromProvider")(function* ( load: Effect.Effect, ) { @@ -2389,18 +2493,23 @@ export const layer: Layer.Layer< (yield* projects .getById(thread.projectId, { includeDeleted: true }) .pipe(Effect.map((project) => Option.getOrUndefined(project)?.workspaceRoot))); + // Settling a turn a restart cut off changes what a start reads, so it starts once more. + const startSettled = start(input, captureStartingRun).pipe( + Effect.filterOrElse( + (started) => started !== CUT_TURN_SETTLED, + () => start(input, captureStartingRun), + ), + Effect.map((started) => (started === CUT_TURN_SETTLED ? undefined : started)), + ); const providerTurn = yield* cwd === undefined - ? start(input, captureStartingRun) + ? startSettled : withTurnStartReservation( fileSystem, path, path.resolve(cwd), thread.worktreePath === null - ? start(input, captureStartingRun) - : withWorkspaceLease( - path.resolve(thread.worktreePath), - start(input, captureStartingRun), - ), + ? startSettled + : withWorkspaceLease(path.resolve(thread.worktreePath), startSettled), ); if (providerTurn !== undefined && "worktreeSetup" in providerTurn) { yield* providerTurn.worktreeSetup; diff --git a/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts b/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts index e9fc7b8d63ff6..8ee13bf8f9878 100644 --- a/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts +++ b/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts @@ -120,6 +120,7 @@ function makeTestAdapter(input: { readonly rejectedNativeThreads?: Ref.Ref>; readonly failedRunOrdinals?: ReadonlySet; readonly promptDroppedRunOrdinals?: ReadonlySet; + readonly nativeTurnKept?: (nativeTurnId: string) => boolean; readonly brokenRunOrdinals?: ReadonlySet; readonly interruptedRunOrdinals?: ReadonlySet; readonly cancelledRunOrdinals?: ReadonlySet; @@ -201,6 +202,12 @@ function makeTestAdapter(input: { ...(input.canReuseContextUsage === undefined ? {} : { canReuseContextUsage: input.canReuseContextUsage }), + ...(input.nativeTurnKept === undefined + ? {} + : { + nativeTurnKept: ({ nativeTurnId }) => + Effect.succeed(input.nativeTurnKept!(nativeTurnId)), + }), ...(input.backgroundWork === undefined ? {} : { @@ -6544,14 +6551,17 @@ describe("orchestration v2 provider switching", () => { it.effect.each([ "same-provider-retry", "cancelled-dropped", + "cancelled-by-restart", "switch-away-and-return", "persisted-failure", ] as const)("handles an inline context handoff after a failed returning turn (%s)", (variant) => Effect.gen(function* () { const cwd = yield* checkpointWorkspace(`dropped-handoff-${variant}`); const capturedTurns = yield* Ref.make>([]); - const dropped = variant !== "persisted-failure"; - const cancelled = variant === "cancelled-dropped"; + // A restart cancels the turn with no adapter left to report the drop. + const cutByRestart = variant === "cancelled-by-restart"; + const dropped = variant !== "persisted-failure" && !cutByRestart; + const cancelled = variant === "cancelled-dropped" || cutByRestart; const layerRegistry = ProviderAdapterRegistry.layerFromAdapters([ makeTestAdapter({ instanceId: CODEX_MODEL_SELECTION.instanceId, @@ -6569,6 +6579,9 @@ describe("orchestration v2 provider switching", () => { ? { cancelledRunOrdinals: new Set([3]) } : { failedRunOrdinals: new Set([3]) }), ...(dropped ? { promptDroppedRunOrdinals: new Set([3]) } : {}), + ...(cutByRestart + ? { nativeTurnKept: (nativeTurnId: string) => !nativeTurnId.endsWith(":3") } + : {}), }), makeTestAdapter({ instanceId: CLAUDE_MODEL_SELECTION.instanceId, @@ -6650,7 +6663,7 @@ describe("orchestration v2 provider switching", () => { assert.equal(run3Handoff?.delivery?.status, "inline"); } - if (variant === "same-provider-retry" || variant === "cancelled-dropped") { + if (variant === "same-provider-retry" || variant === "cancelled-dropped" || cutByRestart) { // Run 4: stay on Codex; must re-deliver run 2's handoff. const afterRun4 = yield* send("Resume", CODEX_MODEL_SELECTION); const turns = yield* Ref.get(capturedTurns); @@ -6662,6 +6675,10 @@ describe("orchestration v2 provider switching", () => { (handoff) => handoff.id === run3Handoff!.id, ); assert.equal(updatedHandoff?.delivery?.status, "inline"); + const run3Turn = afterRun4.providerTurns.find( + (turn) => turn.runAttemptId === run3.activeAttemptId, + ); + assert.equal(run3Turn?.promptDropped, true); } else if (variant === "switch-away-and-return") { // Run 4: bounce back to Claude, then Run 5: return to Codex. yield* send("Continue on Claude", CLAUDE_MODEL_SELECTION); @@ -6702,4 +6719,121 @@ describe("orchestration v2 provider switching", () => { ); }), ); + + it.effect("restores a handoff that a turn cut by a restart carried from an earlier run", () => + Effect.gen(function* () { + const cwd = yield* checkpointWorkspace("carried-handoff-cut-by-restart"); + const capturedTurns = yield* Ref.make>([]); + const refuseStarts = yield* Ref.make(0); + const layerRegistry = ProviderAdapterRegistry.layerFromAdapters([ + makeTestAdapter({ + instanceId: CODEX_MODEL_SELECTION.instanceId, + driver: CODEX_DRIVER, + capabilities: CodexProviderCapabilitiesV2, + modelSelection: CODEX_MODEL_SELECTION, + responseByRunOrdinal: { 1: "Morning Codex summary.", 4: "", 5: "Recovered." }, + capturedTurns, + refuseStarts, + // A restart cancels run 4 before the provider keeps its request. + cancelledRunOrdinals: new Set([4]), + nativeTurnKept: (nativeTurnId) => !nativeTurnId.endsWith(":4"), + }), + makeTestAdapter({ + instanceId: CLAUDE_MODEL_SELECTION.instanceId, + driver: CLAUDE_DRIVER, + capabilities: ClaudeProviderCapabilitiesV2, + modelSelection: CLAUDE_MODEL_SELECTION, + responseByRunOrdinal: { 2: "Afternoon Claude shipped b63 live draft." }, + capturedTurns, + }), + ]); + + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const testThreadId = ThreadId.make("thread:carried-handoff-cut-by-restart"); + yield* orchestrator.dispatch({ + type: "thread.create", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make("command:carried-handoff-cut:create"), + threadId: testThreadId, + projectId, + title: "Carried handoff cut by restart", + modelSelection: CODEX_MODEL_SELECTION, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: cwd, + }); + let step = 0; + const send = (text: string, modelSelection: ModelSelection) => + Effect.gen(function* () { + step += 1; + yield* orchestrator.dispatch({ + type: "message.dispatch", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make(`command:carried-handoff-cut:msg-${step}`), + threadId: testThreadId, + messageId: MessageId.make(`message:carried-handoff-cut:${step}`), + text, + attachments: [], + modelSelection, + dispatchMode: { type: "start_immediately" }, + }); + yield* worker.drain(); + yield* waitForIdle(testThreadId); + yield* worker.drain(); + return yield* orchestrator.getThreadProjection(testThreadId); + }); + + yield* send("Morning task", CODEX_MODEL_SELECTION); + yield* send("Build live draft b63", CLAUDE_MODEL_SELECTION); + // Codex refuses run 3 before its prompt, so run 4 carries the handoff made for run 3. + yield* Ref.set(refuseStarts, 1); + const afterRun3 = yield* send("Resume after failure", CODEX_MODEL_SELECTION); + const run3 = afterRun3.runs.find((run) => run.ordinal === 3)!; + assert.equal(run3.status, "failed"); + const afterRun4 = yield* send("Carry the draft forward", CODEX_MODEL_SELECTION); + const run4 = afterRun4.runs.find((run) => run.ordinal === 4)!; + assert.equal(run4.status, "cancelled"); + const carried = afterRun4.contextHandoffs.find( + (handoff) => handoff.targetRunId === run3.id, + ); + assert.equal(carried?.delivery?.status, "inline"); + assert.include( + (yield* Ref.get(capturedTurns)).at(-1)!.text, + "Afternoon Claude shipped b63 live draft.", + ); + + const afterRun5 = yield* send("Resume", CODEX_MODEL_SELECTION); + const run5Turn = (yield* Ref.get(capturedTurns)).at(-1)!; + assert.include(run5Turn.text, "Afternoon Claude shipped b63 live draft."); + assert.include(run5Turn.text, "Carry the draft forward"); + const run4Turn = afterRun5.providerTurns.find( + (turn) => turn.runAttemptId === run4.activeAttemptId, + ); + assert.equal(run4Turn?.promptDropped, true); + }).pipe( + Effect.provide( + ProviderReplayHarness.layerWithRegistry( + { + name: "carried-handoff-cut-by-restart", + runtimePolicyOverride: { + cwd, + approvalPolicy: "never", + sandboxPolicy: { + type: "readOnly", + access: { type: "fullAccess" }, + networkAccess: false, + }, + }, + }, + layerRegistry, + ), + ), + ); + }), + ); }); diff --git a/packages/provider-core/src/server/ProviderAdapter.ts b/packages/provider-core/src/server/ProviderAdapter.ts index 5cefa6da97fab..a3e15ef9d4e35 100644 --- a/packages/provider-core/src/server/ProviderAdapter.ts +++ b/packages/provider-core/src/server/ProviderAdapter.ts @@ -789,6 +789,14 @@ export interface ProviderAdapterV2SessionRuntime { cwd?: string | null, ) => number | undefined; readonly canReuseContextUsage?: (previous: ModelSelection, next: ModelSelection) => boolean; + /** + * False when the native session no longer holds a cancelled turn's request. Set only by + * providers that can drop one, so a turn a restart cut off is settled like a Stop. + */ + readonly nativeTurnKept?: (input: { + readonly providerThread: OrchestrationV2ProviderThread; + readonly nativeTurnId: string; + }) => Effect.Effect; /** Excludes turn-scoped options from native thread load matching. */ readonly normalizeThreadLoadModelSelection?: (selection: ModelSelection) => ModelSelection; readonly ensureThread: ( diff --git a/packages/provider-cursor/src/server/adapter.test.ts b/packages/provider-cursor/src/server/adapter.test.ts index 1425b87b53486..3b21fcf951ec4 100644 --- a/packages/provider-cursor/src/server/adapter.test.ts +++ b/packages/provider-cursor/src/server/adapter.test.ts @@ -939,6 +939,12 @@ describe("CursorAdapterV2", () => { assert.equal(checkpointed.terminal?.status, "failed"); assert.isUndefined(checkpointed.terminal?.promptDropped); assert.isUndefined(checkpointed.turn?.promptDropped); + + // After a restart no turn ends to report it, so the next turn start asks instead. + const kept = (nativeTurnId: string) => + runtime.nativeTurnKept!({ providerThread, nativeTurnId }); + assert.isFalse(yield* kept("native-cursor-run-1")); + assert.isTrue(yield* kept("native-cursor-run-2")); }).pipe( Effect.scoped, Effect.provide( diff --git a/packages/provider-cursor/src/server/adapter.ts b/packages/provider-cursor/src/server/adapter.ts index 70e7a389f0663..63f8e22aa8b89 100644 --- a/packages/provider-cursor/src/server/adapter.ts +++ b/packages/provider-cursor/src/server/adapter.ts @@ -3372,6 +3372,34 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( ), ), ), + nativeTurnKept: Effect.fn("CursorAdapterV2.nativeTurnKept")( + function* (keptInput: { + readonly providerThread: OrchestrationV2ProviderThread; + readonly nativeTurnId: string; + }) { + const agent = yield* openAgent({ + operation: "resume", + agentId: nativeThreadId(keptInput.providerThread), + storeCwd: keptInput.providerThread.nativeMetadata?.cursorStoreCwd, + threadId: keptInput.providerThread.appThreadId ?? input.threadId, + modelSelection: input.modelSelection, + runtimePolicy: input.runtimePolicy, + }); + if (agent.session.runCheckpointed === undefined) return true; + return yield* agent.session.runCheckpointed(keptInput.nativeTurnId); + }, + (effect, keptInput) => + effect.pipe( + Effect.mapError( + (cause) => + new ProviderAdapter.ProviderAdapterReadThreadSnapshotError({ + driver: CursorAgentSdk.CURSOR_PROVIDER, + providerThreadId: keptInput.providerThread.id, + cause, + }), + ), + ), + ), startTurn, resumeTurn: (input) => startTurn(ProviderAdapter.resumeTurnInput(input)), compactThread: (turnInput) => From f84c7168394eb8541ca928f09177bcd7b5495d1d Mon Sep 17 00:00:00 2001 From: "Paul Dupuy, Jr." <70114489+pauldupuyjr@users.noreply.github.com> Date: Wed, 25 Nov 2026 11:47:55 -0600 Subject: [PATCH 072/238] test(scripts): WSL archive fixture works with Git Bash tar on Windows (#42962) Co-authored-by: Julius Marminge --- scripts/build-desktop-artifact.test.ts | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/scripts/build-desktop-artifact.test.ts b/scripts/build-desktop-artifact.test.ts index 43e89846bded0..e5a0cc3c6e4f4 100644 --- a/scripts/build-desktop-artifact.test.ts +++ b/scripts/build-desktop-artifact.test.ts @@ -104,16 +104,18 @@ const makeLinuxCliArchiveFixture = Effect.fn("test.makeLinuxCliArchiveFixture")( yield* fs.makeDirectory(path.dirname(memberPath), { recursive: true }); yield* fs.writeFileString(memberPath, member); } - const archivePath = path.join(input.root, `${input.stem}.tar.gz`); + const archiveName = `${input.stem}.tar.gz`; const tar = yield* spawner.spawn( - ChildProcess.make("tar", ["-czf", archivePath, "-C", contentRoot, "."], { + // GNU tar reads a drive letter in an absolute archive path as a remote host. + ChildProcess.make("tar", ["-czf", archiveName, "-C", contentRoot, "."], { + cwd: input.root, stdin: "ignore", stdout: "ignore", stderr: "pipe", }), ); assert.equal(Number(yield* tar.exitCode), 0); - return archivePath; + return path.join(input.root, archiveName); }); function mockProcess(exitCode: number, stdout = "") { From 487a29b91659cf7d391fa61f3528e9c991e59cdc Mon Sep 17 00:00:00 2001 From: Kyros Abas Date: Thu, 26 Nov 2026 01:59:00 +0800 Subject: [PATCH 073/238] fix(server): EPUB attachments keep their table captions for agents (#42964) Co-authored-by: Julius Marminge --- apps/server/src/provider/documentTextWorker.ts | 8 +++++++- apps/server/src/provider/userInputAttachments.test.ts | 4 +++- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/apps/server/src/provider/documentTextWorker.ts b/apps/server/src/provider/documentTextWorker.ts index 45b8acba01527..75958b9719709 100644 --- a/apps/server/src/provider/documentTextWorker.ts +++ b/apps/server/src/provider/documentTextWorker.ts @@ -355,8 +355,14 @@ function hasCellText(cell: XmlNode): boolean { ); } function* table(node: XmlNode): Generator { + for (const caption of children(node)) { + if (caption.name !== "caption") continue; + yield LINE_START; + yield* paragraphs(caption); + yield LINE_START; + } let rowCount = 0; - for (const row of all(node, ["tr", "table-row"])) { + for (const row of all(node, ["tr", "table-row"], ["caption"])) { // Word nests a cell inside w:sdt when a content control wraps the whole cell. const cells = [...all(row, ["tc", "table-cell", "covered-table-cell", "td", "th"])]; // ODS writers pad sheets with repeated empty rows and trailing cells. diff --git a/apps/server/src/provider/userInputAttachments.test.ts b/apps/server/src/provider/userInputAttachments.test.ts index 49dcbb9929214..de8dd59a91400 100644 --- a/apps/server/src/provider/userInputAttachments.test.ts +++ b/apps/server/src/provider/userInputAttachments.test.ts @@ -1514,7 +1514,7 @@ describe("question answer paths", () => { "OEBPS/book.opf": '', "OEBPS/a.xhtml": - '

    Last chapter

    Price 10 8 old

    山路やまみちを歩く。東京(とうきょう)に着く。川を見る。海うみ まで。

    ', + '

    Last chapter

    Totals
    Table 1: Revenue
    Q1Q2
    100200

    Table 2: Costs

    Rent

    Price 10 8 old

    山路やまみちを歩く。東京(とうきょう)に着く。川を見る。海うみ まで。

    ', "OEBPS/b.xhtml": 'My Novel

    First chapter

    Larkspur

    Map: North & south piers open.

    Cover art
    Display none imageInvisible image
    Direct div
    Direct section
  • Direct item emphasis trailing
  • Account: A
    Balance: 731Currency: USD
    HeadingTotal
    Important value731
    Before
    Inner
    After
    Neighbor
    Port
    443
    Timeout
    30 seconds

    Prefixed note

    1. Before boarding
      • Check passports
        1. Compare names
      • Confirm gate
    2. Board promptly
    3. Before landing

      • Collect bags
    ' + "
    1. Indented\n
      • Alpha
    ", @@ -1540,6 +1540,8 @@ describe("question answer paths", () => { "Indented\n Alpha", "## Chapter 2", "Last chapter", + "Totals\nTable 1: Revenue\nQ1\tQ2\n100\t200", + "Table 2: Costs\nRent", "Price 10 8 old", "山路(やまみち)を歩く。東京(とうきょう)に着く。川を見る。海(うみ) まで。", "## Chapter 3", From 93b8dc3465ef829c8aa3b375190822550387d33f Mon Sep 17 00:00:00 2001 From: Dara Adedeji <76637177+SunkenInTime@users.noreply.github.com> Date: Wed, 25 Nov 2026 13:00:34 -0500 Subject: [PATCH 074/238] fix(web): Antigravity settings show only the fields the chosen sign-in method uses (#40494) Co-authored-by: shivam <91240327+shivamhwp@users.noreply.github.com> --- .../settings/ProviderSettingsForm.test.ts | 35 ++++++++++++++ .../settings/ProviderSettingsForm.tsx | 46 +++++++++++++++++-- apps/web/src/i18n/translations/de.json | 2 +- apps/web/src/i18n/translations/en.json | 2 +- apps/web/src/i18n/translations/es.json | 2 +- apps/web/src/i18n/translations/fr.json | 2 +- apps/web/src/i18n/translations/ja.json | 2 +- apps/web/src/i18n/translations/ko.json | 2 +- apps/web/src/i18n/translations/pt-BR.json | 2 +- apps/web/src/i18n/translations/ru.json | 2 +- apps/web/src/i18n/translations/sv.json | 2 +- apps/web/src/i18n/translations/zh.json | 2 +- packages/contracts/src/settings.ts | 23 ++++++++-- 13 files changed, 107 insertions(+), 17 deletions(-) diff --git a/apps/web/src/components/settings/ProviderSettingsForm.test.ts b/apps/web/src/components/settings/ProviderSettingsForm.test.ts index 49aa7c30b567d..91b0962a5c32b 100644 --- a/apps/web/src/components/settings/ProviderSettingsForm.test.ts +++ b/apps/web/src/components/settings/ProviderSettingsForm.test.ts @@ -52,6 +52,41 @@ describe("ProviderSettingsForm helpers", () => { expect(next).toEqual({ forkOwned: 1 }); }); + it("shows Antigravity credential fields only for the sign-in methods that read them, or while set", () => { + const antigravity = providerClients.get(ProviderDriverKind.make("antigravity")); + expect(antigravity).toBeDefined(); + const keysFor = (value?: unknown) => + deriveProviderSettingsFields(antigravity!, value).map((field) => field.key); + + expect(keysFor({})).toEqual(["authMethod", "binaryPath"]); + expect( + keysFor({ + authMethod: "oauth-personal", + apiKey: { provider: "vault", reference: "antigravity" }, + gcpLocation: "us-central1", + }), + ).toEqual(["authMethod", "apiKey", "gcpLocation", "binaryPath"]); + expect(keysFor({ authMethod: "oauth-business" })).toEqual([ + "authMethod", + "gcpProject", + "gcpLocation", + "binaryPath", + ]); + expect(keysFor({ authMethod: "gemini-api-key" })).toEqual([ + "authMethod", + "apiKey", + "binaryPath", + ]); + expect(keysFor({ authMethod: "agent-platform" })).toEqual([ + "authMethod", + "apiKey", + "gcpProject", + "gcpLocation", + "binaryPath", + ]); + expect(keysFor()).toEqual(["authMethod", "apiKey", "gcpProject", "gcpLocation", "binaryPath"]); + }); + it("does not store a text value its field's schema rejects", () => { const claude = providerClients.get(ProviderDriverKind.make("claudeAgent")); expect(claude).toBeDefined(); diff --git a/apps/web/src/components/settings/ProviderSettingsForm.tsx b/apps/web/src/components/settings/ProviderSettingsForm.tsx index 6848be472d816..fd185edfdb42c 100644 --- a/apps/web/src/components/settings/ProviderSettingsForm.tsx +++ b/apps/web/src/components/settings/ProviderSettingsForm.tsx @@ -162,8 +162,10 @@ const PACKAGE_FIELD_TEXT: ReadonlyMap = new Map([ ), ], [ - "Google accounts use your subscription; API keys and Agent Platform bill usage.", - msg("Google accounts use your subscription; API keys and Agent Platform bill usage."), + "Google account and Gemini Enterprise use your existing plan. Gemini API key and Agent Platform charge per use to your key or Google Cloud project.", + msg( + "Google account and Gemini Enterprise use your existing plan. Gemini API key and Agent Platform charge per use to your key or Google Cloud project.", + ), ], [ "Gemini or Vertex AI express key. Stored separately on the host.", @@ -259,6 +261,25 @@ function packageFieldText(text: string, resolve: MessageResolver): string { return entry === undefined ? text : resolve(entry); } +/** An unset select shows, and acts as, its first option. */ +function readSelectValue( + config: unknown, + key: string, + options: ReadonlyArray | undefined, +): string { + return readProviderConfigString(config, key) || (options?.[0]?.value ?? ""); +} + +function hasConfiguredValue(config: unknown, key: string): boolean { + if (config === null || typeof config !== "object") return false; + const value = (config as Record)[key]; + return value !== undefined && value !== ""; +} + +/** + * Without a `value`, lists every field. With one, a `visibleWhen` field is hidden only while empty: + * a leftover value still reaches the server, so it stays visible and clearable. + */ export function deriveProviderSettingsFields( definition: SettingsFormDefinition, value?: unknown, @@ -285,6 +306,23 @@ export function deriveProviderSettingsFields( const fieldSchema = definition.settingsSchema.fields[key]!; const formAnnotation = readProviderSettingsFormAnnotation(fieldSchema); if (formAnnotation.hidden) return []; + const visibleWhen = formAnnotation.visibleWhen; + const controller = + visibleWhen === undefined ? undefined : definition.settingsSchema.fields[visibleWhen.field]; + if ( + visibleWhen !== undefined && + value !== undefined && + !hasConfiguredValue(value, key) && + !visibleWhen.values.includes( + readSelectValue( + value, + visibleWhen.field, + controller && readProviderSettingsFormAnnotation(controller).options, + ), + ) + ) { + return []; + } if (isLocalAcp && key !== "source" && key !== "commandPath") return []; const annotatedTitle = readFieldAnnotationString(fieldSchema, "title"); @@ -592,7 +630,7 @@ function ProviderSettingsSelect({ }) { const options = field.options ?? []; const fallback = options[0]?.value ?? ""; - const current = readProviderConfigString(value, field.key) || fallback; + const current = readSelectValue(value, field.key, options); const label = options.find((option) => option.value === current)?.label ?? current; return ( ) : ( - - { - if (surface.kind === "device" && props.canRename) onStartRename(surface.id); - }} - className="cursor-pointer flex min-w-0 items-center" - aria-label={ - sideChatState === null - ? undefined - : gt("{title}, {state}", { - title, - state: messages(SIDE_CHAT_STATE_LABELS[sideChatState]), - }) - } - onClick={() => onActivate(surface)} - > - {title} - - } - /> - - {surface.kind === "device" ? ( + { + if (surface.kind === "device" && props.canRename) onStartRename(surface.id); + }} + className="cursor-pointer flex min-w-0 items-center" + aria-label={ + sideChatState === null + ? undefined + : gt("{title}, {state}", { + title, + state: messages(SIDE_CHAT_STATE_LABELS[sideChatState]), + }) + } + onClick={() => onActivate(surface)} + > + {title} + + } + label={ + surface.kind === "device" ? ( ) : ( title - )} - - + ) + } + /> )} ); @@ -1633,46 +1622,46 @@ export function RightPanelTabs(props: RightPanelTabsProps) { role="group" aria-label={gt("Scroll panel tabs")} > - - - - - } - /> - - Scroll tabs left - - - - - - - } - /> - - Scroll tabs right - - + + + + } + label={ + <> + Scroll tabs left + + } + /> + + + + } + label={ + <> + Scroll tabs right + + } + />
    ) : null} {props.layoutControls} diff --git a/apps/web/src/components/SavedViewsMenu.tsx b/apps/web/src/components/SavedViewsMenu.tsx index 4a31817422459..9a1cebe535307 100644 --- a/apps/web/src/components/SavedViewsMenu.tsx +++ b/apps/web/src/components/SavedViewsMenu.tsx @@ -23,7 +23,7 @@ import { Input } from "./ui/input"; import { Label } from "./ui/label"; import { Menu, MenuItem, MenuItemLabel, MenuPopup, MenuSeparator, MenuTrigger } from "./ui/menu"; import { toastManager } from "./ui/toast"; -import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip"; +import { SharedTooltipTrigger } from "./ui/shared-tooltip"; export interface SavedView { readonly id: string; @@ -142,43 +142,41 @@ export function SavedViewsMenu({ return ( <> - - } aria-label={savedViewsLabel} /> - } - > - - - {selectedView?.name ?? gt("Views", { $context: "saved filter views menu" })} - - {modified ? * : null} - - - {selectedView?.name ?? savedViewsLabel} - + } aria-label={savedViewsLabel} /> + } + label={selectedView?.name ?? savedViewsLabel} + > + + + {selectedView?.name ?? gt("Views", { $context: "saved filter views menu" })} + + {modified ? * : null} + + {views.map((view) => ( - - { - setSelectedId(view.id); - onApply(kind.normalize(view.preferences)); - }} - /> - } - > - {selectedView?.id === view.id && !modified ? ( - - ) : ( - - )} - {view.name} - - {view.name} - + { + setSelectedId(view.id); + onApply(kind.normalize(view.preferences)); + }} + /> + } + label={view.name} + side="right" + > + {selectedView?.id === view.id && !modified ? ( + + ) : ( + + )} + {view.name} + ))} {views.length > 0 ? : null} setEditor({ name: messages(kind.suggestedName(preferences)) })}> diff --git a/apps/web/src/components/ServerUpdateAction.tsx b/apps/web/src/components/ServerUpdateAction.tsx index a3c0ad31a6995..51dcf70862079 100644 --- a/apps/web/src/components/ServerUpdateAction.tsx +++ b/apps/web/src/components/ServerUpdateAction.tsx @@ -42,7 +42,7 @@ import { manualServerUpdateCommand } from "~/versionSkew"; import { crossesReleaseTrack } from "@t3tools/shared/cliRelease"; import { Button } from "./ui/button"; import { toastManager } from "./ui/toast"; -import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip"; +import { SharedTooltipTrigger } from "./ui/shared-tooltip"; const UPDATE_STAGE_LABELS: Record = { downloading: msg("Downloading…"), @@ -264,14 +264,12 @@ export function ServerUpdateProgress({ return (
    - } - /> - {serverUpdateFailureText(state, messages)} - + {serverUpdateFailureText(state, messages)} + } + label={serverUpdateFailureText(state, messages)} + />
    ); } @@ -413,23 +411,21 @@ export function ServerUpdateAction({ if (appearance === "icon") { return ( - - - } - > - - - {actionLabel} - + + } + label={actionLabel} + > + + ); } diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 2ca4abf581ea2..109dc2786b7ae 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -260,7 +260,7 @@ import { import { SidebarContent, SidebarGroup, useSidebar } from "./ui/sidebar"; import { SidebarChromeFooter, SidebarChromeHeader } from "./sidebar/SidebarChrome"; import { SidebarHeaderIconButton, SidebarThreadHeader } from "./sidebar/SidebarThreadHeader"; -import { TooltipProvider, TooltipScrollDismissArea } from "./ui/tooltip"; +import { TooltipScrollDismissArea } from "./ui/tooltip"; import { composerDraftHasUserContent, DraftId, @@ -3344,74 +3344,67 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve {isSearchingThreads ? ( threadSearchResults.length > 0 ? ( - { + contextDragKeyRef.current = String(event.active.id); + }} > - { - contextDragKeyRef.current = String(event.active.id); - }} + + ) : (

    ) : null} {!isSearchingThreads ? ( - - - -

      0 && "flex-1", - actionSweep !== null && "**:pointer-events-none", - // Projected rows (two boundary labels, two hints) extend the scroll range; a range that - // shrinks as the target changes clamps scrollTop and flips the target under a still pointer. - dragState !== null && - "after:pointer-events-none after:absolute after:inset-x-0 after:-bottom-30 after:h-px after:content-['']", - )} - > - {(() => { - const renderThreadRow = ( - thread: EnvironmentThreadShell, - section: SidebarSection, - // The tree row of the project folder this row sits in. - folderRow?: string, - ) => { - const threadKey = scopedThreadKey( - scopeThreadRef(thread.environmentId, thread.id), - ); - const isCard = - section === "active" || section === "pinned" || section === "working"; - const rowVariant = folderRow - ? folderRowsMultiline - ? "folder-multiline" - : "folder" - : isCard - ? "card" - : "slim"; - return ( - - ); - }; - const from = isContextDrag ? null : (dragState?.activeSection ?? null); - const items: ReactNode[] = [ - , - ]; - for (const item of sidebarListItems) { - if (item.kind === "thread") { - // Folders draw active rows in their own place below. - if (projectFolders !== null && item.section === "active") continue; - items.push(renderThreadRow(threadByKey.get(item.key)!, item.section)); - continue; - } - if (projectFolders !== null && item.marker === "active-placeholder") { - for (const folder of projectFolders) { - items.push( - , - ); - for (const thread of folder.threads) { - items.push( - renderThreadRow( - thread, - "active", - sidebarFolderRowId(folder.group.projectKey), - ), - ); - } + +
        0 && "flex-1", + actionSweep !== null && "**:pointer-events-none", + // Projected rows (two boundary labels, two hints) extend the scroll range; a range that + // shrinks as the target changes clamps scrollTop and flips the target under a still pointer. + dragState !== null && + "after:pointer-events-none after:absolute after:inset-x-0 after:-bottom-30 after:h-px after:content-['']", + )} + > + {(() => { + const renderThreadRow = ( + thread: EnvironmentThreadShell, + section: SidebarSection, + // The tree row of the project folder this row sits in. + folderRow?: string, + ) => { + const threadKey = scopedThreadKey( + scopeThreadRef(thread.environmentId, thread.id), + ); + const isCard = + section === "active" || section === "pinned" || section === "working"; + const rowVariant = folderRow + ? folderRowsMultiline + ? "folder-multiline" + : "folder" + : isCard + ? "card" + : "slim"; + return ( + , - ); - break; - case "pinned-divider": - items.push( - , - ); - break; - case "active-placeholder": - items.push( - , - ); - break; - case "working-header": - items.push( - , - ); - break; - case "snoozed-header": - items.push( - , - ); - break; - case "settled-header": - items.push( - , - ); - break; - case "settled-placeholder": + thread={thread} + variant={rowVariant} + navigationParent={ + folderRow ?? + (section === "working" || section === "snoozed" || section === "settled" + ? `shelf:${section}` + : undefined) + } + variantAction={ + section === "snoozed" + ? "unsnooze" + : section === "settled" + ? "unsettle" + : "settle" + } + settlementSupported={serverConfigs.has(thread.environmentId)} + snoozeSupported={serverConfigs.has(thread.environmentId)} + pinningSupported={serverConfigs.has(thread.environmentId)} + isPinned={thread.pinnedAt != null} + dropVerb={ + dragState?.activeKey === threadKey + ? resolveSidebarDropVerb(dragState.activeSection, dragTargetSection) + : null + } + dragOverPinned={ + dragState?.activeKey === threadKey && dragTargetSection === "pinned" + } + sweepAction={actionSweep?.keys.has(threadKey) ? actionSweep.action : null} + snoozeWakeLabelText={ + section === "snoozed" && thread.snoozedUntil != null + ? snoozeWakeLabel( + thread.snoozedUntil, + { now: new Date().toISOString() }, + messages, + ) + : null + } + wokeAt={threadWokeAt(thread, { now: snoozeNow })} + isActive={routeRowThreadKey === threadKey} + revealRef={routeRowThreadKey === threadKey ? revealActiveRow : undefined} + isRouteThread={routeThreadKey === threadKey} + readOpensPullRequestsInRightPanel={readOpensPullRequestsInRightPanel} + jumpLabel={showJumpHints ? (jumpLabelByKey.get(threadKey) ?? null) : null} + environmentLabel={environmentLabelById.get(thread.environmentId) ?? null} + environmentMachine={ + environmentMachineById.get(thread.environmentId) ?? "server" + } + project={ + projectByKey.get(`${thread.environmentId}:${thread.projectId}`) ?? null + } + projectDisplayName={ + projectDisplayNameByKey.get( + `${thread.environmentId}:${thread.projectId}`, + ) ?? null + } + providerEntryByInstanceId={ + providerEntriesByEnvironment.get(thread.environmentId) ?? + EMPTY_PROVIDER_ENTRIES + } + timestampFormat={timestampFormat} + onThreadClick={handleThreadClick} + onThreadActivate={navigateToThread} + onStartRename={startThreadRename} + onRenameTitleChange={setRenamingTitle} + onCommitRename={commitThreadRename} + onCancelRename={cancelThreadRename} + isRenaming={renamingThreadKey === threadKey} + renamingTitle={renamingThreadKey === threadKey ? renamingTitle : ""} + onContextMenu={handleThreadContextMenu} + onSettle={attemptSettle} + onActionSweepStart={startActionSweep} + onUnsettle={attemptUnsettle} + onSnooze={attemptSnooze} + onUnsnooze={attemptUnsnooze} + onUnpin={attemptUnpin} + onAcknowledgeWoke={acknowledgeWoke} + onFileDropThreads={handleThreadFileDrop} + /> + ); + }; + const from = isContextDrag ? null : (dragState?.activeSection ?? null); + const items: ReactNode[] = [ + , + ]; + for (const item of sidebarListItems) { + if (item.kind === "thread") { + // Folders draw active rows in their own place below. + if (projectFolders !== null && item.section === "active") continue; + items.push(renderThreadRow(threadByKey.get(item.key)!, item.section)); + continue; + } + if (projectFolders !== null && item.marker === "active-placeholder") { + for (const folder of projectFolders) { + items.push( + , + ); + for (const thread of folder.threads) { items.push( - , + renderThreadRow( + thread, + "active", + sidebarFolderRowId(folder.group.projectKey), + ), ); - break; + } } + continue; } - return items; - })()} - {settledShelfExpanded && hiddenSettledCount > 0 ? ( -
      • - -
      • - ) : null} -
      -
      - - + switch (item.marker) { + case "pinned-header": + items.push( + , + ); + break; + case "pinned-divider": + items.push( + , + ); + break; + case "active-placeholder": + items.push( + , + ); + break; + case "working-header": + items.push( + , + ); + break; + case "snoozed-header": + items.push( + , + ); + break; + case "settled-header": + items.push( + , + ); + break; + case "settled-placeholder": + items.push( + , + ); + break; + } + } + return items; + })()} + {settledShelfExpanded && hiddenSettledCount > 0 ? ( +
    • + +
    • + ) : null} +
    + + ) : null}
    diff --git a/apps/web/src/components/StartTruncatedPath.tsx b/apps/web/src/components/StartTruncatedPath.tsx index 60cb6cdc740d9..70653d0d0b16d 100644 --- a/apps/web/src/components/StartTruncatedPath.tsx +++ b/apps/web/src/components/StartTruncatedPath.tsx @@ -1,25 +1,22 @@ -import { Tooltip, TooltipPopup, TooltipTrigger } from "~/components/ui/tooltip"; import { cn } from "~/lib/utils"; +import { SharedTooltipTrigger } from "~/components/ui/shared-tooltip"; export function StartTruncatedPath({ path, className }: { path: string; className?: string }) { return ( - - - } - > - {path} - - - {path} - - + + } + label={path} + variant="code" + > + {path} + ); } diff --git a/apps/web/src/components/ThreadHoverCard.tsx b/apps/web/src/components/ThreadHoverCard.tsx index ae6774a98d76d..33598faf08a55 100644 --- a/apps/web/src/components/ThreadHoverCard.tsx +++ b/apps/web/src/components/ThreadHoverCard.tsx @@ -1,13 +1,35 @@ import type { ComponentProps, ReactNode } from "react"; +import { SharedTooltipTrigger } from "./ui/shared-tooltip"; import { TooltipPopup } from "./ui/tooltip"; import { cn } from "~/lib/utils"; +const HOVER_CARD_CLASS_NAME = "max-w-80 text-left whitespace-normal"; + export function ThreadHoverCardPopup({ className, ...props }: ComponentProps) { return ( - + ); +} + +/** A thread hover card on `render`, drawn by the shared tooltip so a list of rows mounts none. */ +export function ThreadHoverCardTrigger({ + card, + side = "right", + align = "start", + sideOffset = 4, + ...props +}: Omit, "label" | "variant" | "className"> & { + card: ReactNode; +}) { + return ( + ); } diff --git a/apps/web/src/components/ThreadStatusIndicators.tsx b/apps/web/src/components/ThreadStatusIndicators.tsx index a73cd8dea1cab..dc8890f252d8a 100644 --- a/apps/web/src/components/ThreadStatusIndicators.tsx +++ b/apps/web/src/components/ThreadStatusIndicators.tsx @@ -59,7 +59,7 @@ import { } from "./Sidebar.logic"; import type { SidebarThreadSummary } from "../types"; -import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip"; +import { SharedTooltipTrigger } from "./ui/shared-tooltip"; import { PULL_REQUEST_STATE_PRESENTATION, PullRequestGlyph, @@ -520,25 +520,23 @@ export function ThreadLinkBadge({ children: ReactNode; }) { return ( - - - - - {text} - - - event.stopPropagation()} - > + // The shared popup renders at the app root, so a right-click in it never reaches the row. + {children}
    - - + } + > + + + {text} + + ); } @@ -768,35 +766,33 @@ export function ThreadTerminalStatusButton({ { count: terminalIds.length }, ); return ( - - event.stopPropagation()} - onKeyDown={(event) => event.stopPropagation()} - onClick={(event) => { - event.preventDefault(); - event.stopPropagation(); - revealThreadTerminal(threadRef, terminalId); - onThreadActivate(threadRef); - }} - /> - } - > - event.stopPropagation()} + onKeyDown={(event) => event.stopPropagation()} + onClick={(event) => { + event.preventDefault(); + event.stopPropagation(); + revealThreadTerminal(threadRef, terminalId); + onThreadActivate(threadRef); + }} /> - - {label} - + } + label={label} + > + + ); } @@ -811,47 +807,43 @@ function ThreadStatusLabel({ const label = m(status.label); if (compact) { return ( - - - } - > - - - {label} - - ); - } - - return ( - - } + label={label} > - {label} - - {label} - + + ); + } + + return ( + + } + label={label} + > + + {label} + ); } @@ -926,21 +918,21 @@ export function ThreadRowLeadingStatus({ thread }: { thread: SidebarThreadSummar } > {prStatus && pr ? ( - - - } - > - - - - - - + + } + label={ + <> + + + } + > + + ) : null} {pendingLink ? ( {terminalStatus ? ( - - - } - > - - - {terminalStatus.label} - + } + label={terminalStatus.label} + > + + ) : null} {isRemoteThread ? ( - - - } - > - - - {threadEnvironmentLabel} - + } + label={threadEnvironmentLabel} + > + + ) : null}
    ); diff --git a/apps/web/src/components/chat/ChatHeader.tsx b/apps/web/src/components/chat/ChatHeader.tsx index fc85231139a28..0b11a6c7f1242 100644 --- a/apps/web/src/components/chat/ChatHeader.tsx +++ b/apps/web/src/components/chat/ChatHeader.tsx @@ -24,7 +24,6 @@ import { import { isTrailingDoubleClick } from "../Sidebar.logic"; import { Badge } from "../ui/badge"; import { MiddleTruncate } from "../ui/middle-truncate"; -import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { toastManager } from "../ui/toast"; import { useThreadActionMenu } from "~/hooks/useThreadActionMenu"; import { readLocalApi } from "~/localApi"; @@ -45,6 +44,7 @@ import { cn } from "~/lib/utils"; import { textDirection } from "~/textDirection"; import { useClientSettings } from "../../hooks/useSettings"; import { GuestShareIndicator } from "./GuestShareControls"; +import { SharedTooltipTrigger } from "../ui/shared-tooltip"; interface ChatHeaderProps { activeThreadEnvironmentId: EnvironmentId; @@ -266,31 +266,31 @@ export const ChatHeader = memo(function ChatHeader({ {activeProject ? ( <> - - - } - > - - - - - - New thread in {activeProjectName} - - - + } + label={ + <> + + New thread in {activeProjectName} + + + } + > + + + / @@ -300,33 +300,31 @@ export const ChatHeader = memo(function ChatHeader({ {parentThreadLink ? ( <> - - onOpenThread(parentThreadLink.threadId)} - className="inline-flex min-w-0 max-w-full cursor-pointer items-center rounded-sm text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring" - /> - } + onOpenThread(parentThreadLink.threadId)} + className="inline-flex min-w-0 max-w-full cursor-pointer items-center rounded-sm text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring" + /> + } + label={parentThreadLink.title} + > + - - {parentThreadLink.title} - - {collapseParentTitle ? ( - - ... - - ) : null} - - {parentThreadLink.title} - + {parentThreadLink.title} + + {collapseParentTitle ? ( + + ... + + ) : null} + / @@ -356,60 +354,58 @@ export const ChatHeader = memo(function ChatHeader({ onKeyDown={handleRenameKeyDown} /> ) : isServerThread ? ( - - - } - > -

    - {activeThreadTitle} -

    - -
    - {activeThreadTitle} -
    - ) : ( - - - } - > + } + label={activeThreadTitle} + > +

    {activeThreadTitle} - - {activeThreadTitle} - +

    + + + ) : ( + + } + label={activeThreadTitle} + > + {activeThreadTitle} + )} {renamingTitle === null && activeThreadLinkOrigin ? ( - - }> - - From {activeThreadLinkOrigin} - - - - - Started by an agent on {activeThreadLinkOrigin} through a linked - environment. - - - + } + label={ + <> + + Started by an agent on {activeThreadLinkOrigin} through a linked + environment. + + + } + > + + From {activeThreadLinkOrigin} + + ) : null} diff --git a/apps/web/src/components/chat/ComposerAttachmentStrip.tsx b/apps/web/src/components/chat/ComposerAttachmentStrip.tsx index 686b16da17ae1..8369299510023 100644 --- a/apps/web/src/components/chat/ComposerAttachmentStrip.tsx +++ b/apps/web/src/components/chat/ComposerAttachmentStrip.tsx @@ -36,7 +36,6 @@ import { AttachmentFilePreview } from "../files/AttachmentFilePreview"; import { AttachmentImage } from "../media/AttachmentImage"; import { Button } from "../ui/button"; import { Dialog, DialogPopup, DialogTitle } from "../ui/dialog"; -import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { ComposerImageThumbnail } from "./ComposerImageThumbnail"; import { composerFloatingLayerProps } from "./composerEventScope"; import type { PreparingComposerImage } from "./preparingComposerImages"; @@ -51,6 +50,7 @@ import { SnapShotAttachmentDetails, } from "./SnapShotAttachmentDetails"; import { prepareVideoFirstFrame } from "../../lib/videoFirstFrame"; +import { SharedTooltipTrigger } from "../ui/shared-tooltip"; function ComposerAttachmentUploadProgress({ id, @@ -271,24 +271,24 @@ export function ComposerAttachmentMediaRow({ /> ) : null} {nonPersistedImageIdSet.has(image.id) && ( - - - - - } - /> - - - Draft attachment could not be saved locally and may be lost on navigation. - - - + + + + } + label={ + <> + + Draft attachment could not be saved locally and may be lost on navigation. + + + } + /> )} {(!ready || upload?.status === "uploading") && ( @@ -302,31 +302,27 @@ export function ComposerAttachmentMediaRow({ )} {ready && upload?.status === "failed" && ( - - - retryAttachmentUpload({ - environmentId, - image: ready, - draftTarget: attachmentDraftTarget, - }) - } - disabled={!canOperateThread} - aria-label={gt("Retry upload for {name}", { name: image.name })} - /> - } - > - - - - {attachmentUploadFailureText(upload, messages)} - - + + retryAttachmentUpload({ + environmentId, + image: ready, + draftTarget: attachmentDraftTarget, + }) + } + disabled={!canOperateThread} + aria-label={gt("Retry upload for {name}", { name: image.name })} + /> + } + label={attachmentUploadFailureText(upload, messages)} + > + + )} )} {upload?.status === "failed" && ( - - - retryAttachmentUpload({ - environmentId, - image: file, - draftTarget: attachmentDraftTarget, - }) - } - disabled={!canOperateThread} - aria-label={gt("Retry upload for {name}", { name: file.name })} - /> - } - > - - - - {attachmentUploadFailureText(upload, messages)} - - + + retryAttachmentUpload({ + environmentId, + image: file, + draftTarget: attachmentDraftTarget, + }) + } + disabled={!canOperateThread} + aria-label={gt("Retry upload for {name}", { name: file.name })} + /> + } + label={attachmentUploadFailureText(upload, messages)} + > + + )} ; return ( - - }>{content} - - {props.description} - - + } + label={props.description} + side="right" + className="max-w-56" + > + {content} + ); } @@ -604,10 +606,9 @@ function SpeedSegment(props: { ); if (!props.description) return ; return ( - - }>{content} - {props.description} - + } label={props.description}> + {content} + ); } diff --git a/apps/web/src/components/chat/ComposerPendingApprovalActions.tsx b/apps/web/src/components/chat/ComposerPendingApprovalActions.tsx index 07f935aaee5e6..b12011046c3ca 100644 --- a/apps/web/src/components/chat/ComposerPendingApprovalActions.tsx +++ b/apps/web/src/components/chat/ComposerPendingApprovalActions.tsx @@ -8,8 +8,8 @@ import { memo } from "react"; import { EllipsisIcon, TriangleAlertIcon } from "lucide-react"; import { Button, InlineButton } from "../ui/button"; import { Menu, MenuItem, MenuPopup, MenuTrigger } from "../ui/menu"; -import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { composerFloatingLayerProps } from "./composerEventScope"; +import { SharedTooltipTrigger } from "../ui/shared-tooltip"; interface ComposerPendingApprovalActionsProps { presentation?: "composer" | "inline"; @@ -100,10 +100,7 @@ export const ComposerPendingApprovalActions = memo(function ComposerPendingAppro ); return option.warning ? ( - - - {option.warning} - + ) : ( button ); @@ -145,10 +142,7 @@ export const ComposerPendingApprovalActions = memo(function ComposerPendingAppro ); return option.warning ? ( - - - {option.warning} - + ) : ( item ); diff --git a/apps/web/src/components/chat/ComposerPrimaryActions.tsx b/apps/web/src/components/chat/ComposerPrimaryActions.tsx index 20a2166676fc9..99f5fafef38ec 100644 --- a/apps/web/src/components/chat/ComposerPrimaryActions.tsx +++ b/apps/web/src/components/chat/ComposerPrimaryActions.tsx @@ -24,6 +24,7 @@ import { StageBackdropButtonArt, useSidebarStageBackdropVariant } from "../Sideb import { Button } from "../ui/button"; import { Spinner } from "../ui/spinner"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; +import { SharedTooltipTrigger } from "../ui/shared-tooltip"; import { alternateComposerDispatchAction, resolveComposerDispatchMode, @@ -156,36 +157,34 @@ function StopGenerationButton({ const gt = useGT(); const isStopDisabled = stopPhase === "pending"; return ( - - { - if (!canOperateThread || isStopDisabled) return; - onStopRequested(); - onInterrupt(); - }} - aria-label={stopPhase === "pending" ? gt("Stopping") : gt("Stop generation")} - /> - } - > - - - - {stopPhase === "pending" + { + if (!canOperateThread || isStopDisabled) return; + onStopRequested(); + onInterrupt(); + }} + aria-label={stopPhase === "pending" ? gt("Stopping") : gt("Stop generation")} + /> + } + label={ + stopPhase === "pending" ? gt("Stopping…") - : gt("Interrupt", { $context: "verb, stops the running agent" })} - - + : gt("Interrupt", { $context: "verb, stops the running agent" }) + } + > + + ); } @@ -510,41 +509,41 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({ return withStopButton(
    - - - } - > - - -
    - {keepFullHistory - ? gt("Next send keeps all {tokens} tokens.", { tokens: compactTokens }) - : gt("Next send compacts {tokens} tokens first.", { tokens: compactTokens })} -
    -
    - {keepFullHistory ? gt("Click to compact first") : gt("Click to keep full history")} -
    -
    -
    + + } + label={ + <> +
    + {keepFullHistory + ? gt("Next send keeps all {tokens} tokens.", { tokens: compactTokens }) + : gt("Next send compacts {tokens} tokens first.", { tokens: compactTokens })} +
    +
    + {keepFullHistory ? gt("Click to compact first") : gt("Click to keep full history")} +
    + + } + > +
    {children} {submit}
    , diff --git a/apps/web/src/components/chat/ComposerSpeechButton.tsx b/apps/web/src/components/chat/ComposerSpeechButton.tsx index 5d547f0c45e08..e2bf41c5069f4 100644 --- a/apps/web/src/components/chat/ComposerSpeechButton.tsx +++ b/apps/web/src/components/chat/ComposerSpeechButton.tsx @@ -9,7 +9,7 @@ import { m, type MessageResolver } from "~/i18n/messages"; import { cn } from "~/lib/utils"; import { Button } from "../ui/button"; import { Spinner } from "../ui/spinner"; -import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; +import { SharedTooltipTrigger } from "../ui/shared-tooltip"; type DownloadProgress = { downloaded: number; total: number } | null; @@ -103,13 +103,15 @@ function ShortcutTooltip(props: { children: ReactElement; }) { return ( - - - - {props.label} - {props.shortcut ? ` (${props.shortcut})` : ""} - - + + {props.label} + {props.shortcut ? ` (${props.shortcut})` : ""} + + } + /> ); } diff --git a/apps/web/src/components/chat/DraftHeroHeadline.tsx b/apps/web/src/components/chat/DraftHeroHeadline.tsx index c01ad1ee78fc5..30b0927e1883d 100644 --- a/apps/web/src/components/chat/DraftHeroHeadline.tsx +++ b/apps/web/src/components/chat/DraftHeroHeadline.tsx @@ -39,6 +39,7 @@ import { useComboboxFilter, } from "../ui/combobox"; import { Tooltip, TooltipPopup, TooltipScrollDismissArea, TooltipTrigger } from "../ui/tooltip"; +import { SharedTooltipTrigger } from "../ui/shared-tooltip"; import { InlineButton } from "../ui/button"; import { DraftProjectName } from "./DraftProjectName"; import { DraftHeroProjectHeading } from "./DraftHeroProjectHeading"; @@ -272,12 +273,12 @@ export function DraftHeroHeadline({ ) : entry ? ( ) : null} - - }> - - - {item.label} - + } + label={item.label} + > + + {entry && canPinProjectGroup(entry.group) ? ( 1 ? ` (${index + 1}/${preview.images.length})` : ""}
    {accessibilityDetails && item.source ? ( - - - setAccessibilityDetailsSrc(showingAccessibilityDetails ? null : item.src) - } - size="icon-micro" - variant="overlay" - /> - } - > - {showingAccessibilityDetails ? ( - - {contentsLabel} - + + setAccessibilityDetailsSrc(showingAccessibilityDetails ? null : item.src) + } + size="icon-micro" + variant="overlay" + /> + } + label={contentsLabel} + > + {showingAccessibilityDetails ? ( + ) : item.source ? ( ) : null} diff --git a/apps/web/src/components/chat/HtmlRenderFrame.tsx b/apps/web/src/components/chat/HtmlRenderFrame.tsx index d3741a6f06e8d..ab7be4db014af 100644 --- a/apps/web/src/components/chat/HtmlRenderFrame.tsx +++ b/apps/web/src/components/chat/HtmlRenderFrame.tsx @@ -15,9 +15,9 @@ import { useLongLivedAssetUrl } from "~/assets/longLivedAssetUrls"; import { HtmlRenderDocument } from "../files/BrowserDocumentFrame"; import { Button } from "../ui/button"; import { toastManager } from "../ui/toast"; -import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { HtmlRenderDialog } from "./HtmlRenderDialog"; import { observeResize } from "~/lib/observeResize"; +import { SharedTooltipTrigger } from "../ui/shared-tooltip"; const MIN_URL_LIFE_MS = 5 * 60_000; const MAX_MEASURED_CONTENT_HEIGHTS = 200; @@ -100,35 +100,36 @@ export function HtmlRenderFrame(props: { onFullscreenChange={onFullscreenChange} />
    - - { - const url = - loaded !== null && loaded.expiresAt - Date.now() > MIN_URL_LIFE_MS - ? src - : await refresh().catch(() => null); - if (url !== null) setExpandedSrc(url); - else - toastManager.add({ - type: "error", - title: gt("Page unavailable"), - description: gt("Reconnect to the environment and try again."), - }); - }} - /> - } - > - - - - Open full screen - - + { + const url = + loaded !== null && loaded.expiresAt - Date.now() > MIN_URL_LIFE_MS + ? src + : await refresh().catch(() => null); + if (url !== null) setExpandedSrc(url); + else + toastManager.add({ + type: "error", + title: gt("Page unavailable"), + description: gt("Reconnect to the environment and try again."), + }); + }} + /> + } + label={ + <> + Open full screen + + } + side="left" + > + +
    {expandedSrc !== null ? ( - - - {tooltipContent} - -
    + ); }, areMarkdownFileLinkPropsEqual); diff --git a/apps/web/src/components/chat/MarkdownMermaidCodeBlock.tsx b/apps/web/src/components/chat/MarkdownMermaidCodeBlock.tsx index 2a7093003a480..5f56c8f46e653 100644 --- a/apps/web/src/components/chat/MarkdownMermaidCodeBlock.tsx +++ b/apps/web/src/components/chat/MarkdownMermaidCodeBlock.tsx @@ -4,10 +4,10 @@ import { Suspense, use, useState, type ReactNode } from "react"; import { RenderErrorBoundary } from "../RenderErrorBoundary"; import { Button } from "../ui/button"; -import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { MarkdownCodeBlock } from "./MarkdownCodeBlock"; import { findRevealRef, MarkdownFindContext } from "./markdownFindContext"; import { MermaidDiagram } from "./MermaidDiagram"; +import { SharedTooltipTrigger } from "../ui/shared-tooltip"; export function MarkdownMermaidCodeBlock({ code, @@ -42,22 +42,20 @@ export function MarkdownMermaidCodeBlock({ diagram={showDiagram} viewToggle={ isStreaming ? null : ( - - setShowCode((value) => !value)} - aria-label={toggleLabel} - /> - } - > - {showCode ? : } - - {toggleLabel} - + setShowCode((value) => !value)} + aria-label={toggleLabel} + /> + } + label={toggleLabel} + > + {showCode ? : } + ) } > diff --git a/apps/web/src/components/chat/MarkdownTable.tsx b/apps/web/src/components/chat/MarkdownTable.tsx index 39193279a0179..3abec62576005 100644 --- a/apps/web/src/components/chat/MarkdownTable.tsx +++ b/apps/web/src/components/chat/MarkdownTable.tsx @@ -11,8 +11,8 @@ import { import { Button } from "../ui/button"; import { Menu, MenuItem, MenuPopup, MenuTrigger } from "../ui/menu"; import { ScrollArea } from "../ui/scroll-area"; -import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { reportMarkdownActionFailure, type TableCopyFormat } from "./markdownActionFailure"; +import { SharedTooltipTrigger } from "../ui/shared-tooltip"; const TABLE_COPY_SERIALIZERS: Record string> = { markdown: serializeTableElementToMarkdown, @@ -51,25 +51,23 @@ export function MarkdownTable({ children, ...props }: ComponentProps<"table">) { {/* Stays within the row's px-1: the chat lane clips sideways overflow. */}
    - - - } - /> - } - > - {copied ? : } - - {copyLabel} - + + } + /> + } + label={copyLabel} + > + {copied ? : } + handleCopy("markdown")}> Copy as Markdown diff --git a/apps/web/src/components/chat/MarkdownThreadLink.tsx b/apps/web/src/components/chat/MarkdownThreadLink.tsx index 6c65fc7ed0ecf..b3247ae88ab58 100644 --- a/apps/web/src/components/chat/MarkdownThreadLink.tsx +++ b/apps/web/src/components/chat/MarkdownThreadLink.tsx @@ -22,7 +22,7 @@ import { useEnvironmentQuery } from "../../state/query"; import { ContextChip, ContextChipLabel } from "../ContextChip"; import { UnresolvedChip } from "../contextChipParts"; import { ThreadContextChip } from "../ThreadContextChip"; -import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; +import { SharedTooltipTrigger } from "../ui/shared-tooltip"; /** `label` is the link's written text; an autolink has none. */ export function MarkdownThreadLink(props: { @@ -89,43 +89,39 @@ export function MarkdownThreadLink(props: { const knownTitle = props.label ?? written?.title ?? null; const title = knownTitle ?? gt("Thread on {label}", { label: linkedLabel }); return ( - - - openLinkedThreadRead({ - panelRef, - target: { - viaEnvironmentId: props.environmentId, - ...writtenRef, - label: linkedLabel, - title: knownTitle, - }, - intent, - navigate, - }), - // Outside a thread there is no panel to read it in. - { panel: panelRef !== null }, - )} - /> - } - aria-label={gt("Thread, {title}", { title })} - > - - {title} - - } - /> - - {gt("Read the thread on {label}", { label: linkedLabel })} - - + + openLinkedThreadRead({ + panelRef, + target: { + viaEnvironmentId: props.environmentId, + ...writtenRef, + label: linkedLabel, + title: knownTitle, + }, + intent, + navigate, + }), + // Outside a thread there is no panel to read it in. + { panel: panelRef !== null }, + )} + /> + } + aria-label={gt("Thread, {title}", { title })} + > + + {title} + + } + label={gt("Read the thread on {label}", { label: linkedLabel })} + /> ); } if (missing && resolved === null) { diff --git a/apps/web/src/components/chat/MessageCopyButton.tsx b/apps/web/src/components/chat/MessageCopyButton.tsx index 9dc43abe02d88..3f65da7e4136a 100644 --- a/apps/web/src/components/chat/MessageCopyButton.tsx +++ b/apps/web/src/components/chat/MessageCopyButton.tsx @@ -7,7 +7,7 @@ import { ANCHORED_COPY_TOAST_TIMEOUT_MS, showAnchoredCopyErrorToast, } from "../ui/anchoredCopyToast"; -import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; +import { SharedTooltipTrigger } from "../ui/shared-tooltip"; export const MessageCopyButton = memo(function MessageCopyButton({ text, @@ -36,26 +36,26 @@ export const MessageCopyButton = memo(function MessageCopyButton({ }); return ( - - copyToClipboard(text)} - ref={ref} - type="button" - size={size} - variant={variant === "ghost" ? "ghost-muted" : variant} - className={className} - /> - } - > - {isCopied ? : } - - -

    {label}

    -
    -
    + copyToClipboard(text)} + ref={ref} + type="button" + size={size} + variant={variant === "ghost" ? "ghost-muted" : variant} + className={className} + /> + } + label={ + <> +

    {label}

    + + } + > + {isCopied ? : } +
    ); }); diff --git a/apps/web/src/components/chat/ModelListRow.tsx b/apps/web/src/components/chat/ModelListRow.tsx index 74dae2dc23582..006484b65c7a6 100644 --- a/apps/web/src/components/chat/ModelListRow.tsx +++ b/apps/web/src/components/chat/ModelListRow.tsx @@ -7,10 +7,10 @@ import { ComboboxItem } from "../ui/combobox"; import { Button } from "../ui/button"; import { Badge } from "../ui/badge"; import { Kbd } from "../ui/kbd"; -import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { cn } from "~/lib/utils"; import { modelPickerModelKey } from "./modelPickerKeys"; import { ProviderInstanceIcon } from "./ProviderInstanceIcon"; +import { SharedTooltipTrigger } from "../ui/shared-tooltip"; export const ModelListRow = memo(function ModelListRow(props: { index: number; @@ -103,37 +103,34 @@ export const ModelListRow = memo(function ModelListRow(props: {
    - - { - event.stopPropagation(); - props.onToggleFavorite(props.instanceId, props.slug); - }} - onKeyDown={(event) => { - event.stopPropagation(); - }} - disabled={Boolean(props.disabledReason)} - aria-label={props.isFavorite ? gt("Remove from favorites") : gt("Add to favorites")} - > - - - } - /> - - {props.isFavorite ? gt("Remove from favorites") : gt("Add to favorites")} - - + { + event.stopPropagation(); + props.onToggleFavorite(props.instanceId, props.slug); + }} + onKeyDown={(event) => { + event.stopPropagation(); + }} + disabled={Boolean(props.disabledReason)} + aria-label={props.isFavorite ? gt("Remove from favorites") : gt("Add to favorites")} + > + + + } + label={props.isFavorite ? gt("Remove from favorites") : gt("Add to favorites")} + align="center" + /> {props.jumpLabel ? {props.jumpLabel} : null}
    @@ -144,11 +141,6 @@ export const ModelListRow = memo(function ModelListRow(props: { } return ( - - - - {props.disabledReason} - - + ); }); diff --git a/apps/web/src/components/chat/ModelPickerContent.tsx b/apps/web/src/components/chat/ModelPickerContent.tsx index 59b67580a4b16..3fa888ffed0cc 100644 --- a/apps/web/src/components/chat/ModelPickerContent.tsx +++ b/apps/web/src/components/chat/ModelPickerContent.tsx @@ -64,7 +64,6 @@ import { import { announce } from "~/lib/announce"; import { cn } from "~/lib/utils"; import { getVirtualizedScrollFadeClassName } from "../ui/scroll-area"; -import { TooltipProvider } from "../ui/tooltip"; import { InlineButton } from "../ui/button"; import { Badge } from "../ui/badge"; import { @@ -956,7 +955,7 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { }; return ( - + <>
    -
    + ); }); diff --git a/apps/web/src/components/chat/OpenInPicker.tsx b/apps/web/src/components/chat/OpenInPicker.tsx index a4b7322aa5dda..6c734149d50c5 100644 --- a/apps/web/src/components/chat/OpenInPicker.tsx +++ b/apps/web/src/components/chat/OpenInPicker.tsx @@ -36,7 +36,7 @@ import { MenuSubPopup, MenuTrigger, } from "../ui/menu"; -import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; +import { SharedTooltipTrigger } from "../ui/shared-tooltip"; import { type EditorIconOption, editorIconOptions } from "../editorIcons"; import { announce } from "~/lib/announce"; import { cn } from "~/lib/utils"; @@ -311,43 +311,40 @@ export const OpenInPicker = memo(function OpenInPicker({ ? { className: THREAD_DETAILS_PANEL_SPLIT_GROUP_CLASS, ref: panelAnchorRef } : {})} > - - - {primaryControlLabel} - + {isPanel ? (
    ); @@ -157,27 +160,22 @@ export const RightPanelMaximizeControl = memo(function RightPanelMaximizeControl const gt = useGT(); const label = maximized ? gt("Restore panel size") : gt("Maximize panel"); return ( - - - {maximized ? ( - - ) : ( - - )} - - } - /> - {label} - + + {maximized ? : } + + } + label={label} + side="bottom" + /> ); }); diff --git a/apps/web/src/components/chat/ProviderModelPicker.tsx b/apps/web/src/components/chat/ProviderModelPicker.tsx index 254b1ffeac937..d136a54fc6066 100644 --- a/apps/web/src/components/chat/ProviderModelPicker.tsx +++ b/apps/web/src/components/chat/ProviderModelPicker.tsx @@ -19,7 +19,6 @@ import { } from "react"; import { Badge } from "../ui/badge"; import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover"; -import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { cn } from "~/lib/utils"; import { useMediaQuery } from "../../hooks/useMediaQuery"; import { ModelPickerContent, resolveModelPickerSelectedModel } from "./ModelPickerContent"; @@ -33,6 +32,7 @@ import { takeOpenTarget, useComposerMenuProps } from "./composerEventScope"; import { shortcutLabelForCommand } from "../../keybindings"; import { serverEnvironment } from "../../state/server"; import { useAtomCommand } from "../../state/use-atom-command"; +import { SharedTooltipTrigger } from "../ui/shared-tooltip"; /** Holds the page still behind the open picker; its lifetime is the popup element's. */ function lockBackgroundScroll(popup: HTMLElement | null) { @@ -435,10 +435,12 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: { {props.isComposerOwned ? ( {triggerText} ) : ( - - }>{triggerText} - {triggerTooltipContent} - + } + label={triggerTooltipContent} + > + {triggerText} + )} {props.triggerSuffix} {selectedModel?.isUnavailable && !selectedEntries && props.triggerLabel === undefined ? ( diff --git a/apps/web/src/components/chat/ProviderStatusBanner.tsx b/apps/web/src/components/chat/ProviderStatusBanner.tsx index 6de02124aa0c9..c2119479d397e 100644 --- a/apps/web/src/components/chat/ProviderStatusBanner.tsx +++ b/apps/web/src/components/chat/ProviderStatusBanner.tsx @@ -11,10 +11,10 @@ import { Alert, AlertAction, AlertDescription, AlertTitle } from "../ui/alert"; import { Button, InlineButton } from "../ui/button"; import { m, type MessageResolver } from "../../i18n/messages"; import { formatProviderDriverKindLabel } from "../../providerModels"; -import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { serverEnvironment } from "../../state/server"; import { useAtomCommand } from "../../state/use-atom-command"; import { RefreshIcon } from "../ui/refresh-icon"; +import { SharedTooltipTrigger } from "../ui/shared-tooltip"; function getIncompatibleVersion(status: ServerProvider) { const compatibility = status.compatibilityAdvisory; @@ -204,12 +204,13 @@ export const ProviderStatusBanner = memo(function ProviderStatusBanner({ {title}
    - - }>{message} - - {message} - - + } + label={message} + className="whitespace-pre-wrap" + > + {message} +
    {onOpenProviderSetup && hasProviderSetup(status) ? ( onOpenProviderSetup(status.instanceId)}> diff --git a/apps/web/src/components/chat/QueuedRunsControl.tsx b/apps/web/src/components/chat/QueuedRunsControl.tsx index 20ea71f88adcd..c01fd90e5c22e 100644 --- a/apps/web/src/components/chat/QueuedRunsControl.tsx +++ b/apps/web/src/components/chat/QueuedRunsControl.tsx @@ -46,6 +46,7 @@ import { Button, InlineButton } from "../ui/button"; import { toastManager } from "../ui/toast"; import { m } from "../../i18n/messages"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; +import { SharedTooltipTrigger } from "../ui/shared-tooltip"; import type { TimestampFormat } from "@t3tools/contracts/settings"; import { GuestMessageName } from "./guestMessageStyle"; import { TimelineRowTimestamp } from "./TimelineRowParts"; @@ -305,24 +306,10 @@ export function QueuedRunsControl({ > {canSendRun(item.freshContext) && !isEditing ? ( <> - - }> - - - - {item.serverIndex === 0 && props.steerShortcutLabel + } + label={ + item.serverIndex === 0 && props.steerShortcutLabel ? workflow?.canSendNow ? gt("Start a turn with this message ({shortcut})", { shortcut: props.steerShortcutLabel, @@ -344,9 +331,23 @@ export function QueuedRunsControl({ ? gt("Skip compaction and send this message") : movesCommandFirst ? gt("Move this command to the front of the queue") - : gt("Send into the current turn")} - - + : gt("Send into the current turn") + } + > + + ) : null} {item.pending ? ( @@ -407,26 +408,26 @@ export function QueuedRunsControl({ : gt("Edit in the composer"))} - - { - if (item.runId !== null) void remove(item.runId); - }} - /> - } - > - - - - Remove from queue - - + { + if (item.runId !== null) void remove(item.runId); + }} + /> + } + label={ + <> + Remove from queue + + } + > + + )} diff --git a/apps/web/src/components/chat/SideThreadPane.tsx b/apps/web/src/components/chat/SideThreadPane.tsx index 516103c5415f0..701986930a475 100644 --- a/apps/web/src/components/chat/SideThreadPane.tsx +++ b/apps/web/src/components/chat/SideThreadPane.tsx @@ -37,9 +37,9 @@ import { useAtomCommand } from "../../state/use-atom-command"; import ChatView from "../ChatView"; import { Button } from "../ui/button"; import { toastManager } from "../ui/toast"; -import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { BackgroundThreadContext } from "./backgroundThread"; import { closeThreadFindIn } from "./threadFindStore"; +import { SharedTooltipTrigger } from "../ui/shared-tooltip"; /** * A side chat or a subagent as a tab: the thread's own chat, which decides its bottom, the @@ -160,25 +160,24 @@ export default function SideThreadPane(props: { {isSideChat ? (

    {title}

    - - - Add to chat - - } - /> - - {canAddToChat + + Add to chat + + } + label={ + canAddToChat ? gt("Adds this side chat to the main thread's next message.") - : gt("Available after the first message.")} - - + : gt("Available after the first message.") + } + side="bottom" + />
    diff --git a/apps/web/src/components/chat/ThreadLineageWorkflowRow.tsx b/apps/web/src/components/chat/ThreadLineageWorkflowRow.tsx index 5f47073bb965b..227aa4b95d1c9 100644 --- a/apps/web/src/components/chat/ThreadLineageWorkflowRow.tsx +++ b/apps/web/src/components/chat/ThreadLineageWorkflowRow.tsx @@ -18,7 +18,8 @@ import type { ProviderInstanceEntry } from "../../providerInstances"; import { cn } from "../../lib/utils"; import { ThreadDetailsControl } from "./ThreadDetailsControl"; import { CollapsibleSectionHeader, SectionHeaderStatus } from "../ui/collapsible-section-header"; -import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; +import { Tooltip, TooltipTrigger } from "../ui/tooltip"; +import { SharedTooltipTrigger } from "../ui/shared-tooltip"; import { Spinner } from "../ui/spinner"; import { THREAD_DETAILS_PANEL_SPLIT_GROUP_CLASS, @@ -167,30 +168,31 @@ export function ThreadLineageWorkflowRow({ {header} {onStop ? (
    - - - } - > - {stopping ? ( - - ) : ( - - )} - - - Stop entire workflow - - + + } + label={ + <> + Stop entire workflow + + } + side="left" + > + {stopping ? ( + + ) : ( + + )} +
    ) : null}
  • diff --git a/apps/web/src/components/chat/ThreadServersPanel.tsx b/apps/web/src/components/chat/ThreadServersPanel.tsx index e71a6be549a42..76ad23a9b7cf3 100644 --- a/apps/web/src/components/chat/ThreadServersPanel.tsx +++ b/apps/web/src/components/chat/ThreadServersPanel.tsx @@ -42,6 +42,7 @@ import { openDiscoveredPort } from "../preview/openDiscoveredPort"; import { Spinner } from "../ui/spinner"; import { stackedThreadToast, toastManager } from "../ui/toast"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; +import { SharedTooltipTrigger } from "../ui/shared-tooltip"; import { ThreadDetailsControl } from "./ThreadDetailsControl"; import { ThreadDetailsSection } from "./ThreadDetailsSection"; import { THREAD_DETAILS_PANEL_ICON_CLASS } from "./threadDetailsPanelStyles"; @@ -251,72 +252,72 @@ function ThreadServersList(props: ThreadServersPanelProps) { )} > {canForward ? ( - - void toggleForward(server, forward !== undefined)} - /> - } - > - {forwardingPort === server.port ? ( - - ) : ( - - )} - - - {forward ? ( + void toggleForward(server, forward !== undefined)} + /> + } + label={ + forward ? ( Forwarded to localhost:{forward.localPort} on this machine. Click to stop. ) : ( Forward to this machine, for any app here - )} - - + ) + } + side="left" + > + {forwardingPort === server.port ? ( + + ) : ( + + )} + ) : null} {stoppable ? ( - - void stop(server)} - /> - } - > - {stoppingKey === key ? ( - - ) : ( - - )} - - - Stop server - - + void stop(server)} + /> + } + label={ + <> + Stop server + + } + side="left" + > + {stoppingKey === key ? ( + + ) : ( + + )} + ) : null}
    ) : null} diff --git a/apps/web/src/components/chat/TimelineAssistantRows.tsx b/apps/web/src/components/chat/TimelineAssistantRows.tsx index 9692bbedad62a..4917c17b67cfe 100644 --- a/apps/web/src/components/chat/TimelineAssistantRows.tsx +++ b/apps/web/src/components/chat/TimelineAssistantRows.tsx @@ -17,13 +17,13 @@ import { readResponseSubagents, useAssistantMessageText } from "../../state/enti import { MessageCopyButton } from "./MessageCopyButton"; import { AssistantCitationSource } from "./AssistantCitationSource"; import { resolveAssistantMessageCopyState } from "./MessagesTimeline.logic"; -import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { cn } from "~/lib/utils"; import { formatChatTimestampTooltip, formatDayAwareTimestamp } from "../../timestampFormat"; import { readThreadTurnItems } from "../../state/entities"; import { useV2ItemSupport } from "../../state/v2ItemSupport"; import { TimelineRowCtx, TimelineRowActivityCtx, type TimelineRow } from "./timelineRowContext"; import { MESSAGE_HEADING_LEVEL, MessageAuthorHeading } from "./TimelineRowParts"; +import { SharedTooltipTrigger } from "../ui/shared-tooltip"; export function AssistantTimelineRow({ row }: { row: Extract }) { const ctx = use(TimelineRowCtx); @@ -146,30 +146,30 @@ function AssistantForkButton({ const runId = projectedItem.item.runId; return ( - - { - setBusy(true); - void onForkFromRun({ sourceThreadId: projectedItem.sourceThreadId, runId }).finally( - () => setBusy(false), - ); - }} - aria-label={gt("Fork from this response")} - /> - } - > - - - - Fork from this response - - + { + setBusy(true); + void onForkFromRun({ sourceThreadId: projectedItem.sourceThreadId, runId }).finally( + () => setBusy(false), + ); + }} + aria-label={gt("Fork from this response")} + /> + } + label={ + <> + Fork from this response + + } + > + + ); } @@ -235,20 +235,12 @@ function AssistantMessageMeta({ ) : null} {!message.streaming && ( - - }> - {formatDayAwareTimestamp( - message.updatedAt, - ctx.timestampFormat, - undefined, - undefined, - m, - )} - - - {formatChatTimestampTooltip(message.updatedAt, ctx.timestampFormat, m)} - - + } + label={formatChatTimestampTooltip(message.updatedAt, ctx.timestampFormat, m)} + > + {formatDayAwareTimestamp(message.updatedAt, ctx.timestampFormat, undefined, undefined, m)} + )}
    ); @@ -282,24 +274,24 @@ function AssistantReplyButton({ message, itemId }: { message: ChatMessage; itemI }; return ( - - - } - > - - - - Reply to this response - - + + } + label={ + <> + Reply to this response + + } + > + + ); } diff --git a/apps/web/src/components/chat/TimelineRowParts.tsx b/apps/web/src/components/chat/TimelineRowParts.tsx index 1c496680c7293..0290dd185a265 100644 --- a/apps/web/src/components/chat/TimelineRowParts.tsx +++ b/apps/web/src/components/chat/TimelineRowParts.tsx @@ -1,9 +1,9 @@ import { useMessages } from "gt-react"; import { type ReactNode } from "react"; -import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { cn } from "~/lib/utils"; import { type TimestampFormat } from "@t3tools/contracts/settings"; import { formatChatTimestampTooltip, formatDayAwareTimestamp } from "../../timestampFormat"; +import { SharedTooltipTrigger } from "../ui/shared-tooltip"; export const MESSAGE_HEADING_LEVEL = 3; @@ -24,22 +24,20 @@ export function TimelineRowTimestamp({ }) { const m = useMessages(); return ( - - - } - > - {formatDayAwareTimestamp(createdAt, timestampFormat, undefined, undefined, m)} - - {formatChatTimestampTooltip(createdAt, timestampFormat, m)} - + + } + label={formatChatTimestampTooltip(createdAt, timestampFormat, m)} + > + {formatDayAwareTimestamp(createdAt, timestampFormat, undefined, undefined, m)} + ); } diff --git a/apps/web/src/components/chat/TimelineSystemDivider.tsx b/apps/web/src/components/chat/TimelineSystemDivider.tsx index cb0489998f04a..d9d2801780e60 100644 --- a/apps/web/src/components/chat/TimelineSystemDivider.tsx +++ b/apps/web/src/components/chat/TimelineSystemDivider.tsx @@ -2,7 +2,7 @@ import type { ReactNode } from "react"; import type { LucideIcon } from "lucide-react"; import { cn } from "~/lib/utils"; -import { Tooltip, TooltipPopup, TooltipTrigger } from "~/components/ui/tooltip"; +import { SharedTooltipTrigger } from "~/components/ui/shared-tooltip"; export function TimelineSystemDivider(props: { readonly label: string; @@ -51,24 +51,22 @@ export function TimelineSystemDivider(props: { > + } + label={ + <> + {entry?.displayName ?? props.instanceId} · {label} + + } + /> ); } diff --git a/apps/web/src/components/chat/VoiceInputErrorPill.tsx b/apps/web/src/components/chat/VoiceInputErrorPill.tsx index a2f0387146716..cd5571ee5e0db 100644 --- a/apps/web/src/components/chat/VoiceInputErrorPill.tsx +++ b/apps/web/src/components/chat/VoiceInputErrorPill.tsx @@ -4,8 +4,8 @@ import { useNavigate } from "@tanstack/react-router"; import { CircleAlertIcon, XIcon } from "lucide-react"; import { Button } from "../ui/button"; -import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { VoiceInputPill } from "./VoiceInputPill"; +import { SharedTooltipTrigger } from "../ui/shared-tooltip"; const VOICE_ERROR_LABELS: Readonly> = { "microphone-blocked": msg("Mic blocked"), @@ -51,44 +51,40 @@ export function VoiceInputErrorPill(props: { : { label: gt("Record again"), text: gt("Record again") }; return ( - - event.preventDefault()} - onClick={props.onDismiss} - className="shrink-0" - > - - - } - /> - - {props.cancelShortcutLabel + event.preventDefault()} + onClick={props.onDismiss} + className="shrink-0" + > + + + } + label={ + props.cancelShortcutLabel ? gt("Dismiss ({shortcut})", { shortcut: props.cancelShortcutLabel }) - : gt("Dismiss")} - - - - - } - > - - {errorLabel ? m(errorLabel) : gt("Voice input failed")} - - {message} - + : gt("Dismiss") + } + /> + + } + label={message} + > + + {errorLabel ? m(errorLabel) : gt("Voice input failed")} + {props.errorAction ? ( - - {unsupportedDetail ?? gt("Client not supported")} - + } + label={unsupportedDetail ?? gt("Client not supported")} + > + + ) : savedConnection ? ( - ) : ( - - {props.children} - - ) - } - /> - {props.label} - + + {props.children} + + ) : ( + + {props.children} + + ) + } + label={props.label} + /> ); } diff --git a/apps/web/src/components/files/office/WordDocument.tsx b/apps/web/src/components/files/office/WordDocument.tsx index edebcb6f63337..dae5764a04683 100644 --- a/apps/web/src/components/files/office/WordDocument.tsx +++ b/apps/web/src/components/files/office/WordDocument.tsx @@ -1,6 +1,5 @@ /* oxlint-disable react/no-array-index-key -- Text spans retain their order within an immutable page. */ /* oxlint-disable react/no-unstable-nested-components -- These callbacks return overlays, and are invoked as render functions. */ -import { Tooltip, TooltipTrigger, TooltipPopup } from "~/components/ui/tooltip"; import { msg } from "gt-react"; import { Fragment, useEffect, useRef, useState } from "react"; import { m } from "~/i18n/messages"; @@ -16,6 +15,7 @@ import { type WordSpan, type WordLink, } from "./word-protocol"; +import { SharedTooltipTrigger } from "~/components/ui/shared-tooltip"; type Opened = { pages: readonly WordPageSize[]; @@ -201,14 +201,7 @@ function WordTextLayer(props: { ); return ( - {span.title ? ( - - - {span.title} - - ) : ( - text - )} + {span.title ? : text} {span.after === "br" ?
    : span.after === "tab" ? "\t" : null}
    ); diff --git a/apps/web/src/components/issue/IssueThreadLinks.tsx b/apps/web/src/components/issue/IssueThreadLinks.tsx index e9d54ba19a7bf..354d13ae07585 100644 --- a/apps/web/src/components/issue/IssueThreadLinks.tsx +++ b/apps/web/src/components/issue/IssueThreadLinks.tsx @@ -33,7 +33,7 @@ import { ThreadLinkPicker } from "../ThreadLinkPicker"; import { Button } from "../ui/button"; import { Dialog, DialogPopup, DialogTitle } from "../ui/dialog"; import { toastManager } from "../ui/toast"; -import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; +import { SharedTooltipTrigger } from "../ui/shared-tooltip"; /** * The threads an issue is linked to, and the control that links it to one more: the thread it is @@ -129,65 +129,59 @@ export function IssueThreadLinks({ return ( <> {linkedThreads.length > 0 || (!relationsKnown && relations.error !== null) ? ( - - - openCommandPalette({ - query: issue.url, - ...(relationsKnown - ? { linkedThreads: { environmentId, threads: linkedThreads } } - : {}), - }) - } - > - - {linkedThreads.length || "?"} - - } - /> - - {gt("{label}. Search in the command palette.", { label: linkedThreadsLabel })} - - + + openCommandPalette({ + query: issue.url, + ...(relationsKnown + ? { linkedThreads: { environmentId, threads: linkedThreads } } + : {}), + }) + } + > + + {linkedThreads.length || "?"} + + } + label={gt("{label}. Search in the command palette.", { label: linkedThreadsLabel })} + /> ) : null} {canOperate ? ( - - { - if (thread === null) setPickerOpen(true); - else void changeLink(thread.id, linkedHere); - }} - /> - } - > - {linkedHere ? ( - - ) : ( - - )} - - - {linkedHere ? ( + { + if (thread === null) setPickerOpen(true); + else void changeLink(thread.id, linkedHere); + }} + /> + } + label={ + linkedHere ? ( Unlink from this thread ) : thread === null ? ( gt("Link to thread") ) : ( Link to this thread - )} - - + ) + } + > + {linkedHere ? ( + + ) : ( + + )} + ) : null} {pickerOpen ? ( diff --git a/apps/web/src/components/onboarding/WelcomePage.tsx b/apps/web/src/components/onboarding/WelcomePage.tsx index 5c1b4218117fc..a5a46efb19d17 100644 --- a/apps/web/src/components/onboarding/WelcomePage.tsx +++ b/apps/web/src/components/onboarding/WelcomePage.tsx @@ -109,13 +109,13 @@ import { Button } from "../ui/button"; import { Checkbox } from "../ui/checkbox"; import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from "../ui/collapsible"; import { QRCodeSvg } from "../ui/qr-code"; -import { Tooltip, TooltipTrigger, TooltipPopup } from "../ui/tooltip"; import { ScrollArea } from "../ui/scroll-area"; import { SidebarInset } from "../ui/sidebar"; import { toastManager } from "../ui/toast"; import { WorkspacePageHeader } from "../WorkspacePageHeader"; import { cn } from "../../lib/utils"; import { formatRelativeTime } from "../../timestampFormat"; +import { SharedTooltipTrigger } from "../ui/shared-tooltip"; const AGENT_ONBOARDING_THREAD_ID = ThreadId.make("onboarding-agent-setup"); const SCAN_LIMIT_MESSAGE = msg( @@ -1922,22 +1922,19 @@ function ImportCandidateRow({ )} > onCheckedChange(value === true)} /> - - } - > - {label !== undefined ? ( - {label} - ) : null} - {path !== undefined ? ( - - ) : null} - - {candidate.path} - + } + label={candidate.path} + variant="code" + > + {label !== undefined ? {label} : null} + {path !== undefined ? ( + + ) : null} +
    - - - } - > - - - - Back - - - - - } - > - - - - Forward - - - - - } - > - - - - {loading ? gt("Stop", { $context: "stop loading the page" }) : gt("Refresh")} - - + + } + label={ + <> + Back + + } + > + + + + } + label={ + <> + Forward + + } + > + + + + } + label={loading ? gt("Stop", { $context: "stop loading the page" }) : gt("Refresh")} + > + +
    {leadingActions} @@ -206,103 +203,93 @@ export function PreviewChromeRow({ {} - - - } - > - - - - Open in system browser - - + + } + label={ + <> + Open in system browser + + } + > + + ) : null} {onPickElement ? ( - - - } - > - - - - {pickDisabled && pickDisabledReason + + } + label={ + pickDisabled && pickDisabledReason ? pickDisabledReason : pickActive ? gt("Cancel annotation (Esc)") - : gt("Annotate elements, regions, and drawings")} - - + : gt("Annotate elements, regions, and drawings") + } + > + +
    ) : null} {onCapture ? ( - - onCapture(event.shiftKey)} - aria-label={recording ? gt("Stop recording") : gt("Capture screenshot")} - type="button" - className="relative" - disabled={captureDisabled} - /> - } - > - - {recording ? ( - - ) : null} - - - {recording ? gt("Stop recording") : gt("Screenshot · Shift-click to record")} - - + onCapture(event.shiftKey)} + aria-label={recording ? gt("Stop recording") : gt("Capture screenshot")} + type="button" + className="relative" + disabled={captureDisabled} + /> + } + label={recording ? gt("Stop recording") : gt("Screenshot · Shift-click to record")} + > + + {recording ? ( + + ) : null} + ) : null} {onPictureInPicture ? ( - - - } - > - - - - {pictureInPicture ? gt("Close floating preview") : gt("Float preview over chat")} - - + + } + label={pictureInPicture ? gt("Close floating preview") : gt("Float preview over chat")} + > + + ) : null} {trailingActions} diff --git a/apps/web/src/components/preview/PreviewMoreMenu.tsx b/apps/web/src/components/preview/PreviewMoreMenu.tsx index c4fabfa97d6df..89d3d13f4f263 100644 --- a/apps/web/src/components/preview/PreviewMoreMenu.tsx +++ b/apps/web/src/components/preview/PreviewMoreMenu.tsx @@ -18,7 +18,7 @@ import { MenuSubTrigger, MenuTrigger, } from "~/components/ui/menu"; -import { Tooltip, TooltipPopup, TooltipTrigger } from "~/components/ui/tooltip"; +import { SharedTooltipTrigger } from "~/components/ui/shared-tooltip"; const COLOR_SCHEME_OPTIONS: ReadonlyArray<{ value: DesktopPreviewColorScheme; @@ -58,27 +58,22 @@ interface Props { const MenuTriggerButton = () => { const gt = useGT(); return ( - - - } - /> - } - > - - - - More - - + + } + /> + } + label={ + <> + More + + } + > + + ); }; diff --git a/apps/web/src/components/preview/PreviewView.tsx b/apps/web/src/components/preview/PreviewView.tsx index bb62228b93736..84fd733275d93 100644 --- a/apps/web/src/components/preview/PreviewView.tsx +++ b/apps/web/src/components/preview/PreviewView.tsx @@ -111,8 +111,8 @@ import { useActiveBrowserRecordingTabIds, } from "~/browser/browserRecording"; import { stackedThreadToast, toastManager } from "~/components/ui/toast"; -import { Tooltip, TooltipPopup, TooltipTrigger } from "~/components/ui/tooltip"; import { observeResize } from "~/lib/observeResize"; +import { SharedTooltipTrigger } from "~/components/ui/shared-tooltip"; interface Props { threadRef: ScopedThreadRef; @@ -1039,12 +1039,12 @@ export function PreviewView({ } leadingActions={ activeProfileId !== browserDefaults.profileId ? ( - - }> - {activeProfileName} - - {activeProfileName} - + } + label={activeProfileName} + > + {activeProfileName} + ) : null } trailingActions={ diff --git a/apps/web/src/components/preview/ThreadPreviewMiniPlayer.tsx b/apps/web/src/components/preview/ThreadPreviewMiniPlayer.tsx index 989f283ad083b..5e0fb3d762abc 100644 --- a/apps/web/src/components/preview/ThreadPreviewMiniPlayer.tsx +++ b/apps/web/src/components/preview/ThreadPreviewMiniPlayer.tsx @@ -40,7 +40,6 @@ import { import { useBrowserLayoutZoomFactor } from "~/browser/useBrowserLayoutZoomFactor"; import { Button } from "~/components/ui/button"; import { toastManager } from "~/components/ui/toast"; -import { Tooltip, TooltipPopup, TooltipTrigger } from "~/components/ui/tooltip"; import { cn } from "~/lib/utils"; import { useThreadPreviewState } from "~/previewStateStore"; import { @@ -75,6 +74,7 @@ import { resolveDeviceMiniPlayerSourceSize, resolvePreviewMiniPlayerSourceSize, } from "./previewMiniPlayerLayout"; +import { SharedTooltipTrigger } from "~/components/ui/shared-tooltip"; interface Props { readonly threadRef: ScopedThreadRef; @@ -291,29 +291,25 @@ function BrowserMiniPlayer({ threadRef, tabId, miniPlayer }: Props & { readonly onOpenInPanel={openInPanel} pillActions={ canPopOut ? ( - - event.stopPropagation()} - onClick={toggleNativePictureInPicture} - /> - } - > - - - - {poppedOut ? gt("Close separate window") : gt("Pop into separate window")} - - + event.stopPropagation()} + onClick={toggleNativePictureInPicture} + /> + } + label={poppedOut ? gt("Close separate window") : gt("Pop into separate window")} + > + + ) : null } > @@ -647,43 +643,43 @@ function MiniPlayerShell({ ) : null} - - event.stopPropagation()} - onClick={onOpenInPanel} - /> - } - > - - - - Open in right panel - - + event.stopPropagation()} + onClick={onOpenInPanel} + /> + } + label={ + <> + Open in right panel + + } + > + + {pillActions} - - event.stopPropagation()} - onClick={close} - /> - } - > - - - - Close floating preview - - + event.stopPropagation()} + onClick={close} + /> + } + label={ + <> + Close floating preview + + } + > + + diff --git a/apps/web/src/components/pullRequest/PullRequestActionsMenu.tsx b/apps/web/src/components/pullRequest/PullRequestActionsMenu.tsx index a6b23ded9b928..7b048f7519498 100644 --- a/apps/web/src/components/pullRequest/PullRequestActionsMenu.tsx +++ b/apps/web/src/components/pullRequest/PullRequestActionsMenu.tsx @@ -50,7 +50,6 @@ import { } from "../ui/menu"; import { RefreshIcon } from "../ui/refresh-icon"; import { toastManager } from "../ui/toast"; -import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { ActOnEnvironmentPicker, type PerformPullRequestAction } from "./PullRequestDetailActions"; import { PULL_REQUEST_MERGE_METHOD_LABELS, @@ -63,6 +62,7 @@ import { PullRequestThreadLinks } from "./PullRequestThreadLinks"; import { useInlineActionConfirm } from "./useInlineActionConfirm"; import { changeRequestTermKind } from "./changeRequestTerm"; +import { SharedTooltipTrigger } from "../ui/shared-tooltip"; /** Everything else the reader can do with the pull request, behind the header's overflow button. */ export function PullRequestActionsMenu({ @@ -213,38 +213,36 @@ export function PullRequestActionsMenu({ }; return (
    - - - } - > - {refreshing ? ( - - ) : ( - - )} - - } - /> - - {refreshing + + } + > + {refreshing ? ( + + ) : ( + + )} + + } + label={ + refreshing ? gt( "Refreshing {term, select, mr {merge request} cr {change request} other {pull request}}", { term: changeRequestTermKind(terminology) }, @@ -252,9 +250,9 @@ export function PullRequestActionsMenu({ : gt( "More {term, select, mr {merge request} cr {change request} other {pull request}} actions", { term: changeRequestTermKind(terminology) }, - )} - - + ) + } + /> ({ icon, @@ -58,16 +58,15 @@ export function PullRequestCandidatePicker({ }) { if (!allowed) { return ( - - - {icon} - - } - /> - {disabledReason} - + + {icon} + + } + label={disabledReason} + side="bottom" + /> ); } diff --git a/apps/web/src/components/pullRequest/PullRequestChecksPopover.tsx b/apps/web/src/components/pullRequest/PullRequestChecksPopover.tsx index 213848cc0ebfe..64c9cffa982d6 100644 --- a/apps/web/src/components/pullRequest/PullRequestChecksPopover.tsx +++ b/apps/web/src/components/pullRequest/PullRequestChecksPopover.tsx @@ -18,7 +18,6 @@ import { useEnvironmentQuery } from "~/state/query"; import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover"; import { Button } from "../ui/button"; import { ScrollArea } from "../ui/scroll-area"; -import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { toastManager } from "../ui/toast"; import { groupPullRequestChecks } from "./pullRequestDetail.logic"; import { @@ -28,6 +27,7 @@ import { pullRequestChecksStatePresentation, summarizePullRequestChecks, } from "./pullRequestPresentation"; +import { SharedTooltipTrigger } from "../ui/shared-tooltip"; // Fetch only on open to avoid per-row requests. function LazyChecksBody({ @@ -97,10 +97,10 @@ function ChecksBody({ className="col-span-full grid grid-cols-subgrid items-center text-xs" > - - {check.name}} /> - {check.description ?? check.name} - + {check.name}} + label={check.description ?? check.name} + /> {pullRequestCheckStatusLabel(check, resolve)} diff --git a/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx b/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx index d3c7af4841c50..1ffe0db520237 100644 --- a/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx +++ b/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx @@ -135,7 +135,6 @@ import { } from "../ui/menu"; import { toastManager } from "../ui/toast"; import { Toggle, ToggleGroup } from "../ui/toggle-group"; -import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { getReviewPositionAnchor, InlineReviewThreads, @@ -159,6 +158,7 @@ import { } from "./pullRequestReviewStore"; import { changeRequestTermKind } from "./changeRequestTerm"; +import { SharedTooltipTrigger } from "../ui/shared-tooltip"; interface ReviewAnnotationGroup { readonly threads: ReadonlyArray; @@ -352,14 +352,17 @@ function FileViewedToggle({ } /> {stale ? ( - - }> - Changed - - - This file has been pushed to since you marked it viewed. - - + } + label={ + <> + This file has been pushed to since you marked it viewed. + + } + side="bottom" + > + Changed + ) : ( Viewed @@ -1491,12 +1494,10 @@ function PullRequestCodeTab({ {orderedCommits.slice(0, visibleCommitCount).map((entry) => ( - - {entry.messageHeadline}} - /> - {entry.messageHeadline} - + {entry.messageHeadline}} + label={entry.messageHeadline} + /> {entry.oid.slice(0, 7)} @@ -1555,107 +1556,123 @@ function PullRequestCodeTab({ : gt("viewed", { $context: "files marked as viewed" })} {viewedFilesStore === "environment" ? ( - - }> - - - - - This host keeps no shared record of which files you have read, so these ticks - are kept by this environment. They follow you between the apps connected to - it, but the host's own web UI will not show them. - - - + } + label={ + <> + + This host keeps no shared record of which files you have read, so these + ticks are kept by this environment. They follow you between the apps + connected to it, but the host's own web UI will not show them. + + + } + side="bottom" + > + + ) : null} {filesViewed.error !== null ? ( - - }> - - - - - The boxes below are whatever was last read, and empty if nothing has been read - yet. {filesViewed.error} - - - + } + label={ + <> + + The boxes below are whatever was last read, and empty if nothing has been + read yet. {filesViewed.error} + + + } + side="bottom" + > + + ) : null} {filesViewed.truncated ? ( - - }> - - - - - This change has more files than the host will report ticks for in one read, so - the count is short and some boxes below start empty. - - - + } + label={ + <> + + This change has more files than the host will report ticks for in one read, + so the count is short and some boxes below start empty. + + + } + side="bottom" + > + + ) : null} ) : null} {withheldContent ? ( - - }> - - - - - The host withheld part of this diff: a binary file, or a change too large to - inline. - - - + } + label={ + <> + + The host withheld part of this diff: a binary file, or a change too large to + inline. + + + } + side="bottom" + > + + ) : null} {commit !== null && review.inlineComment ? ( - - }> - - - - - A comment is anchored to the whole change, so switch to All commits to write one. - - - + } + label={ + <> + + A comment is anchored to the whole change, so switch to All commits to write + one. + + + } + side="bottom" + > + + ) : null}
    - - } - className="@lg:hidden" - aria-label={gt("Diff options")} - /> - } - > - - - - Diff options - - + } + className="@lg:hidden" + aria-label={gt("Diff options")} + /> + } + label={ + <> + Diff options + + } + > + +
    - - changeIgnoreWhitespace(Boolean(pressed))} - /> - } - > - - - - {ignoreWhitespace ? gt("Show whitespace changes") : gt("Hide whitespace changes")} - - + changeIgnoreWhitespace(Boolean(pressed))} + /> + } + label={ignoreWhitespace ? gt("Show whitespace changes") : gt("Hide whitespace changes")} + > + + - - { - setWordWrapOverride(Boolean(pressed)); - }} - /> - } - > - - - - {wordWrap ? gt("Disable line wrapping") : gt("Enable line wrapping")} - - + { + setWordWrapOverride(Boolean(pressed)); + }} + /> + } + label={wordWrap ? gt("Disable line wrapping") : gt("Enable line wrapping")} + > + +
    {fileKeys.length > 0 ? ( - - - } - > - {allFilesCollapsed ? ( - - ) : ( - - )} - - - {allFilesCollapsed ? gt("Expand all files") : gt("Collapse all files")} - - + + } + label={allFilesCollapsed ? gt("Expand all files") : gt("Collapse all files")} + > + {allFilesCollapsed ? ( + + ) : ( + + )} + ) : null} {testFileCount > 0 ? ( - - setHideTestFiles(Boolean(pressed))} - /> - } - > - - - - {hideTestFiles ? gt("Show test files") : gt("Hide test files")} - - + setHideTestFiles(Boolean(pressed))} + /> + } + label={hideTestFiles ? gt("Show test files") : gt("Hide test files")} + > + + ) : null} {fileKeys.length > 0 ? ( - - setFileTreeOpen(Boolean(pressed))} - /> - } - > - - - - {fileTreeOpen ? gt("Hide file tree") : gt("Show file tree")} - - + setFileTreeOpen(Boolean(pressed))} + /> + } + label={fileTreeOpen ? gt("Hide file tree") : gt("Show file tree")} + > + + ) : null}
    @@ -1997,14 +1994,10 @@ function PullRequestCodeTab({
    {[...orphanFiles].map(([path, threads]) => (
    - - {path}

    - } - /> - {path} -
    + {path}

    } + label={path} + />
    {threads.map((thread) => (
    diff --git a/apps/web/src/components/pullRequest/PullRequestCompactFilterMenu.tsx b/apps/web/src/components/pullRequest/PullRequestCompactFilterMenu.tsx index 47e1de807f0ce..173e72906289c 100644 --- a/apps/web/src/components/pullRequest/PullRequestCompactFilterMenu.tsx +++ b/apps/web/src/components/pullRequest/PullRequestCompactFilterMenu.tsx @@ -5,11 +5,11 @@ import type { ReactNode } from "react"; import { cn } from "~/lib/utils"; import { Button } from "../ui/button"; import { Menu, MenuPopup, MenuRadioGroup, MenuRadioItem, MenuTrigger } from "../ui/menu"; -import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { PullRequestFilterOptionIcon, type PullRequestFilterOption, } from "./PullRequestListFilters"; +import { SharedTooltipTrigger } from "../ui/shared-tooltip"; export function PullRequestCompactFilterMenu({ label, @@ -84,10 +84,12 @@ export function PullRequestCompactFilterMenu({ return option.unavailable === undefined ? ( item ) : ( - - - {option.unavailable} - + ); })} diff --git a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx index 1a6d4bbb5d8f8..5b9e8dc857094 100644 --- a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx +++ b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx @@ -87,7 +87,6 @@ import { useUiStateStore } from "~/uiStateStore"; import { Alert, AlertAction, AlertDescription } from "../ui/alert"; import { Button } from "../ui/button"; import { toastManager } from "../ui/toast"; -import { Tooltip, TooltipPopup, TooltipProvider, TooltipTrigger } from "../ui/tooltip"; import { MiddleTruncate } from "../ui/middle-truncate"; import { PullRequestChecksStatusLine, @@ -98,7 +97,7 @@ import { import { PullRequestDetailGhost, PullRequestTimelineGhost } from "./PullRequestGhosts"; import { PullRequestCopyableCode } from "./PullRequestCopyableCode"; import { useStableCallback } from "~/hooks/useStableCallback"; -import { SharedTooltipProvider } from "../ui/shared-tooltip"; +import { SharedTooltipTrigger } from "../ui/shared-tooltip"; import { internPullRequestReference, pullRequestRefKey, @@ -1589,12 +1588,12 @@ export function PullRequestDetailPanel({ {...(onClose ? { onClose } : {})} actions={ handoffSummary ? ( - + <> {handoffSummary.state === "open" && handoffSummary.mergeability === "conflicting" ? resolveConflictsControl : null} {checkoutControl} - + ) : undefined } /> @@ -1602,745 +1601,732 @@ export function PullRequestDetailPanel({ } return ( - // One tooltip for the panel's many triggers; mounting one per trigger dominated opening it. - -
    - {threadPickerOpen && detail ? ( - - ) : null} -
    - -
    - {detail ? ( - - {detail.visibility === "private" ? : null} - {context === "page" ? ( - - ) : null} - {!nativeStack && supportsStackActions && nativeStackQuery.error ? ( - - ) : null} - {nativeStack ? ( - 0 - } - canRebase={ - supportsStackActions && detail.viewerPermissions.stackRebase === true - } - canAutoMerge={ - stackAutoMerge && can("enable-auto-merge") && allowedMergeMethods.length > 0 - } - preferAutoMerge={checksState !== null && checksState !== "passing"} - autoMergeArmed={stackAutoMerge && autoMergeArmed} - canCancelAutoMerge={stackAutoMerge && can("disable-auto-merge")} - onActed={() => { - refreshDetail(); - onActed?.(); - }} - /> - ) : null} - - {checkoutControl} - + {threadPickerOpen && detail ? ( + + ) : null} +
    + +
    + {detail ? ( + <> + {detail.visibility === "private" ? : null} + {context === "page" ? ( + + ) : null} + {!nativeStack && supportsStackActions && nativeStackQuery.error ? ( + + ) : null} + {nativeStack ? ( + 0} + canRebase={supportsStackActions && detail.viewerPermissions.stackRebase === true} + canAutoMerge={ + stackAutoMerge && can("enable-auto-merge") && allowedMergeMethods.length > 0 } - onThreadPickerOpenChange={setThreadPickerOpen} - refreshing={refreshing} - refreshFromHost={refreshFromHost} - handoff={handoff} - attachesToComposer={attachTarget !== null} - askAboutPullRequest={askAboutPullRequest} - explainPullRequest={explainPullRequest} - canFixFindings={canFixFindings} - startFixFindings={startFixFindings} - handoffLabels={handoffLabels} - canWriteGuide={reviewGuidesEnabled && guideWriter.canWrite} - guideRunning={guideWriter.running} - guideWritten={guideWriter.data?.guide != null} - writeGuide={writeGuide} - pickableEnvironments={pickableEnvironments} - actingEnvironmentId={actingEnvironmentId} - onActingEnvironmentChange={selectActingEnvironment} - can={can} - autoMergeArmed={autoMergeArmed} - showsDraftToggle={showsDraftToggle} - showsMergeNow={showsMergeNow} - showsAutoMerge={showsAutoMerge} - showsMergeMethods={showsMergeMethods} - allowedMergeMethods={allowedMergeMethods} - selectedMergeMethod={selectedMergeMethod} - onSelectMergeMethod={selectMergeMethod} - showsDeleteBranch={showsDeleteBranch} - environmentConnected={environmentConnected} - canWriteSourceControl={canWriteSourceControl} - onMaintainerEditsSaved={refreshDetail} - confirmDeleteBranch={confirmDeleteBranch} - pendingAction={pendingAction} - perform={perform} - openOnHostText={openOnHostText} - copyReference={copyReference} + preferAutoMerge={checksState !== null && checksState !== "passing"} + autoMergeArmed={stackAutoMerge && autoMergeArmed} + canCancelAutoMerge={stackAutoMerge && can("disable-auto-merge")} + onActed={() => { + refreshDetail(); + onActed?.(); + }} /> - - ) : null} - {onClose ? ( - - ) : null} -
    - -
    -
    + {checkoutControl} + + + ) : null} + {onClose ? ( +
    -
    + + + ) : null} +
    +
    -
    - {detail ? ( - - } - author={ + {detail ? ( +
    +
    + - } - updated={ - - - updated{" "} - - - - + + - } - checkout={ - checkoutCommand ? ( - - ) : null - } - base={ + + + void perform("update-branch", undefined, method)} + iconClassName="size-3" /> - } - head={ - - } - files={gt("{count, plural, one {{formatted} file} other {{formatted} files}}", { - count: detail.changedFiles, - formatted: detail.changedFiles.toLocaleString(), - })} - diffStat={ + + + + } + label={detail.headBranch} + /> + + + + + {detail.changedFiles.toLocaleString()} + - } - /> - ) : null} -
    + +
    +
    + ) : null}
    +
    - {unseenHeadSha !== undefined && shownHeadSha !== undefined ? ( -
    - - - - {gt("New commits were pushed. A merge or review still applies to {sha}.", { - sha: shownHeadSha.slice(0, 7), - })} - - - - - -
    - ) : null} - {detail ? ( - { - if (item !== "code") return; - void loadCodeTab(); - setCodeIntentKey(pullRequestKey); - }} - > - {tab === "summary" ? ( - showsApproveWorkflows ? ( - +
    + {detail ? ( + - ) : ( - + } + updated={ + + + updated{" "} + + + + + + } + checkout={ + checkoutCommand ? ( + + ) : null + } + base={ + void perform("update-branch", undefined, method)} + /> + } + head={ + + } + files={gt("{count, plural, one {{formatted} file} other {{formatted} files}}", { + count: detail.changedFiles, + formatted: detail.changedFiles.toLocaleString(), + })} + diffStat={ + + } + /> + ) : null} +
    +
    + + {unseenHeadSha !== undefined && shownHeadSha !== undefined ? ( +
    + + + + {gt("New commits were pushed. A merge or review still applies to {sha}.", { + sha: shownHeadSha.slice(0, 7), + })} + + + + + +
    + ) : null} + {detail ? ( + { + if (item !== "code") return; + void loadCodeTab(); + setCodeIntentKey(pullRequestKey); + }} + > + {tab === "summary" ? ( + showsApproveWorkflows ? ( + + ) : ( + + ) : ( + + ) + } + label={checksSummary} + /> + ) + ) : tab === "timeline" ? ( +
    + + - ) : ( - - ) + > + + {activityError + ? "-" + : activityPending + ? "…" + : detail.commentCount.toLocaleString()} + + - ) - ) : tab === "timeline" ? ( -
    - + + {activityError + ? "-" + : activityPending + ? "…" + : detail.commits.length.toLocaleString()} + + {approvalCount > 0 ? ( - - {activityError - ? "-" - : activityPending - ? "…" - : detail.commentCount.toLocaleString()} - - - - {activityError - ? "-" - : activityPending - ? "…" - : detail.commits.length.toLocaleString()} - - {approvalCount > 0 ? ( - + {approvalCount.toLocaleString()} + + {gt( + "{count, plural, one {{formatted} approval} other {{formatted} approvals}}", + { count: approvalCount, formatted: approvalCount.toLocaleString() }, )} - > - - {approvalCount.toLocaleString()} - - {gt( - "{count, plural, one {{formatted} approval} other {{formatted} approvals}}", - { count: approvalCount, formatted: approvalCount.toLocaleString() }, - )} - - ) : null} - - -
    - ) : null} - - ) : null} -
    + + ) : null} + + +
    + ) : null} + + ) : null} +
    - -
    { - const scroller = scrollerByTab.current[tab]; - if (event.target !== scroller || scroller === null || scroller === undefined) return; - const top = scroller.scrollTop; - const previous = condensedByTab[tab] ?? false; - const foldHeight = foldRef.current?.scrollHeight ?? 0; - let next = previous; - if (previous) { - if (top < 4 && foldHeight > 0) next = false; - } else if (foldHeight > 0 && top > foldHeight + 32) { - const chromeDelta = foldHeight - (condensedRowRef.current?.scrollHeight ?? 0); - compensationRef.current = { tab, scroller, target: top - chromeDelta }; - next = true; - } - if (next === previous) return; - if (tab === "summary") summaryCondensedByScopeKey.set(tabScopeKey, next); - setCondensedByTab({ ...condensedByTab, [tab]: next }); - }} - > - {detailQuery.error && !detail ? ( - +
    { + const scroller = scrollerByTab.current[tab]; + if (event.target !== scroller || scroller === null || scroller === undefined) return; + const top = scroller.scrollTop; + const previous = condensedByTab[tab] ?? false; + const foldHeight = foldRef.current?.scrollHeight ?? 0; + let next = previous; + if (previous) { + if (top < 4 && foldHeight > 0) next = false; + } else if (foldHeight > 0 && top > foldHeight + 32) { + const chromeDelta = foldHeight - (condensedRowRef.current?.scrollHeight ?? 0); + compensationRef.current = { tab, scroller, target: top - chromeDelta }; + next = true; + } + if (next === previous) return; + if (tab === "summary") summaryCondensedByScopeKey.set(tabScopeKey, next); + setCondensedByTab({ ...condensedByTab, [tab]: next }); + }} + > + {detailQuery.error && !detail ? ( + + ) : detail ? ( + + {mountedTabs.has("summary") ? ( +
    + +
    + ) : null} + {mountedTabs.has("guide") ? ( +
    + + addSelectionToAgent({ comment, request }, { keepGuide: true }) } - : {})} - /> - ) : detail ? ( - - {mountedTabs.has("summary") ? ( -
    - + detail.viewerPermissions.verdicts.includes(verdict), + ) + ? () => setOpenReviewRequest((count) => count + 1) + : null + } + onOpenFile={openFileInCode} + onTourShown={onGuideShown} + /> +
    + ) : null} + {mountedTabs.has("timeline") ? ( +
    + {activityPending ? ( +
    + +
    + ) : activityError ? ( + + ) : ( + -
    - ) : null} - {mountedTabs.has("guide") ? ( -
    + ) : null} + {mountedTabs.has("code") ? ( +
    + + +
    + } > - - addSelectionToAgent({ comment, request }, { keepGuide: true }) - } - onAskAboutStop={askAboutGuideStop} - onFinishReview={ - detail.capabilities.review.verdicts.some((verdict) => - detail.viewerPermissions.verdicts.includes(verdict), - ) - ? () => setOpenReviewRequest((count) => count + 1) - : null - } - onOpenFile={openFileInCode} - onTourShown={onGuideShown} + detail={detail} + selectedCommitOid={selectedCodeCommitOid} + onSelectedCommitChange={selectCodeCommit} + pendingFinding={handoff} + fixFindingLabel={handoffLabels.fixFinding} + {...(canFixFindings ? { onFixFinding: startFixFinding } : {})} + {...(attachTarget === null ? {} : { onAddToChat: addCommentToChat })} + onRefresh={refreshDetail} + refreshToken={refreshToken} + backgroundRefreshToken={turnRefresh ?? 0} + revealRequest={codeRevealRequest} + revealUrl={tab === "code" ? revealUrl : undefined} + onRevealSettled={settleReveal} /> -
    - ) : null} - {mountedTabs.has("timeline") ? ( -
    - {activityPending ? ( -
    - -
    - ) : activityError ? ( - - ) : ( - - )} -
    - ) : null} - {mountedTabs.has("code") ? ( -
    - - -
    - } - > - - -
    - ) : null} -
    - ) : null} -
    - - {detail ? ( -
    - -
    + +
    + ) : null} + ) : null}
    - + + {detail ? ( +
    + +
    + ) : null} +
    ); } diff --git a/apps/web/src/components/pullRequest/PullRequestListFilters.tsx b/apps/web/src/components/pullRequest/PullRequestListFilters.tsx index 58dc689343bd1..c027fc8495e6a 100644 --- a/apps/web/src/components/pullRequest/PullRequestListFilters.tsx +++ b/apps/web/src/components/pullRequest/PullRequestListFilters.tsx @@ -47,7 +47,6 @@ import { MenuSubTrigger, MenuTrigger, } from "../ui/menu"; -import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { pullRequestAuthorChoices, selectedPullRequestAuthor, @@ -59,6 +58,7 @@ import { import { resolveFilterOptions } from "./pullRequestListOptions"; import { PullRequestActorAvatar } from "./pullRequestPresentation"; import { PullRequestGlyph } from "./pullRequestIcons"; +import { SharedTooltipTrigger } from "../ui/shared-tooltip"; export interface PullRequestFilterOption { readonly value: Value; @@ -236,12 +236,7 @@ function PullRequestFilterRadioGroup({ ); if (!option.unavailable) return item; - return ( - - - {option.unavailable} - - ); + return ; })} ); diff --git a/apps/web/src/components/pullRequest/PullRequestListRow.tsx b/apps/web/src/components/pullRequest/PullRequestListRow.tsx index feec84fac0110..1cf342fe6fb28 100644 --- a/apps/web/src/components/pullRequest/PullRequestListRow.tsx +++ b/apps/web/src/components/pullRequest/PullRequestListRow.tsx @@ -9,12 +9,12 @@ import { cn } from "~/lib/utils"; import { RelativeTime } from "~/components/RelativeTime"; import { MiddleTruncate } from "../ui/middle-truncate"; -import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { PullRequestActorAvatar, PullRequestConflictGlyph, PullRequestStateGlyph, } from "./pullRequestPresentation"; +import { SharedTooltipTrigger } from "../ui/shared-tooltip"; export const PULL_REQUEST_ROW_CLASS = "group/pr-row flex w-full items-center gap-2 rounded-md py-1 pr-1 text-left"; @@ -114,17 +114,13 @@ export function PullRequestRowAuthor({ }) { const login = actor?.login ?? "ghost"; return ( - - } - > - - {login} - - - {actor?.name && actor.name !== login ? `${actor.name} (@${login})` : login} - - + } + label={actor?.name && actor.name !== login ? `${actor.name} (@${login})` : login} + > + + {login} + ); } diff --git a/apps/web/src/components/pullRequest/PullRequestReviewAnnotation.tsx b/apps/web/src/components/pullRequest/PullRequestReviewAnnotation.tsx index 43b5c90554809..4272650642f2e 100644 --- a/apps/web/src/components/pullRequest/PullRequestReviewAnnotation.tsx +++ b/apps/web/src/components/pullRequest/PullRequestReviewAnnotation.tsx @@ -25,7 +25,6 @@ import { cn } from "~/lib/utils"; import { SpeechTextField, TextFieldSpeechControls } from "~/speech/useTextFieldSpeech"; import { Button } from "../ui/button"; -import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { PullRequestEditButton } from "./PullRequestEditButton"; import { isCommentSubmitShortcut } from "../diffs/commentSubmitShortcut"; import { @@ -42,6 +41,7 @@ import { PullRequestMarkdownTextarea, type PullRequestCompletionScope, } from "./PullRequestMarkdownTextarea"; +import { SharedTooltipTrigger } from "../ui/shared-tooltip"; const CARD_CLASS = "mx-3 my-2 rounded-xl border border-border/70 bg-background p-3 text-sm shadow-sm"; @@ -154,34 +154,29 @@ export function InlineReviewThreads({ return ( <> {resolved.length > 0 ? ( - - event.stopPropagation()} - onClick={() => - setShown(new Set((expanded ? open : threads).map((thread) => thread.id))) - } - /> - } - > - {[...authors].slice(0, 3).map(([login, author]) => ( - - ))} - - {label} - + event.stopPropagation()} + onClick={() => + setShown(new Set((expanded ? open : threads).map((thread) => thread.id))) + } + /> + } + label={label} + side="left" + > + {[...authors].slice(0, 3).map(([login, author]) => ( + + ))} + ) : null} {threads.map((thread) => renderThread(thread, thread.isResolved && !shown.has(thread.id)))} diff --git a/apps/web/src/components/pullRequest/PullRequestRow.tsx b/apps/web/src/components/pullRequest/PullRequestRow.tsx index 872cd534de991..738aafa09531b 100644 --- a/apps/web/src/components/pullRequest/PullRequestRow.tsx +++ b/apps/web/src/components/pullRequest/PullRequestRow.tsx @@ -14,7 +14,6 @@ import { memo, type RefCallback } from "react"; import { cn } from "~/lib/utils"; import { getSourceControlPresentationForKind } from "~/sourceControlPresentation"; -import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { PullRequestChecksPopover } from "./PullRequestChecksPopover"; import { pullRequestPanelReference } from "./usePullRequestDetail"; import type { EnvironmentPullRequestEntry } from "./pullRequestList.logic"; @@ -28,6 +27,7 @@ import { } from "./PullRequestListRow"; import { PullRequestPrivateMark } from "./PullRequestDetailLayout"; import { PullRequestLabelChip, PullRequestReviewDecisionGlyph } from "./pullRequestPresentation"; +import { SharedTooltipTrigger } from "../ui/shared-tooltip"; const LABEL_SLOTS = [ { overflow: "@xl/pr-row-meta:hidden" }, @@ -217,32 +217,32 @@ function PullRequestRowImpl({ meta={ <> {matchedElsewhere ? ( - - - } - > - - matched in the description - - - - matched in the description - - - - Matched in the description - - + + } + label={ + <> + Matched in the description + + } + > + + matched in the description + + + + matched in the description + + ) : null} {showProvider ? ( - - }> - - - {providerName} - + } + label={providerName} + > + + ) : null} - void perform(action)} - onPointerDown={(event) => { - if (action !== "close" || !event.isPrimary || event.button !== 0) return; - event.stopPropagation(); - onCloseSweepStart?.(entry, event.nativeEvent); - }} - /> - } - > - {busy ? : } - {label} - - - {action === "merge" && entry.stack + void perform(action)} + onPointerDown={(event) => { + if (action !== "close" || !event.isPrimary || event.button !== 0) return; + event.stopPropagation(); + onCloseSweepStart?.(entry, event.nativeEvent); + }} + /> + } + label={ + action === "merge" && entry.stack ? gt( "Open this {term, select, mr {merge request} cr {change request} other {pull request}} to merge its stack", { term: changeRequestTermKind(terminology) }, ) : action === "close" && onCloseSweepStart ? gt("Close immediately, or drag across rows to close several") - : resolve(ACTIONS[action].immediate)} - - + : resolve(ACTIONS[action].immediate) + } + > + {busy ? : } + {label} + ); })} diff --git a/apps/web/src/components/pullRequest/PullRequestStackMenu.tsx b/apps/web/src/components/pullRequest/PullRequestStackMenu.tsx index 299f919bfab87..5271d4f04e1f5 100644 --- a/apps/web/src/components/pullRequest/PullRequestStackMenu.tsx +++ b/apps/web/src/components/pullRequest/PullRequestStackMenu.tsx @@ -1,4 +1,3 @@ -import { Tooltip, TooltipTrigger, TooltipPopup } from "../ui/tooltip"; import type { EnvironmentId, PullRequestRef, @@ -33,6 +32,7 @@ import { PullRequestGlyph } from "./pullRequestIcons"; import { mergeHeadPin, readableFailure } from "./pullRequestDetail.logic"; import { changeRequestTermKind } from "./changeRequestTerm"; +import { SharedTooltipTrigger } from "../ui/shared-tooltip"; export function PullRequestStackMenu({ hostLabel, @@ -220,36 +220,36 @@ export function PullRequestStackMenu({ return ( <> - - - } - > - {position}/ - {stack.layers.length} - {onRetry ? : null} - - } - /> - - - View stack #{stack.number}, layer {position} of{" "} - {stack.layers.length} - - {notice ? ` · ${notice}` : null} - - + + } + > + {position}/ + {stack.layers.length} + {onRetry ? : null} + + } + label={ + <> + + View stack #{stack.number}, layer {position} of{" "} + {stack.layers.length} + + {notice ? ` · ${notice}` : null} + + } + /> @@ -319,34 +319,32 @@ export function PullRequestStackMenu({ {(leadsWithAutoMerge || canMerge) && !autoMergeArmed && selectedLayer?.state === "open" ? ( - - - - - } - /> - - {stale + + + + } + label={ + stale ? staleReason : gt( "{count, plural, one {Merge stack through '#'{number} into {base} ({count} {term, select, mr {merge request} cr {change request} other {pull request}})} other {Merge stack through '#'{number} into {base} ({count} {term, select, mr {merge requests} cr {change requests} other {pull requests}})}}", @@ -356,9 +354,9 @@ export function PullRequestStackMenu({ base: stack.base, term: changeRequestTermKind(terminology), }, - )} - - + ) + } + /> ) : null} - - - } - aria-label={gt("Stack {number}, layer {position} of {size}", { - number: membership.number, - position: membership.position, - size: membership.size, - })} - onClick={(event) => event.stopPropagation()} - onKeyDown={(event) => event.stopPropagation()} - > - - {membership.position}/{membership.size} - - } - /> - - - View stack #{membership.number}, layer {membership.position} of{" "} - {membership.size} - - - + + } + aria-label={gt("Stack {number}, layer {position} of {size}", { + number: membership.number, + position: membership.position, + size: membership.size, + })} + onClick={(event) => event.stopPropagation()} + onKeyDown={(event) => event.stopPropagation()} + > + + {membership.position}/{membership.size} + + } + label={ + <> + + View stack #{membership.number}, layer {membership.position} of{" "} + {membership.size} + + + } + /> event.stopPropagation()} diff --git a/apps/web/src/components/pullRequest/PullRequestTimelineTab.tsx b/apps/web/src/components/pullRequest/PullRequestTimelineTab.tsx index e282676792a9b..368f9cbcf382b 100644 --- a/apps/web/src/components/pullRequest/PullRequestTimelineTab.tsx +++ b/apps/web/src/components/pullRequest/PullRequestTimelineTab.tsx @@ -37,7 +37,6 @@ import { Button } from "../ui/button"; import { PullRequestEditButton } from "./PullRequestEditButton"; import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from "../ui/collapsible"; import { toastManager } from "../ui/toast"; -import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { buildPullRequestTimeline, groupPullRequestTimelineConversations, @@ -75,6 +74,7 @@ import { import { LegendList, type LegendListRef } from "@legendapp/list/react"; import { changeRequestTermKind, type ChangeRequestTermKind } from "./changeRequestTerm"; +import { SharedTooltipTrigger } from "../ui/shared-tooltip"; interface ReactionSurface { revealAnchor?: string | null; @@ -198,24 +198,24 @@ function AddToChatButton({ const gt = useGT(); const onAddToChat = reactions.onAddToChat; return onAddToChat === undefined ? null : ( - - onAddToChat(comment)} - /> - } - > - - - - Add to chat - - + onAddToChat(comment)} + /> + } + label={ + <> + Add to chat + + } + > + + ); } @@ -756,30 +756,29 @@ function ReviewVerdictEvent({

    - - - } - > - {stale ? ( - <> - {pullRequestReviewOutcomeLabel(outcome, resolve)} - {staleReviewOutcomeLabel(outcome, gt)} - - ) : ( - pullRequestReviewOutcomeLabel(outcome, resolve) - )} - - {pullRequestReviewOutcomeStaleLabel(outcome, resolve)} - + + } + label={pullRequestReviewOutcomeStaleLabel(outcome, resolve)} + > + {stale ? ( + <> + {pullRequestReviewOutcomeLabel(outcome, resolve)} + {staleReviewOutcomeLabel(outcome, gt)} + + ) : ( + pullRequestReviewOutcomeLabel(outcome, resolve) + )} +

    diff --git a/apps/web/src/components/pullRequest/ThreadPullRequestsPanel.tsx b/apps/web/src/components/pullRequest/ThreadPullRequestsPanel.tsx index 95185c23ae263..a69a67374b3f1 100644 --- a/apps/web/src/components/pullRequest/ThreadPullRequestsPanel.tsx +++ b/apps/web/src/components/pullRequest/ThreadPullRequestsPanel.tsx @@ -44,7 +44,6 @@ import { ThreadDetailsIssueRows } from "../chat/ThreadDetailsIssueRows"; import { Button } from "../ui/button"; import { Menu, MenuItem, MenuPopup, MenuTrigger } from "../ui/menu"; import { MiddleTruncate } from "../ui/middle-truncate"; -import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { openLinkPullRequestDialog } from "./LinkPullRequestDialog"; import { PULL_REQUEST_ROW_CLASS, @@ -64,6 +63,7 @@ import { pullRequestQuickActions } from "./pullRequestList.logic"; import { PullRequestSpeedActions, PullRequestSpeedModeContext } from "./PullRequestSpeedActions"; import { changeRequestTermKind } from "./changeRequestTerm"; +import { SharedTooltipTrigger } from "../ui/shared-tooltip"; const SOURCE_LABELS: Record = { manual: msg("Linked by you"), @@ -81,16 +81,16 @@ function ChecksGlyph({ const resolve = useMessages(); const presentation = pullRequestChecksStatePresentation(state, resolve); return ( - - }> - - - {presentation.label} - + } + label={presentation.label} + > + + ); } @@ -201,31 +201,35 @@ function LinkRowImpl({ > - }> - #{link.number} - - - {resolve(SOURCE_LABELS[link.source])} · - - + } + label={ + <> + {resolve(SOURCE_LABELS[link.source])} · + + } + > + #{link.number} + } title={snapshot?.title ?? link.repository} signals={ open ? ( <> {watching ? ( - - }> - - - - - Watching: the agent wakes when checks finish, someone comments, or the - branch conflicts - - - + } + label={ + <> + + Watching: the agent wakes when checks finish, someone comments, or the + branch conflicts + + + } + > + + ) : null} {snapshot?.checksState ? : null} {snapshot?.reviewDecision ? ( @@ -259,17 +263,12 @@ function LinkRowImpl({ meta={ <> {stack ? ( - - - } - > - - {stack.size} - - - {stack.kind === "native" + + } + label={ + stack.kind === "native" ? gt("{host} stack of {size}: merging a layer lands the ones below it.", { host: sourceControlClients.hostLabelForChangeRequestUrl(link.url), size: stack.size, @@ -280,9 +279,12 @@ function LinkRowImpl({ size: stack.size, terms: changeRequestTermKind(linkHost.changeRequest), }, - )} - - + ) + } + > + + {stack.size} + ) : null} {snapshot?.author ? ( - - }> - - - {link.repository} - + } + label={link.repository} + > + + ) : ( diff --git a/apps/web/src/components/search/ProjectContentSearchDialog.tsx b/apps/web/src/components/search/ProjectContentSearchDialog.tsx index 0515c9d026bc3..7e97b76bfefc3 100644 --- a/apps/web/src/components/search/ProjectContentSearchDialog.tsx +++ b/apps/web/src/components/search/ProjectContentSearchDialog.tsx @@ -15,8 +15,8 @@ import { PierreEntryIcon } from "../chat/PierreEntryIcon"; import { CommandPaletteContent } from "../CommandPaletteContent"; import { ScrollArea } from "../ui/scroll-area"; import { Toggle } from "../ui/toggle"; -import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { HighlightedSearchLine } from "./HighlightedSearchLine"; +import { SharedTooltipTrigger } from "../ui/shared-tooltip"; interface ProjectContentSearchDialogProps { readonly onOpenChange: (open: boolean) => void; @@ -59,23 +59,21 @@ function SearchOptionButton(props: { readonly children: ReactNode; }) { return ( - - - } - > - {props.children} - - {props.label} - + + } + label={props.label} + > + {props.children} + ); } diff --git a/apps/web/src/components/settings/AboutVersionTitle.tsx b/apps/web/src/components/settings/AboutVersionTitle.tsx index e8e3fd654e5e6..5026d19321b81 100644 --- a/apps/web/src/components/settings/AboutVersionTitle.tsx +++ b/apps/web/src/components/settings/AboutVersionTitle.tsx @@ -4,7 +4,7 @@ import { APP_VERSION } from "../../branding"; import { useCopyToClipboard } from "../../hooks/useCopyToClipboard"; import { InlineButton } from "../ui/button"; import { stackedThreadToast, toastManager } from "../ui/toast"; -import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; +import { SharedTooltipTrigger } from "../ui/shared-tooltip"; export function AboutVersionTitle() { const gt = useGT(); @@ -31,22 +31,22 @@ export function AboutVersionTitle() { Version - - copyToClipboard(APP_VERSION, undefined)} - > - {APP_VERSION} - - } - /> - - Copy version - - + copyToClipboard(APP_VERSION, undefined)} + > + {APP_VERSION} + + } + label={ + <> + Copy version + + } + /> ); diff --git a/apps/web/src/components/settings/AcpRegistrySearchStep.tsx b/apps/web/src/components/settings/AcpRegistrySearchStep.tsx index 3cafdde2be543..a97b8fe77153f 100644 --- a/apps/web/src/components/settings/AcpRegistrySearchStep.tsx +++ b/apps/web/src/components/settings/AcpRegistrySearchStep.tsx @@ -28,11 +28,11 @@ import { Alert, AlertDescription } from "../ui/alert"; import { Button } from "../ui/button"; import { InputGroup, InputGroupAddon, InputGroupInput } from "../ui/input-group"; import { ScrollArea } from "../ui/scroll-area"; -import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { isConfiguredAcpRegistryAgent } from "./AddProviderInstanceDialog.logic"; import { ProviderDriverKind } from "@t3tools/contracts"; import { ProviderInstanceIcon } from "../chat/ProviderInstanceIcon"; import { providerClients } from "./providerDriverMeta"; +import { SharedTooltipTrigger } from "../ui/shared-tooltip"; function errorMessage(error: unknown): string { return error instanceof Error && error.message.trim() @@ -318,25 +318,25 @@ function AcpRegistryAgentRow({
    {aboutUrl ? ( - - } - > - - - } - /> - - - About {agent.name} - - - + } + > + + + } + label={ + <> + + About {agent.name} + + + } + /> ) : null} - } - /> - } - /> - - Add environment - - + + + + Add environment + + + } + /> + } + label={ + <> + Add environment + + } + /> diff --git a/apps/web/src/components/settings/ArchivedThreadsPanel.tsx b/apps/web/src/components/settings/ArchivedThreadsPanel.tsx index cc1c95ba0bc86..25c7329a57647 100644 --- a/apps/web/src/components/settings/ArchivedThreadsPanel.tsx +++ b/apps/web/src/components/settings/ArchivedThreadsPanel.tsx @@ -27,7 +27,7 @@ import { ProjectFavicon } from "../ProjectFavicon"; import { msg, T, useGT, useMessages } from "gt-react"; import { type ReactNode, useRef, useState } from "react"; import { observeIntersection } from "~/lib/observeIntersection"; -import { Tooltip, TooltipTrigger, TooltipPopup } from "../ui/tooltip"; +import { SharedTooltipTrigger } from "../ui/shared-tooltip"; const ARCHIVE_ACTIONS = [ { @@ -289,23 +289,22 @@ export function ArchivedThreadsPanel() { control={
    {ARCHIVE_ACTIONS.map(({ action, label, threadLabel, Icon }) => ( - - void handleThreadAction(action, thread)} - /> - } - > - - - {m(label)} - + void handleThreadAction(action, thread)} + /> + } + label={m(label)} + > + + ))}
    } diff --git a/apps/web/src/components/settings/AuthorizedClientsSettings.tsx b/apps/web/src/components/settings/AuthorizedClientsSettings.tsx index d44bffdc04137..5ee9ab7012bcd 100644 --- a/apps/web/src/components/settings/AuthorizedClientsSettings.tsx +++ b/apps/web/src/components/settings/AuthorizedClientsSettings.tsx @@ -51,7 +51,6 @@ import { import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover"; import { QRCodeSvg } from "../ui/qr-code"; import { stackedThreadToast, toastManager } from "../ui/toast"; -import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { Button } from "../ui/button"; import { Textarea } from "../ui/textarea"; import { @@ -76,6 +75,7 @@ import { isHostedAppPairingUrl, endpointShareHint, } from "./ConnectionsSettings.logic"; +import { SharedTooltipTrigger } from "../ui/shared-tooltip"; function AccessScopeSummary({ scopes, @@ -287,12 +287,9 @@ const PairingLinkListRow = memo(function PairingLinkListRow({

    {primaryLabel}

    - - }> - {formatExpiresInLabel(pairingLink.expiresAt, nowMs, m)} - - {expiresAbsolute} - + } label={expiresAbsolute}> + {formatExpiresInLabel(pairingLink.expiresAt, nowMs, m)} + ·

    @@ -453,16 +450,14 @@ const PairingLinkListRow = memo(function PairingLinkListRow({
    ) : null}
    - - - {qrPairingUrl} - - } - /> - {qrPairingUrl} - + + {qrPairingUrl} + + } + label={qrPairingUrl} + /> - } - /> - - Configure background activity - - + setBackgroundActivityDialogOpen(true)} + > + + + } + label={ + <> + Configure background activity + + } + /> ) : null} - - - - } - /> - - - Network exposure changes restart the backend and must be controlled where the server - process is launched. - - - + + + + } + label={ + <> + + Network exposure changes restart the backend and must be controlled where the + server process is launched. + + + } + /> ) : undefined } /> diff --git a/apps/web/src/components/settings/DiagnosticsSettings.tsx b/apps/web/src/components/settings/DiagnosticsSettings.tsx index 75817a6e1b5ba..c77839ad52f78 100644 --- a/apps/web/src/components/settings/DiagnosticsSettings.tsx +++ b/apps/web/src/components/settings/DiagnosticsSettings.tsx @@ -41,7 +41,6 @@ import { useCopyToClipboard } from "../../hooks/useCopyToClipboard"; import { Button } from "../ui/button"; import { ScrollArea } from "../ui/scroll-area"; import { Toggle, ToggleGroup } from "../ui/toggle-group"; -import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { toastManager } from "../ui/toast"; import { formatDiagnosticsDuration } from "./DiagnosticsSettings.logic"; import { ExpandableText } from "./ExpandableText"; @@ -51,6 +50,7 @@ import { SettingsPageContainer, SettingsSection } from "./settingsLayout"; import { useAtomCommand } from "../../state/use-atom-command"; import { useSettingsScope } from "./SettingsScopeContext"; import { TelemetryExportSettings } from "./TelemetryExportSettings"; +import { SharedTooltipTrigger } from "../ui/shared-tooltip"; const NUMBER_FORMAT = new Intl.NumberFormat(); @@ -89,20 +89,18 @@ function StatBlock({
    {label} {tooltip ? ( - - - - - } - /> - {tooltip} - + + + + } + label={tooltip} + /> ) : null}
    - - - {shortenTraceId(traceId)} - - } - /> - - {traceId} - - - - copyToClipboard(traceId)} - > - - - } - /> - {copied ? gt("Copied") : gt("Copy full trace ID")} - + + {shortenTraceId(traceId)} + + } + label={traceId} + variant="code" + /> + copyToClipboard(traceId)} + > + + + } + label={copied ? gt("Copied") : gt("Copy full trace ID")} + />
    ); } @@ -293,14 +286,11 @@ function ProcessNameCell({ } + label={process.command} + variant="code" + />
    ); } @@ -425,14 +415,11 @@ function ProcessDiagnosticsTable({ {formatBytes(process.rssBytes)} - - {process.command}} - /> - - {process.command} - - + {process.command}} + label={process.command} + variant="code" + /> {process.pid} @@ -494,14 +481,11 @@ function ResourceHistoryProcessNameCell({ process.isServerRoot ? "bg-warning/90" : "bg-success/80", )} /> - - {name}} - /> - - {process.command} - - + {name}} + label={process.command} + variant="code" + />
    ); } @@ -525,36 +509,33 @@ function ProcessResourceHistoryChart({ const peakHeight = Math.max(2, (bucket.maxCpuPercent / maxCpuPercent) * 100); const averageHeight = Math.max(2, (bucket.avgCpuPercent / maxCpuPercent) * 100); return ( - - -
    - - {gt("Average CPU {average}%, peak CPU {peak}%", { - average: bucket.avgCpuPercent.toFixed(1), - peak: bucket.maxCpuPercent.toFixed(1), - })} - -
    -
    -
    + +
    + + {gt("Average CPU {average}%, peak CPU {peak}%", { + average: bucket.avgCpuPercent.toFixed(1), + peak: bucket.maxCpuPercent.toFixed(1), + })} + +
    +
    - } - /> - - {gt("Avg {average}%, peak {peak}%", { - average: bucket.avgCpuPercent.toFixed(1), - peak: bucket.maxCpuPercent.toFixed(1), - })} - - +
    + } + label={gt("Avg {average}%, peak {peak}%", { + average: bucket.avgCpuPercent.toFixed(1), + peak: bucket.maxCpuPercent.toFixed(1), + })} + /> ); })}
    @@ -687,14 +668,11 @@ function ProcessResourceHistoryTable({ {formatBytes(process.maxRssBytes)} - - {process.command}} - /> - - {process.command} - - + {process.command}} + label={process.command} + variant="code" + /> {process.pid} @@ -755,22 +733,20 @@ function DiagnosticsRefreshButton({ onClick: () => void; }) { return ( - - - - - } - /> - {label} - + + + + } + label={label} + /> ); } @@ -1151,28 +1127,28 @@ function DiagnosticsSettingsBody() { headerAction={
    - - - - - } - /> - - Open logs folder - - + + + + } + label={ + <> + Open logs folder + + } + /> {removable ? ( - - - } - > - - - - Remove route - - + + } + label={ + <> + Remove route + + } + > + + ) : null} ); diff --git a/apps/web/src/components/settings/EnvironmentsMap.tsx b/apps/web/src/components/settings/EnvironmentsMap.tsx index cd38521dc6b2e..a518c04548828 100644 --- a/apps/web/src/components/settings/EnvironmentsMap.tsx +++ b/apps/web/src/components/settings/EnvironmentsMap.tsx @@ -74,7 +74,6 @@ import { Button } from "../ui/button"; import { InputGroup, InputGroupAddon, InputGroupInput } from "../ui/input-group"; import { Menu, MenuItem, MenuPopup, MenuTrigger } from "../ui/menu"; import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover"; -import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { buildFleetGraph, anchorFleetView, @@ -136,6 +135,7 @@ import { LinkEnvironmentDialog, type LinkEnvironmentPrefill } from "./LinkedEnvi import { LinkSeveralEnvironmentsDialog } from "./LinkSeveralEnvironments"; import { savedBackendStatus } from "./SavedEnvironmentRows"; import { SettingsSearchTarget } from "./settingsLayout"; +import { SharedTooltipTrigger } from "../ui/shared-tooltip"; type GT = ReturnType; type Messages = ReturnType; @@ -934,32 +934,28 @@ function FleetCanvas({ ) : null} {sources.length === 0 ? null : source !== undefined ? ( - - onLinkSeveral(source.id)}> + {gt("Link several…")} + + } + label={selectSeveral} + /> + ) : ( + + onLinkSeveral(source.id)}> - {gt("Link several…")} - + + {gt("Link several…")} + + } + /> } + label={selectSeveral} /> - {selectSeveral} - - ) : ( - - - - {gt("Link several…")} - - } - /> - } - /> - {selectSeveral} - {sources.map((node) => ( onLinkSeveral(node.id)}> diff --git a/apps/web/src/components/settings/IntegrationsSettings.tsx b/apps/web/src/components/settings/IntegrationsSettings.tsx index c6a1efcec8fe5..a6dd44b5e2945 100644 --- a/apps/web/src/components/settings/IntegrationsSettings.tsx +++ b/apps/web/src/components/settings/IntegrationsSettings.tsx @@ -99,7 +99,6 @@ import { SelectValue, } from "../ui/select"; import { Switch } from "../ui/switch"; -import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { getClientSettings, persistClientSettingsUpdate, @@ -121,6 +120,7 @@ import { commitNumberFieldOnEnter } from "./commitNumberFieldOnEnter"; import { useSettingsScope } from "./SettingsScopeContext"; import { BrowserImportWizard, type WizardTarget } from "./BrowserImportWizard"; import type { ImportOutcome } from "./browserImportWizard.logic"; +import { SharedTooltipTrigger } from "../ui/shared-tooltip"; const FILL_VALUE = "fill"; const RESPONSIVE_VALUE = "responsive"; @@ -469,30 +469,30 @@ function BrowserViewportSetting({ disabled }: { readonly disabled: boolean }) { /> - - = presentedSize.width - ? gt("Rotate to landscape") - : gt("Rotate to portrait") - } - onClick={() => - updateSettings({ browserDefaultViewport: rotateViewport(sized) }) - } - > - - - } - /> - - Rotate - - + = presentedSize.width + ? gt("Rotate to landscape") + : gt("Rotate to portrait") + } + onClick={() => + updateSettings({ browserDefaultViewport: rotateViewport(sized) }) + } + > + + + } + label={ + <> + Rotate + + } + />
    ) : null}
    diff --git a/apps/web/src/components/settings/KeybindingsSettings.tsx b/apps/web/src/components/settings/KeybindingsSettings.tsx index 87b4257d07d10..bbe05c925be25 100644 --- a/apps/web/src/components/settings/KeybindingsSettings.tsx +++ b/apps/web/src/components/settings/KeybindingsSettings.tsx @@ -100,6 +100,7 @@ import { SettingsGroup } from "./SettingsGroup"; import { SettingsPageContainer, SettingsRow, SettingsSection } from "./settingsLayout"; import { keybindingSearchAnchorId, useSearchableSetting } from "./settingsSearch"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; +import { SharedTooltipTrigger } from "../ui/shared-tooltip"; import { useAtomCommand } from "../../state/use-atom-command"; function KeybindingPill({ shortcut }: { shortcut: KeybindingShortcut }) { @@ -249,23 +250,21 @@ function WarningTooltipIcon({ children: ReactNode; }) { return ( - - - } - > - - - {children} - + + } + label={children} + > + + ); } @@ -1069,13 +1068,10 @@ function KeybindingSourceBadge({ source }: { source: KeybindingRow["source"] }) function KeybindingRowTitle({ row }: { row: KeybindingRow }) { const m = useMessages(); return ( - - }> - {commandLabel(row.command, m)} - - - {row.command} - + } label={row.command}> + {commandLabel(row.command, m)} + + ); } @@ -1384,25 +1380,25 @@ function NewKeybindingCancelIcon({ }) { const gt = useGT(); return ( - - - } - > - - - - Cancel - - + + } + label={ + <> + Cancel + + } + > + + ); } @@ -1705,25 +1701,25 @@ export function KeybindingsSettingsPanel() { Add keybinding - - - - - } - /> - - Open keybindings.json - - + + + + } + label={ + <> + Open keybindings.json + + } + />
    diff --git a/apps/web/src/components/settings/OpenSourceLicenses.tsx b/apps/web/src/components/settings/OpenSourceLicenses.tsx index 43e759e083941..705984fdafdab 100644 --- a/apps/web/src/components/settings/OpenSourceLicenses.tsx +++ b/apps/web/src/components/settings/OpenSourceLicenses.tsx @@ -22,8 +22,8 @@ import { m } from "../../i18n/messages"; import { Button } from "../ui/button"; import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from "../ui/collapsible"; import { InputGroup, InputGroupAddon, InputGroupInput } from "../ui/input-group"; -import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { SettingsPageContainer, SettingsSection } from "./settingsLayout"; +import { SharedTooltipTrigger } from "../ui/shared-tooltip"; class LicenseManifestLoadError extends Schema.TaggedError()( "LicenseManifestLoadError", @@ -174,24 +174,24 @@ function LicenseHeaderAction({ return (
    - - onSearchOpenChange(true)} - size="icon-micro" - type="button" - variant="ghost-muted" - > - - - } - /> - - Search licenses - - + onSearchOpenChange(true)} + size="icon-micro" + type="button" + variant="ghost-muted" + > + + + } + label={ + <> + Search licenses + + } + />
    ); } diff --git a/apps/web/src/components/settings/ProcessSignalActions.tsx b/apps/web/src/components/settings/ProcessSignalActions.tsx index c6acf52ce6c9e..665be731bedee 100644 --- a/apps/web/src/components/settings/ProcessSignalActions.tsx +++ b/apps/web/src/components/settings/ProcessSignalActions.tsx @@ -2,7 +2,7 @@ import type { ServerProcessSignal } from "@t3tools/contracts"; import { T, useGT, Var } from "gt-react"; import { InlineButton } from "../ui/button"; -import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; +import { SharedTooltipTrigger } from "../ui/shared-tooltip"; const SIGNAL_SHORT_NAMES = { SIGINT: "INT", SIGKILL: "KILL" } as const; @@ -16,44 +16,44 @@ export function ProcessSignalActions({ const gt = useGT(); return (
    - - onSignal("SIGINT")} - > - {SIGNAL_SHORT_NAMES.SIGINT} - - } - /> - - - Send {"SIGINT"} - - - - - onSignal("SIGKILL")} - > - {SIGNAL_SHORT_NAMES.SIGKILL} - - } - /> - - - Send {"SIGKILL"} - - - + onSignal("SIGINT")} + > + {SIGNAL_SHORT_NAMES.SIGINT} + + } + label={ + <> + + Send {"SIGINT"} + + + } + /> + onSignal("SIGKILL")} + > + {SIGNAL_SHORT_NAMES.SIGKILL} + + } + label={ + <> + + Send {"SIGKILL"} + + + } + />
    ); } diff --git a/apps/web/src/components/settings/ProjectSettingsPanel.tsx b/apps/web/src/components/settings/ProjectSettingsPanel.tsx index 01782d42895e1..d10dfaaa8f455 100644 --- a/apps/web/src/components/settings/ProjectSettingsPanel.tsx +++ b/apps/web/src/components/settings/ProjectSettingsPanel.tsx @@ -41,7 +41,6 @@ import { Input } from "../ui/input"; import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select"; import { Switch } from "../ui/switch"; import { stackedThreadToast, toastManager } from "../ui/toast"; -import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { SettingResetButton, SettingsPageContainer, @@ -66,6 +65,7 @@ import { import { useSettingsProjectGroups } from "./useSettingsProjectGroups"; import { readUnloadedThreadCount } from "../../state/olderSettledShelf"; import { settingsScopeEnvironmentLabels } from "./settingsScopeAxis"; +import { SharedTooltipTrigger } from "../ui/shared-tooltip"; const ProjectIconPickerDialog = lazy(() => import("./ProjectIconPickerDialog").then((module) => ({ @@ -497,12 +497,12 @@ function ProjectDetail({ {labels.secondary} ) : null} {!hasMultiple ? ( - - }> - {firstMember.workspaceRoot} - - {firstMember.workspaceRoot} - + } + label={firstMember.workspaceRoot} + > + {firstMember.workspaceRoot} + ) : null} } @@ -515,16 +515,14 @@ function ProjectDetail({ key={member.physicalProjectKey} className="flex min-w-0 flex-col gap-1.5 @min-[36rem]/settings-row:flex-row @min-[36rem]/settings-row:items-center @min-[36rem]/settings-row:justify-between @min-[36rem]/settings-row:gap-3" > - - - } - > - {member.workspaceRoot} - - {member.workspaceRoot} - + + } + label={member.workspaceRoot} + > + {member.workspaceRoot} +
    {checkoutControls(member)}
    ))} diff --git a/apps/web/src/components/settings/ProviderAuthenticationSection.tsx b/apps/web/src/components/settings/ProviderAuthenticationSection.tsx index 17ce23281c59b..638b40f3656cc 100644 --- a/apps/web/src/components/settings/ProviderAuthenticationSection.tsx +++ b/apps/web/src/components/settings/ProviderAuthenticationSection.tsx @@ -25,9 +25,9 @@ import { useAtomCommand } from "../../state/use-atom-command"; import { Button } from "../ui/button"; import { Input } from "../ui/input"; import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select"; -import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { SettingsRow } from "./settingsLayout"; import { RedactedSensitiveText } from "./RedactedSensitiveText"; +import { SharedTooltipTrigger } from "../ui/shared-tooltip"; const ProviderAuthTerminal = lazy(() => import("./ProviderAuthTerminal")); @@ -239,41 +239,41 @@ export function ProviderAuthenticationSection({ > Open browser - - { - // Copy during the click to retain clipboard activation; consent must still be - // recorded before use. - const copied = writeTextToClipboard(url, { - target: "Provider sign-in link", - unavailableMessage: msg( - "Clipboard API is unavailable while copying Provider sign-in link.", - ), - failureMessage: msg( - "Failed to copy Provider sign-in link to the clipboard.", - ), - }); - void (async () => { - await copied; - if (interaction?.type === "browser" && interaction.requiresConsent) - await send({ type: "browser", action: "accept" }); - })().catch(() => setError(gt("Could not copy the sign-in link."))); - }} - > - - - } - /> - - Copy sign-in link - - + { + // Copy during the click to retain clipboard activation; consent must still be + // recorded before use. + const copied = writeTextToClipboard(url, { + target: "Provider sign-in link", + unavailableMessage: msg( + "Clipboard API is unavailable while copying Provider sign-in link.", + ), + failureMessage: msg( + "Failed to copy Provider sign-in link to the clipboard.", + ), + }); + void (async () => { + await copied; + if (interaction?.type === "browser" && interaction.requiresConsent) + await send({ type: "browser", action: "accept" }); + })().catch(() => setError(gt("Could not copy the sign-in link."))); + }} + > + + + } + label={ + <> + Copy sign-in link + + } + /> ) : null} <> diff --git a/apps/web/src/components/settings/ProviderInstanceCard.tsx b/apps/web/src/components/settings/ProviderInstanceCard.tsx index cd5455cc19556..9872da5c7ce6d 100644 --- a/apps/web/src/components/settings/ProviderInstanceCard.tsx +++ b/apps/web/src/components/settings/ProviderInstanceCard.tsx @@ -52,7 +52,6 @@ import { ManagedControl, ManagedNotice } from "../ManagedPolicy"; import { managedInstanceLocks, useManagedPolicy } from "../../state/managedPolicy"; import { disallowedProviderMessage, isManagedDriverAllowed } from "@t3tools/contracts"; import { stackedThreadToast, toastManager } from "../ui/toast"; -import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import type { ProviderClientDefinition, ProviderEnvironmentField, @@ -86,6 +85,7 @@ import { getProviderVersionLabel, providerAuthLabel, } from "./providerStatus"; +import { SharedTooltipTrigger } from "../ui/shared-tooltip"; const ENVIRONMENT_VARIABLE_NAME_PATTERN = /^[a-zA-Z_][a-zA-Z0-9_]*$/; @@ -97,12 +97,7 @@ function ProviderStatusDiagnostic({ children: ReactElement; }) { if (!detail) return children; - return ( - - - {detail} - - ); + return ; } const ENVIRONMENT_VARIABLE_NAME_PLACEHOLDER = "VARIABLE_NAME"; @@ -504,40 +499,36 @@ export function ProviderEnvironmentSection(props: { ); const sensitiveToggle = typeof variable.value === "string" ? ( - - { - const sensitive = !variable.sensitive; - updateVariable(variable.id, { - sensitive, - ...(sensitive && variable.valueRedacted === undefined - ? {} - : { valueRedacted: sensitive ? variable.valueRedacted : false }), - }); - }} - aria-pressed={variable.sensitive} - aria-label={gt("Mark environment variable {name} as sensitive", { - name: variable.name || index + 1, - })} - > - {variable.sensitive ? ( - - ) : ( - - )} - - } - /> - - {variable.sensitive ? gt("Sensitive, stored separately") : gt("Plain text")} - - + { + const sensitive = !variable.sensitive; + updateVariable(variable.id, { + sensitive, + ...(sensitive && variable.valueRedacted === undefined + ? {} + : { valueRedacted: sensitive ? variable.valueRedacted : false }), + }); + }} + aria-pressed={variable.sensitive} + aria-label={gt("Mark environment variable {name} as sensitive", { + name: variable.name || index + 1, + })} + > + {variable.sensitive ? ( + + ) : ( + + )} + + } + label={variable.sensitive ? gt("Sensitive, stored separately") : gt("Plain text")} + /> ) : null; const layout = (source: ReactNode, value: ReactNode) => (
    @@ -635,26 +626,26 @@ function ProjectOverrideInheritance({ ]; return ( - - - } - /> - } - > - - - - Overridden for this project - - + + } + /> + } + label={ + <> + Overridden for this project + + } + > + +
      {layers.map((layer) => ( @@ -1054,39 +1045,35 @@ export function ProviderInstanceCard({ ); const versionAdvisoryNode = versionAdvisory ? ( - - - {updateProgress ? ( - - ) : ( - - )} - - } - /> - } - /> - - {updateProgress ? gt("Updating") : versionAdvisory.title} - - + + {updateProgress ? ( + + ) : ( + + )} + + } + /> + } + label={updateProgress ? gt("Updating") : versionAdvisory.title} + />
      @@ -1144,25 +1131,25 @@ export function ProviderInstanceCard({ {updateCommand} - - copyToClipboard(updateCommand, { providerName: displayName })} - aria-label={gt("Copy update command")} - > - - - } - /> - - Copy command - - + copyToClipboard(updateCommand, { providerName: displayName })} + aria-label={gt("Copy update command")} + > + + + } + label={ + <> + Copy command + + } + />
      ) : null}
      diff --git a/apps/web/src/components/settings/ProviderModelsSection.tsx b/apps/web/src/components/settings/ProviderModelsSection.tsx index fb9bd2df702ea..2fe56258afe7c 100644 --- a/apps/web/src/components/settings/ProviderModelsSection.tsx +++ b/apps/web/src/components/settings/ProviderModelsSection.tsx @@ -17,8 +17,8 @@ import { MAX_CUSTOM_MODEL_LENGTH } from "../../modelSelection"; import { Button } from "../ui/button"; import { Input } from "../ui/input"; import { Switch } from "../ui/switch"; -import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { CustomModelEditor } from "./CustomModelEditor"; +import { SharedTooltipTrigger } from "../ui/shared-tooltip"; const CUSTOM_MODEL_PLACEHOLDER_BY_KIND: Partial> = { [ProviderDriverKind.make("codex")]: "gpt-6.7-codex-ultra-preview", @@ -559,49 +559,46 @@ const ProviderModelRow = memo(function ProviderModelRow({ isHidden && "opacity-50", )} > - - onToggleFavorite(model.slug)} + aria-label={ + isFavorite + ? gt("Remove {name} from favorites", { name: model.name }) + : gt("Add {name} to favorites", { name: model.name }) + } + /> + } + label={isFavorite ? gt("Remove from favorites") : gt("Add to favorites")} + > + +
      + + onToggleFavorite(model.slug)} - aria-label={ - isFavorite - ? gt("Remove {name} from favorites", { name: model.name }) - : gt("Add {name} to favorites", { name: model.name }) - } - /> + } + label={ + <> +
      {model.name}
      + {model.name !== model.slug ? ( + {model.slug} + ) : null} + + } + align="start" > - - - - {isFavorite ? gt("Remove from favorites") : gt("Add to favorites")} - - - - - - } - > - {model.name} - {model.name !== model.slug ? ( - - {model.slug} - - ) : null} - - -
      {model.name}
      - {model.name !== model.slug ? ( - {model.slug} - ) : null} -
      -
      + {model.name} + {model.name !== model.slug ? ( + + {model.slug} + + ) : null} +
      {model.isCustom ? ( {gt("custom", { $context: "badge, user-added model" })} @@ -616,98 +613,98 @@ const ProviderModelRow = memo(function ProviderModelRow({ {!isHidden && !isFiltering ? ( <> - - onMove(model.slug, -1)} - aria-label={gt("Move {name} up", { name: model.name })} - /> - } - > - - - - Move up - - - - onMove(model.slug, 1)} - aria-label={gt("Move {name} down", { name: model.name })} - /> - } - > - - - - Move down - - + onMove(model.slug, -1)} + aria-label={gt("Move {name} up", { name: model.name })} + /> + } + label={ + <> + Move up + + } + > + + + onMove(model.slug, 1)} + aria-label={gt("Move {name} down", { name: model.name })} + /> + } + label={ + <> + Move down + + } + > + + ) : null} {model.isCustom ? ( <> - - onToggleEdit(model.slug)} - /> - } - > - - - - Edit name and options - - - - onRemove(model.slug)} - /> - } - > - - - - Remove custom model - - + onToggleEdit(model.slug)} + /> + } + label={ + <> + Edit name and options + + } + > + + + onRemove(model.slug)} + /> + } + label={ + <> + Remove custom model + + } + > + + ) : null} {/* Disabled switches receive no pointer events; wrap the tooltip trigger. */} - - }> - onSetHidden(model.slug, !checked)} - aria-label={gt("Show {name} in the model picker", { name: model.name })} - /> - - {pickerTooltip} - + } + label={pickerTooltip} + > + onSetHidden(model.slug, !checked)} + aria-label={gt("Show {name} in the model picker", { name: model.name })} + /> +
    ); }); diff --git a/apps/web/src/components/settings/ProviderSettingsPanel.tsx b/apps/web/src/components/settings/ProviderSettingsPanel.tsx index 892c9cd219454..fea2b1258c842 100644 --- a/apps/web/src/components/settings/ProviderSettingsPanel.tsx +++ b/apps/web/src/components/settings/ProviderSettingsPanel.tsx @@ -94,7 +94,6 @@ import { } from "../ui/empty"; import { ScrollArea } from "../ui/scroll-area"; import { Toggle, ToggleGroup } from "../ui/toggle-group"; -import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { stackedThreadToast, toastManager } from "../ui/toast"; import { AddProviderInstanceDialog } from "./AddProviderInstanceDialog"; import { useManagedPolicy } from "~/state/managedPolicy"; @@ -135,6 +134,7 @@ import { resolveRemoteOperateAccess, resolveSelectedProviderEnvironmentId, } from "./ProviderSettingsPanel.logic"; +import { SharedTooltipTrigger } from "../ui/shared-tooltip"; function providerInstanceName(instance: ProviderInstanceConfig): string { return ( @@ -416,32 +416,33 @@ function ProviderSettingsPanelContent(target: ProviderSettingsTarget) { const detail = providerEnvironmentDetail(environment, m); const statusText = connectionStatusTitle(environment.connection, m); return ( - - - + + {environment.label} + {environment.connection.phase !== "connected" ? ( + - {environment.label} - {environment.connection.phase !== "connected" ? ( - - ) : null} - - {detail}, {statusText} - - - } - /> - - {detail} · {statusText} - - + ) : null} + + {detail}, {statusText} + + + } + label={ + <> + {detail} · {statusText} + + } + /> ); })} @@ -1029,57 +1030,57 @@ export function EnvironmentProviderSettings({ variant="plain" titleAction={ canAddProvider ? ( - - setIsAddInstanceDialogOpen(true)} - aria-label={gt("Add provider")} - > - - - } - /> - - Add provider - - + setIsAddInstanceDialogOpen(true)} + aria-label={gt("Add provider")} + > + + + } + label={ + <> + Add provider + + } + /> ) : null } headerAction={ // The ghost button's padding would inset its label, so pull the text to the card edge.
    - - void refreshProviders()} - > - - - Refresh provider status - - - {isRefreshingProviders ? ( - gt("Refreshing providers") - ) : ( - - )} - - - } - /> - - Refresh provider status - - + void refreshProviders()} + > + + + Refresh provider status + + + {isRefreshingProviders ? ( + gt("Refreshing providers") + ) : ( + + )} + + + } + label={ + <> + Refresh provider status + + } + />
    } > diff --git a/apps/web/src/components/settings/ProviderSetupSection.tsx b/apps/web/src/components/settings/ProviderSetupSection.tsx index 5c887e7a3aee1..93ead5f4fc818 100644 --- a/apps/web/src/components/settings/ProviderSetupSection.tsx +++ b/apps/web/src/components/settings/ProviderSetupSection.tsx @@ -22,9 +22,9 @@ import { useEnvironmentQuery } from "../../state/query"; import { serverEnvironment } from "../../state/server"; import { useAtomCommand } from "../../state/use-atom-command"; import { Button } from "../ui/button"; -import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { SettingsRow } from "./settingsLayout"; import { ProviderAuthenticationSection } from "./ProviderAuthenticationSection"; +import { SharedTooltipTrigger } from "../ui/shared-tooltip"; interface ProviderSetupSectionProps { readonly environmentId: EnvironmentId; @@ -307,25 +307,25 @@ function ProviderSetupActions({ ) : null} {installation?.canRemove && !installActive ? ( - - void removeRuntime()} - /> - } - > - - - - Remove downloaded runtime - - + void removeRuntime()} + /> + } + label={ + <> + Remove downloaded runtime + + } + > + + ) : null} diff --git a/apps/web/src/components/settings/RedactedSensitiveText.tsx b/apps/web/src/components/settings/RedactedSensitiveText.tsx index 6dd8e1f77cc48..ab267c4eed028 100644 --- a/apps/web/src/components/settings/RedactedSensitiveText.tsx +++ b/apps/web/src/components/settings/RedactedSensitiveText.tsx @@ -2,7 +2,7 @@ import { useState } from "react"; import { flushSync } from "react-dom"; import { cn } from "../../lib/utils"; -import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; +import { SharedTooltipTrigger } from "../ui/shared-tooltip"; const REDACTED_TEXT_ALPHABET = "abcdefghjkmnpqrstuvwxyz23456789"; @@ -40,39 +40,37 @@ export function RedactedSensitiveText(props: { if (!value) return null; return ( - - { - if (!revealed) return setVisibility("revealed"); - const button = event.currentTarget; - flushSync(() => setVisibility("hiding")); - const finishHiding = () => - setVisibility((current) => (current === "hiding" ? "hidden" : current)); - const blur = button - .getAnimations() - .find( - (animation) => - animation instanceof CSSTransition && animation.transitionProperty === "filter", - ); - // Theme changes suppress the transition; a reversed one settles once revealed. - if (blur) void blur.finished.then(finishHiding, finishHiding); - else finishHiding(); - }} - aria-label={props.ariaLabel} - > - {visibility === "hidden" ? redacted : value} - - } - /> - {revealed ? props.hideTooltip : props.revealTooltip} - + { + if (!revealed) return setVisibility("revealed"); + const button = event.currentTarget; + flushSync(() => setVisibility("hiding")); + const finishHiding = () => + setVisibility((current) => (current === "hiding" ? "hidden" : current)); + const blur = button + .getAnimations() + .find( + (animation) => + animation instanceof CSSTransition && animation.transitionProperty === "filter", + ); + // Theme changes suppress the transition; a reversed one settles once revealed. + if (blur) void blur.finished.then(finishHiding, finishHiding); + else finishHiding(); + }} + aria-label={props.ariaLabel} + > + {visibility === "hidden" ? redacted : value} + + } + label={revealed ? props.hideTooltip : props.revealTooltip} + /> ); } diff --git a/apps/web/src/components/settings/ResourceTelemetryDiagnostics.tsx b/apps/web/src/components/settings/ResourceTelemetryDiagnostics.tsx index 7bf23d6186012..7152f3defd4fb 100644 --- a/apps/web/src/components/settings/ResourceTelemetryDiagnostics.tsx +++ b/apps/web/src/components/settings/ResourceTelemetryDiagnostics.tsx @@ -53,7 +53,6 @@ import { useRelativeTimeState } from "../../hooks/useRelativeTimeState"; import { Button } from "../ui/button"; import { ScrollArea } from "../ui/scroll-area"; import { Toggle, ToggleGroup } from "../ui/toggle-group"; -import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { toastManager } from "../ui/toast"; import { formatCpuTime, @@ -65,6 +64,7 @@ import { visibleResourceTelemetryProcesses, } from "./ResourceTelemetryDiagnostics.logic"; import { SettingsSection } from "./settingsLayout"; +import { SharedTooltipTrigger } from "../ui/shared-tooltip"; const HISTORY_WINDOWS = [ { label: "5m", windowMs: 5 * 60_000, bucketMs: 15_000 }, @@ -433,38 +433,40 @@ function ResourceHistoryChart({ minimumVisiblePercent: 1, }); return ( - - - - - - - } - /> - -
    -
    - {gt("CPU avg {percent}%", { percent: bucket.avgCpuPercent.toFixed(1) })} -
    -
    - {gt("CPU peak {percent}%", { percent: bucket.maxCpuPercent.toFixed(1) })} -
    -
    {gt("Read {bytes}", { bytes: formatBytes(bucket.ioReadBytes) })}
    -
    {gt("Write {bytes}", { bytes: formatBytes(bucket.ioWriteBytes) })}
    + + + +
    -
    -
    + } + label={ + <> +
    +
    + {gt("CPU avg {percent}%", { percent: bucket.avgCpuPercent.toFixed(1) })} +
    +
    + {gt("CPU peak {percent}%", { percent: bucket.maxCpuPercent.toFixed(1) })} +
    +
    {gt("Read {bytes}", { bytes: formatBytes(bucket.ioReadBytes) })}
    +
    {gt("Write {bytes}", { bytes: formatBytes(bucket.ioWriteBytes) })}
    +
    + + } + className="text-left" + /> ); })} @@ -506,14 +508,11 @@ function ProcessTreeName({ )} - - {name}} - /> - - {process.command || process.name} - - + {name}} + label={process.command || process.name} + variant="code" + /> ); } @@ -674,12 +673,10 @@ function ProcessTable({ {formatBytes(process.ioReadBytes)} - - {formatBytes(process.ioWriteBytes)}} /> - - {ioSemanticsLabel(process.ioSemantics, messages)} - - + {formatBytes(process.ioWriteBytes)}} + label={ioSemanticsLabel(process.ioSemantics, messages)} + /> {process.identity.pid} @@ -769,18 +766,15 @@ function HistoryProcessTable({ {processes.map((process) => ( - - - {process.name || process.command} - - } - /> - - {process.command || process.name} - - + + {process.name || process.command} + + } + label={process.command || process.name} + variant="code" + /> {categoryLabel(process.category, messages)} @@ -1070,24 +1064,24 @@ function ResourceTelemetryDiagnosticsBody({ ) : null} - - - - - } - /> - - Refresh telemetry snapshot - - + + + + } + label={ + <> + Refresh telemetry snapshot + + } + /> } > diff --git a/apps/web/src/components/settings/SavedEnvironmentRows.tsx b/apps/web/src/components/settings/SavedEnvironmentRows.tsx index 2b9ad1225ff0a..569437f239a22 100644 --- a/apps/web/src/components/settings/SavedEnvironmentRows.tsx +++ b/apps/web/src/components/settings/SavedEnvironmentRows.tsx @@ -43,6 +43,7 @@ import { Menu, MenuItem, MenuPopup, MenuSeparator, MenuTrigger } from "../ui/men import { Switch } from "../ui/switch"; import { stackedThreadToast, toastManager } from "../ui/toast"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; +import { SharedTooltipTrigger } from "../ui/shared-tooltip"; import { Button, InlineButton } from "../ui/button"; import { Empty, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle } from "../ui/empty"; import { @@ -411,26 +412,22 @@ export function SavedBackendListRow({ appearance="icon" /> ) : null} - - onSetEnabled(environmentId, checked)} - /> - } - /> - - {blocked ? gt("Client not supported") : enabled ? gt("Switch off") : gt("Switch on")} - - + onSetEnabled(environmentId, checked)} + /> + } + label={blocked ? gt("Client not supported") : enabled ? gt("Switch off") : gt("Switch on")} + />
    ); return disabledReason ? ( - - {control}} /> - {disabledReason} - + {control}} + label={disabledReason} + /> ) : ( control ); diff --git a/apps/web/src/components/settings/ScheduledTasksSettings.tsx b/apps/web/src/components/settings/ScheduledTasksSettings.tsx index fc7be80a59c38..7a42aae22219a 100644 --- a/apps/web/src/components/settings/ScheduledTasksSettings.tsx +++ b/apps/web/src/components/settings/ScheduledTasksSettings.tsx @@ -146,7 +146,6 @@ import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ import { Switch } from "../ui/switch"; import { Textarea } from "../ui/textarea"; import { stackedThreadToast, toastManager } from "../ui/toast"; -import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { useSearchableSetting } from "./settingsSearch"; import { SettingsPageContainer, @@ -154,6 +153,7 @@ import { SettingsSection, SETTINGS_PICKER_TRIGGER_CLASSNAME, } from "./settingsLayout"; +import { SharedTooltipTrigger } from "../ui/shared-tooltip"; const WEEKDAY_ORDER = [1, 2, 3, 4, 5, 6, 0] as const; const WEEKDAY_SHORT = [ @@ -651,19 +651,18 @@ function ScheduledTaskEnvironmentList({ environments: entries.join(", "), }); return ( - - - } - > - {summary} - - {summary} - + + } + label={summary} + > + {summary} + ); })} diff --git a/apps/web/src/components/settings/SecretSourceInput.tsx b/apps/web/src/components/settings/SecretSourceInput.tsx index 53263c226d2f0..2c244b0e08982 100644 --- a/apps/web/src/components/settings/SecretSourceInput.tsx +++ b/apps/web/src/components/settings/SecretSourceInput.tsx @@ -23,9 +23,9 @@ import { Button } from "../ui/button"; import { DraftInput } from "../ui/draft-input"; import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select"; import { Spinner } from "../ui/spinner"; -import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { SecretInput } from "./SecretInput"; import { classifySecretProvider } from "./SecretProviderDialog.logic"; +import { SharedTooltipTrigger } from "../ui/shared-tooltip"; export interface SecretSource { readonly id: SecretProviderId; @@ -174,39 +174,37 @@ function SecretCheckButton(props: { ? gt("Secret resolved") : state.detail; return ( - - - - - } - /> - {description} - + + + + } + label={description} + /> ); } diff --git a/apps/web/src/components/settings/SettingInheritance.tsx b/apps/web/src/components/settings/SettingInheritance.tsx index 4cae56f264627..b2adc4b7d099d 100644 --- a/apps/web/src/components/settings/SettingInheritance.tsx +++ b/apps/web/src/components/settings/SettingInheritance.tsx @@ -19,11 +19,11 @@ import { PULL_REQUEST_MERGE_METHOD_LABELS } from "../pullRequest/pullRequestDeta import { Button, InlineButton } from "../ui/button"; import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from "../ui/collapsible"; import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover"; -import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { useOptionalSettingsScope } from "./SettingsScopeContext"; import type { ProjectOverrideEntry, ScopedSettingsTarget } from "./scopedSettings"; import { isProjectScopedSettingKey } from "./scopedSettings"; import { settingsScopeEnvironmentLabels } from "./settingsScopeAxis"; +import { SharedTooltipTrigger } from "../ui/shared-tooltip"; interface InheritanceLayer { readonly key: "project" | "environment" | "t3.json" | "built-in"; @@ -280,32 +280,30 @@ export function SettingInheritance({ } return ( - - - } - /> - } - > - + } /> - - {overrideSummary} - + } + label={overrideSummary} + > + +
    {groups.map((members) => { diff --git a/apps/web/src/components/settings/SettingsScopeNotice.tsx b/apps/web/src/components/settings/SettingsScopeNotice.tsx index fc74e2765100a..50df07b78ebf0 100644 --- a/apps/web/src/components/settings/SettingsScopeNotice.tsx +++ b/apps/web/src/components/settings/SettingsScopeNotice.tsx @@ -9,7 +9,6 @@ import type { SidebarProjectSnapshot } from "../../sidebarProjectGrouping"; import { useEnvironments, type EnvironmentPresentation } from "../../state/environments"; import { EnvironmentMachineIcon } from "../EnvironmentMachineIcon"; import { ProjectFavicon } from "../ProjectFavicon"; -import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { ITEM_ROW_CLASSNAME } from "./itemRows"; import { SettingsGroup } from "./SettingsGroup"; import { SettingsPageContainer, SettingsSection } from "./settingsLayout"; @@ -22,6 +21,7 @@ import { settingsScopeEnvironmentLabels, settingsScopeProjectMachines, } from "./settingsScopeAxis"; +import { SharedTooltipTrigger } from "../ui/shared-tooltip"; interface ScopeChoice { label: string; @@ -151,14 +151,12 @@ export function SettingsScopeNotice({ {choice.label} {choice.secondary ? ( - - } - > - {choice.secondary} - - {choice.secondary} - + } + label={choice.secondary} + > + {choice.secondary} + ) : null} diff --git a/apps/web/src/components/settings/SourceControlSettings.tsx b/apps/web/src/components/settings/SourceControlSettings.tsx index 18fda05127d3d..ec720ebe408b6 100644 --- a/apps/web/src/components/settings/SourceControlSettings.tsx +++ b/apps/web/src/components/settings/SourceControlSettings.tsx @@ -31,7 +31,6 @@ import { } from "../ui/empty"; import { Skeleton } from "../ui/skeleton"; import { Switch } from "../ui/switch"; -import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { msg, T, useGT, useMessages, Var } from "gt-react"; import { m, type MessageResolver } from "../../i18n/messages"; @@ -55,6 +54,7 @@ import { sourceControlInstallHintText } from "@t3tools/client-runtime/contract-l import { isSourceControlProviderOffered } from "@t3tools/client-runtime/operations/projects"; import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients"; import { sourceControlIcon } from "~/sourceControlPresentation"; +import { SharedTooltipTrigger } from "../ui/shared-tooltip"; const EMPTY_DISCOVERY_RESULT: SourceControlDiscoveryResult = { versionControlSystems: [], @@ -339,23 +339,23 @@ function DiscoveryItemRow({ ) : null} {offered ? ( - - - } - /> - - Offer when adding or publishing a project - - + + } + label={ + <> + Offer when adding or publishing a project + + } + /> ) : !isVcsNotReady(item) ? ( - - - - } - /> - - Rescan Git and hosting integrations - - + + + + } + label={ + <> + Rescan Git and hosting integrations + + } + /> ); return ( diff --git a/apps/web/src/components/settings/ThemeColorPicker.tsx b/apps/web/src/components/settings/ThemeColorPicker.tsx index 391d975924b1e..dff7ac99ca900 100644 --- a/apps/web/src/components/settings/ThemeColorPicker.tsx +++ b/apps/web/src/components/settings/ThemeColorPicker.tsx @@ -7,7 +7,7 @@ import { hexToHsv, hsvToHex, type HsvColor } from "../../lib/color"; import { ColorHueSlider, ColorSaturationValuePlane } from "../ui/color-picker"; import { Input } from "../ui/input"; import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover"; -import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; +import { SharedTooltipTrigger } from "../ui/shared-tooltip"; const THEME_ROLE_LABELS: Partial> = { canvas: msg("Background"), toolbar: msg("Toolbar background"), @@ -290,29 +290,27 @@ function ThemeColorPicker({ if (cancelledRef.current) onEditCancel?.(); }} > - - - - - } - /> - } - /> - {gt("Choose {label} color", { label })} - + + + + } + /> + } + label={gt("Choose {label} color", { label })} + /> - - onToggleSelected?.(role)} - type="button" - > - {label} - - } - /> - - {selected + onToggleSelected?.(role)} + type="button" + > + {label} + + } + label={ + selected ? gt("Hide where {label} is used", { label }) - : gt("Show where {label} is used", { label })} - - + : gt("Show where {label} is used", { label }) + } + />
    ); if (lockReason === null) return button; - return ( - - - {lockReason} - - ); + return ; }; const renderAppearanceButtons = () => ( diff --git a/apps/web/src/components/settings/ThemePreviewCircles.tsx b/apps/web/src/components/settings/ThemePreviewCircles.tsx index 8f23f5be6caa8..4242ca46b7f72 100644 --- a/apps/web/src/components/settings/ThemePreviewCircles.tsx +++ b/apps/web/src/components/settings/ThemePreviewCircles.tsx @@ -6,13 +6,13 @@ import { THEME_PREVIEW_RENDER_SPECS, } from "@t3tools/shared/themePreview"; import { cn } from "../../lib/utils"; -import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { getThemeColorsForMode, getThemeModes, type ThemeAppearance, type ThemeDefinition, } from "../../themePalette"; +import { SharedTooltipTrigger } from "../ui/shared-tooltip"; const THEME_PREVIEW_ROLES = [ "sidebar", @@ -167,53 +167,50 @@ export function ThemePreviewCircles({ const mode = preview.mode; const isPicked = activeModes.includes(mode); return ( - - { - event.stopPropagation(); - onSelectMode(mode); - }} - type="button" - > - - {isPicked ? ( - <> - - - {mode === "light" ? ( - - ) : ( - - )} - - - ) : null} - - } - /> - - {mode === "light" ? gt("Use for light mode only") : gt("Use for dark mode only")} - - + { + event.stopPropagation(); + onSelectMode(mode); + }} + type="button" + > + + {isPicked ? ( + <> + + + {mode === "light" ? ( + + ) : ( + + )} + + + ) : null} + + } + label={mode === "light" ? gt("Use for light mode only") : gt("Use for dark mode only")} + /> ); })}
    diff --git a/apps/web/src/components/settings/ThemeSettings.tsx b/apps/web/src/components/settings/ThemeSettings.tsx index 9e59c2ef3f30a..9d64c0f2272b0 100644 --- a/apps/web/src/components/settings/ThemeSettings.tsx +++ b/apps/web/src/components/settings/ThemeSettings.tsx @@ -39,7 +39,7 @@ import { } from "../ui/alert-dialog"; import { Button } from "../ui/button"; import { stackedThreadToast, toastManager } from "../ui/toast"; -import { Tooltip, TooltipPopup, TooltipProvider, TooltipTrigger } from "../ui/tooltip"; +import { SharedTooltipTrigger } from "../ui/shared-tooltip"; import { ThemeImportDialog } from "./ThemeImportDialog"; import { useSearchableSetting } from "./settingsSearch"; import { useThemeEditorStore } from "./themeEditorStore"; @@ -89,12 +89,7 @@ function downloadThemeFile(filename: string, contents: string): void { } function ThemeVariantTooltip({ label, children }: { label: string; children: ReactElement }) { - return ( - - - {label} - - ); + return ; } function ThemeLibraryCard({ @@ -145,334 +140,322 @@ function ThemeLibraryCard({ }; }); return ( - - -
    - {variantNavigation ? ( -
    { - const nextTarget = event.relatedTarget; - if ( - !(nextTarget instanceof Node) || - !event.currentTarget.contains(nextTarget) - ) { - setRadialModeOpen(null); - } - }} - onKeyDown={(event) => { - if (event.key === "Escape") setRadialModeOpen(null); - }} - onMouseLeave={() => setRadialModeOpen(null)} - > - {radialModeGroups.map(({ mode, options, selected }) => { - if (!selected) return null; - const rootOffsetX = mode === "light" ? -52 : 52; - const isOpen = radialModeOpen === mode; - const isActive = selected.option.activeModes.includes(mode); - const modeLabel = mode === "light" ? gt("Light") : gt("Dark"); - return ( -
    - - - - +
    + {variantNavigation ? ( +
    { + const nextTarget = event.relatedTarget; + if (!(nextTarget instanceof Node) || !event.currentTarget.contains(nextTarget)) { + setRadialModeOpen(null); + } + }} + onKeyDown={(event) => { + if (event.key === "Escape") setRadialModeOpen(null); + }} + onMouseLeave={() => setRadialModeOpen(null)} + > + {radialModeGroups.map(({ mode, options, selected }) => { + if (!selected) return null; + const rootOffsetX = mode === "light" ? -52 : 52; + const isOpen = radialModeOpen === mode; + const isActive = selected.option.activeModes.includes(mode); + const modeLabel = mode === "light" ? gt("Light") : gt("Dark"); + return ( +
    + + - - ); - }) - : null} -
    - ); - })} -
    - ) : ( - - )} + + + + + + ); + }) + : null} +
    + ); + })} +
    + ) : ( + + )} +
    +
    +
    +
    + +
    -
    -
    -
    - } - aria-pressed={isActive} - className="min-w-0 cursor-pointer truncate rounded-sm text-left text-sm font-medium text-foreground outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-card" - type="button" - onClick={(event) => { - event.stopPropagation(); - onUse(); - }} - > - {variantNavigation?.collectionLabel ?? theme.label} - -
    -
    - {onEdit || onDuplicate || onDownload || onRemove ? ( -
    - {onDuplicate ? ( - - { - event.stopPropagation(); - onDuplicate(); - }} - > - - - } - /> - + label={ + <> Duplicate theme - - - ) : null} - {onEdit ? ( - - { - event.stopPropagation(); - onEdit(); - }} - > - - - } - /> - + + } + /> + ) : null} + {onEdit ? ( + { + event.stopPropagation(); + onEdit(); + }} + > + + + } + label={ + <> Edit theme - - - ) : null} - {onDownload ? ( - - { - event.stopPropagation(); - onDownload(); - }} - > - - - } - /> - + + } + /> + ) : null} + {onDownload ? ( + { + event.stopPropagation(); + onDownload(); + }} + > + + + } + label={ + <> Export theme file - - - ) : null} - {onRemove ? ( - - { - event.stopPropagation(); - onRemove(); - }} - > - - + + } + /> + ) : null} + {onRemove ? ( + - - {variantNavigation ? gt("Remove themes") : gt("Remove theme")} - - - ) : null} -
    - ) : null} -
    + size="icon-xs" + variant="ghost-destructive" + onClick={(event) => { + event.stopPropagation(); + onRemove(); + }} + > + + + } + label={variantNavigation ? gt("Remove themes") : gt("Remove theme")} + /> + ) : null} +
    + ) : null}
    - } - /> - - {variantNavigation +
    + } + label={ + variantNavigation ? gt("Use the first variants for light and dark") : cardModes.length > 1 ? gt("Use for both light and dark") : cardModes[0] === "light" ? gt("Use for light mode only") - : gt("Use for dark mode only")} - - + : gt("Use for dark mode only") + } + /> ); } @@ -786,112 +769,110 @@ export function ThemeLibrary({ ]; const renderPairGrid = () => ( - -
    - {STANDARD_THEME_CARDS.map((standardTheme) => ( +
    + {STANDARD_THEME_CARDS.map((standardTheme) => ( + + openThemeEditor({ + editingThemeId: null, + seedThemeId: null, + seedName: `${standardTheme.label} copy`, + initialAppearance, + }) + } + onUse={() => persistTheme(appearanceMode === "system" ? "system" : appearanceMode)} + onUseMode={handlePairPick(null)} + theme={standardTheme} + /> + ))} + {MAINTAINER_THEMES.map((maintainerTheme) => { + const card = getThemeCardDefinition(maintainerTheme); + return ( openThemeEditor({ editingThemeId: null, - seedThemeId: null, - seedName: `${standardTheme.label} copy`, + seedThemeId: maintainerTheme.id, + seedName: `${maintainerTheme.label} copy`, initialAppearance, }) } - onUse={() => persistTheme(appearanceMode === "system" ? "system" : appearanceMode)} - onUseMode={handlePairPick(null)} - theme={standardTheme} + onUse={() => persistTheme(maintainerTheme.id)} + onUseMode={handlePairPick(maintainerTheme.id)} + theme={card} /> - ))} - {MAINTAINER_THEMES.map((maintainerTheme) => { - const card = getThemeCardDefinition(maintainerTheme); - return ( - - openThemeEditor({ - editingThemeId: null, - seedThemeId: maintainerTheme.id, - seedName: `${maintainerTheme.label} copy`, - initialAppearance, - }) - } - onUse={() => persistTheme(maintainerTheme.id)} - onUseMode={handlePairPick(maintainerTheme.id)} - theme={card} - /> - ); - })} - {environmentThemes - .filter( - // Saved themes win id resolution; show only their card to avoid duplicate keys. - (environmentTheme) => !customThemes.some((theme) => theme.id === environmentTheme.id), - ) - .map((environmentTheme) => ( - - openThemeEditor({ - editingThemeId: null, - seedThemeId: environmentTheme.id, - seedName: `${environmentTheme.label} copy`, - initialAppearance, - }) - } - onUse={() => { - const half = singleAppearanceOf(environmentTheme); - if (half === null) persistTheme(environmentTheme.id); - else assignHalf(half, environmentTheme.id); - }} - onUseMode={handlePairPick(environmentTheme.id)} - theme={getThemeCardDefinition(environmentTheme)} - /> - ))} - {customThemeCollections.map(([collectionId, themes]) => ( - - downloadThemeFile(`${customTheme.id}.json`, serializeThemeFile(customTheme)) - } - onDuplicate={(customTheme) => + ); + })} + {environmentThemes + .filter( + // Saved themes win id resolution; show only their card to avoid duplicate keys. + (environmentTheme) => !customThemes.some((theme) => theme.id === environmentTheme.id), + ) + .map((environmentTheme) => ( + openThemeEditor({ editingThemeId: null, - seedThemeId: customTheme.id, - seedName: `${customTheme.label} copy`, - initialAppearance, - }) - } - onEdit={(customTheme) => - openThemeEditor({ - editingThemeId: customTheme.id, - seedThemeId: null, - seedName: null, + seedThemeId: environmentTheme.id, + seedName: `${environmentTheme.label} copy`, initialAppearance, }) } - onRemove={(customTheme) => handleRemoveTheme(customTheme, themes)} - onUse={(customTheme) => { - const modes = getThemeModes(customTheme); - if (modes.length === 1) assignHalf(modes[0]!, customTheme.id); - else persistTheme(customTheme.id); + onUse={() => { + const half = singleAppearanceOf(environmentTheme); + if (half === null) persistTheme(environmentTheme.id); + else assignHalf(half, environmentTheme.id); }} - onUseMode={(customTheme, mode) => handlePairPick(customTheme.id)(mode)} - themes={themes} + onUseMode={handlePairPick(environmentTheme.id)} + theme={getThemeCardDefinition(environmentTheme)} /> ))} -
    - + {customThemeCollections.map(([collectionId, themes]) => ( + + downloadThemeFile(`${customTheme.id}.json`, serializeThemeFile(customTheme)) + } + onDuplicate={(customTheme) => + openThemeEditor({ + editingThemeId: null, + seedThemeId: customTheme.id, + seedName: `${customTheme.label} copy`, + initialAppearance, + }) + } + onEdit={(customTheme) => + openThemeEditor({ + editingThemeId: customTheme.id, + seedThemeId: null, + seedName: null, + initialAppearance, + }) + } + onRemove={(customTheme) => handleRemoveTheme(customTheme, themes)} + onUse={(customTheme) => { + const modes = getThemeModes(customTheme); + if (modes.length === 1) assignHalf(modes[0]!, customTheme.id); + else persistTheme(customTheme.id); + }} + onUseMode={(customTheme, mode) => handlePairPick(customTheme.id)(mode)} + themes={themes} + /> + ))} +
    ); return ( diff --git a/apps/web/src/components/settings/VoiceSettingsPanel.tsx b/apps/web/src/components/settings/VoiceSettingsPanel.tsx index a6283977cf534..a7eebed9d8af0 100644 --- a/apps/web/src/components/settings/VoiceSettingsPanel.tsx +++ b/apps/web/src/components/settings/VoiceSettingsPanel.tsx @@ -100,7 +100,6 @@ import { ProviderPackageIcon } from "../chat/ProviderPackageIcon"; import { TraitsPicker } from "../chat/TraitsPicker"; import { VoiceInputSetup } from "../chat/VoiceInputSetup"; import { Badge } from "../ui/badge"; -import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { Button } from "../ui/button"; import { Input } from "../ui/input"; import { InputGroup, InputGroupAddon, InputGroupInput } from "../ui/input-group"; @@ -147,6 +146,7 @@ import { useSearchableSetting } from "./settingsSearch"; import { useOptionalSettingsScope, useSettingsScope } from "./SettingsScopeContext"; import { useScopedModelDisabledReason } from "./useScopedModelAvailability"; import { useScopedSettings, useUpdateScopedSettings } from "./useScopedSettings"; +import { SharedTooltipTrigger } from "../ui/shared-tooltip"; const OFF = "off"; const DEVICE = "device"; @@ -212,13 +212,10 @@ type ModelCardProps = { function ModelBadge(props: { icon: ReactNode; label: string; tooltip: string }) { return ( - - }> - {props.icon} - {props.label} - - {props.tooltip} - + } label={props.tooltip}> + {props.icon} + {props.label} + ); } @@ -1457,24 +1454,24 @@ export function VoiceSettingsPanel() { title={gt("Microphone")} description={gt("Voice input uses the first connected microphone in this list.")} control={ - - void refreshMicrophones()} - > - - - } - /> - - Refresh microphones - - + void refreshMicrophones()} + > + + + } + label={ + <> + Refresh microphones + + } + /> } >
    @@ -1659,28 +1656,26 @@ export function VoiceSettingsPanel() { {destination.cloudProvider && chosenEnvironment && (canManageKey || destination.cloudProvider === "openrouter") && ( - - { - if (destination.cloudProvider) - setPendingCloud({ - provider: destination.cloudProvider, - environmentId: chosenEnvironment.environmentId, - }); - }} - > - - - } - /> - {manageLabel} - + { + if (destination.cloudProvider) + setPendingCloud({ + provider: destination.cloudProvider, + environmentId: chosenEnvironment.environmentId, + }); + }} + > + + + } + label={manageLabel} + /> )}
    } diff --git a/apps/web/src/components/settings/settingsLayout.tsx b/apps/web/src/components/settings/settingsLayout.tsx index ee9cf2cfdc89f..70c80e47097b3 100644 --- a/apps/web/src/components/settings/settingsLayout.tsx +++ b/apps/web/src/components/settings/settingsLayout.tsx @@ -22,6 +22,7 @@ import { cn } from "../../lib/utils"; import { WorkspacePageContainer, type WorkspacePageWidth } from "../WorkspacePageContainer"; import { Button } from "../ui/button"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; +import { SharedTooltipTrigger } from "../ui/shared-tooltip"; import { useOptionalSettingsScope } from "./SettingsScopeContext"; import { SettingsScopeSentence } from "./SettingsScopeSentence"; import { @@ -424,24 +425,22 @@ export function SettingsRow({ resetAction ); const inertControl = (message: string) => ( - - - } + + } + label={message} + > +
    -
    - {control} -
    - - {message} - + {control} +
    +
    ); const lackingPermissionMessage = () => { const environments = context diff --git a/apps/web/src/components/sidebar/SidebarChrome.tsx b/apps/web/src/components/sidebar/SidebarChrome.tsx index 1dbc9b9fc6366..637921f1f9100 100644 --- a/apps/web/src/components/sidebar/SidebarChrome.tsx +++ b/apps/web/src/components/sidebar/SidebarChrome.tsx @@ -32,7 +32,6 @@ import { SidebarTrigger, useSidebar, } from "../ui/sidebar"; -import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { readPullRequestListPreferences } from "../pullRequest/pullRequestListPreferences"; import { readIssueListPreferences } from "../issue/issueListPreferences"; import { IssueGlyph } from "../issue/issuePresentation"; @@ -42,6 +41,7 @@ import { SidebarProviderUpdatePill } from "./SidebarProviderUpdatePill"; import { SidebarUpdateArchitectureWarning, SidebarUpdatePill } from "./SidebarUpdatePill"; import { PullRequestGlyph } from "~/components/pullRequest/pullRequestIcons"; import { observeResize } from "~/lib/observeResize"; +import { SharedTooltipTrigger } from "../ui/shared-tooltip"; export const SidebarChromeHeader = memo(function SidebarChromeHeader({ isElectron, @@ -141,29 +141,30 @@ function HistoryNavigationButton({ ); const Icon = direction === "back" ? ArrowLeftIcon : ArrowRightIcon; return ( - - navigateHistory(direction)} - size="icon-sm" - variant={onBackdrop ? "media-navigation" : "ghost"} - /> - } - > - - - - {label} - {shortcutLabel ? ` (${shortcutLabel})` : ""} - - + navigateHistory(direction)} + size="icon-sm" + variant={onBackdrop ? "media-navigation" : "ghost"} + /> + } + label={ + <> + {label} + {shortcutLabel ? ` (${shortcutLabel})` : ""} + + } + side="bottom" + > + + ); } @@ -211,16 +212,14 @@ function SidebarUtilityItem({ }) { return ( - - - {icon} - - } - /> - {label} - + + {icon} + + } + label={label} + /> ); } diff --git a/apps/web/src/components/sidebar/SidebarDraftBlock.tsx b/apps/web/src/components/sidebar/SidebarDraftBlock.tsx index e0b0d92a764ac..6c41c20838775 100644 --- a/apps/web/src/components/sidebar/SidebarDraftBlock.tsx +++ b/apps/web/src/components/sidebar/SidebarDraftBlock.tsx @@ -19,7 +19,6 @@ import { cn } from "~/lib/utils"; import { useTerminalLabelsByThreadKey } from "~/state/terminalSessions"; import { resolveSidebarRowAccessibility } from "../Sidebar.logic"; import { ProjectFavicon, type ProjectFaviconProject } from "../ProjectFavicon"; -import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { composerDraftHasUserContent, DraftId, @@ -33,6 +32,7 @@ import { JUMP_HINT_SLOT_CLASS_NAME, JumpHintBadge, } from "./SidebarThreadRow"; +import { SharedTooltipTrigger } from "../ui/shared-tooltip"; const EMPTY_COMPOSER_PARTS = { prompt: "", @@ -170,23 +170,23 @@ const SidebarDraftRow = memo(function SidebarDraftRow(props: { props.jumpLabel && JUMP_HINT_SLOT_CLASS_NAME, )} > - - - - - } - /> - - Discard draft - - + + + + } + label={ + <> + Discard draft + + } + /> {props.jumpLabel ? : null} diff --git a/apps/web/src/components/sidebar/SidebarProjectFolderHeader.tsx b/apps/web/src/components/sidebar/SidebarProjectFolderHeader.tsx index 7ebda48e5b89a..8c4f6131dff6a 100644 --- a/apps/web/src/components/sidebar/SidebarProjectFolderHeader.tsx +++ b/apps/web/src/components/sidebar/SidebarProjectFolderHeader.tsx @@ -12,7 +12,7 @@ import { useUiStateStore } from "../../uiStateStore"; import { resolveSidebarFolderDot, resolveThreadLastVisitedAt } from "../Sidebar.logic"; import { ProjectFavicon } from "../ProjectFavicon"; import { Button } from "../ui/button"; -import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; +import { SharedTooltipTrigger } from "../ui/shared-tooltip"; const FOLDER_DOT_CLASS_NAME = { attention: "bg-warning", @@ -112,26 +112,26 @@ export const SidebarProjectFolderHeader = memo(function SidebarProjectFolderHead {/* Sits over the count, which hides on hover or focus, and left of the chevron. */} - - props.onNewThread(group)} - /> - } - > - - - - - New thread in {group.displayName} - - - + props.onNewThread(group)} + /> + } + label={ + <> + + New thread in {group.displayName} + + + } + > + + ); diff --git a/apps/web/src/components/sidebar/SidebarProviderUpdatePill.tsx b/apps/web/src/components/sidebar/SidebarProviderUpdatePill.tsx index 5ca319587792d..674e3b04b72c0 100644 --- a/apps/web/src/components/sidebar/SidebarProviderUpdatePill.tsx +++ b/apps/web/src/components/sidebar/SidebarProviderUpdatePill.tsx @@ -11,7 +11,7 @@ import { getProviderUpdateSidebarPillView, type ProviderUpdateSidebarPillView, } from "../ProviderUpdateLaunchNotification.logic"; -import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; +import { SharedTooltipTrigger } from "../ui/shared-tooltip"; // Matches the pill's `duration-180` class. const PROVIDER_UPDATE_PILL_EXIT_MS = 180; @@ -172,49 +172,47 @@ export function SidebarProviderUpdatePill() { /> ) : null}
    - - + {displayedView.tone === "loading" ? ( + + ) : displayedView.tone === "success" ? ( + + ) : displayedView.tone === "error" ? ( + + ) : ( + + )} + {displayedView.title} + + } + label={displayedView.description} + /> + {displayedView.dismissible && ( + startExit(displayedView.key, null, displayedView.dismissKeys)} > - {displayedView.tone === "loading" ? ( - - ) : displayedView.tone === "success" ? ( - - ) : displayedView.tone === "error" ? ( - - ) : ( - - )} - {displayedView.title} + } + label={ + <> + Dismiss until provider status changes + + } /> - {displayedView.description} - - {displayedView.dismissible && ( - - startExit(displayedView.key, null, displayedView.dismissKeys)} - > - - - } - /> - - Dismiss until provider status changes - - )}
    ); diff --git a/apps/web/src/components/sidebar/SidebarThreadHeader.tsx b/apps/web/src/components/sidebar/SidebarThreadHeader.tsx index 185f8fc8487a5..91f7fe206d825 100644 --- a/apps/web/src/components/sidebar/SidebarThreadHeader.tsx +++ b/apps/web/src/components/sidebar/SidebarThreadHeader.tsx @@ -11,7 +11,7 @@ import { import { cn } from "~/lib/utils"; import { Button } from "../ui/button"; import { SidebarInput, SidebarMenuButton } from "../ui/sidebar"; -import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; +import { SharedTooltipTrigger } from "../ui/shared-tooltip"; export interface SidebarThreadHeaderProps { hasProjects: boolean; @@ -142,25 +142,23 @@ export function SidebarHeaderIconButton({ "children" | "className" | "tooltip" | "isActive" | "aria-label" >) { return ( - - - } - > - {children} - - - {tooltip} - + } + label={tooltip} + > + {children} + +
    ); } diff --git a/apps/web/src/components/sidebar/SidebarThreadRow.tsx b/apps/web/src/components/sidebar/SidebarThreadRow.tsx index dcc7f6983084b..635d6acabfc32 100644 --- a/apps/web/src/components/sidebar/SidebarThreadRow.tsx +++ b/apps/web/src/components/sidebar/SidebarThreadRow.tsx @@ -1,6 +1,6 @@ import { useAtomMount, useAtomValue } from "@effect/atom-react"; import { asLaunchingThread } from "@t3tools/client-runtime/state/thread-inbox"; -import { ThreadHoverCard, ThreadHoverCardPopup } from "../ThreadHoverCard"; +import { ThreadHoverCard, ThreadHoverCardTrigger } from "../ThreadHoverCard"; import { ThreadTerminalStatusButton } from "../ThreadStatusIndicators"; import { discardComposerDraft } from "../../lib/discardComposerDraft"; import { formatWorktreePathForDisplay } from "../../worktreeCleanup"; @@ -132,7 +132,7 @@ import { useThreadRunningTerminalIds } from "../../state/terminalSessions"; import { InlineButton } from "../ui/button"; import { Kbd } from "../ui/kbd"; import { Menu, MenuItem, MenuItemDetail, MenuPopup, MenuSeparator, MenuTrigger } from "../ui/menu"; -import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; +import { SharedTooltipTrigger } from "../ui/shared-tooltip"; import { MiddleTruncate } from "../ui/middle-truncate"; import { ActivityShimmerOverlay } from "../chat/TimelineRowParts"; import { observeVisibleAnimation } from "~/lib/visibleAnimation"; @@ -163,14 +163,16 @@ function compactSidebarTimeLabel(timestamp: string, nowMs: number, resolve: Mess function PendingSyncLabel() { return ( - - }> - Pending - - - Waiting to sync with its environment - - + } + label={ + <> + Waiting to sync with its environment + + } + > + Pending + ); } @@ -314,7 +316,7 @@ function SidebarThreadTooltip({ const gt = useGT(); const m = useMessages(); return ( - + <> ) : null} - + ); } @@ -439,28 +441,28 @@ function SnoozeMenuButton(props: { : []; return (
    - - event.stopPropagation()} - onDoubleClick={(event) => event.stopPropagation()} - className="inline-flex h-full cursor-pointer items-center gap-0.5 rounded-md bg-transparent px-1.5 text-xs text-muted-foreground hover:text-foreground" - /> - } - /> - } - > - - - - Snooze thread - - + event.stopPropagation()} + onDoubleClick={(event) => event.stopPropagation()} + className="inline-flex h-full cursor-pointer items-center gap-0.5 rounded-md bg-transparent px-1.5 text-xs text-muted-foreground hover:text-foreground" + /> + } + /> + } + label={ + <> + Snooze thread + + } + > + + {presets.map((preset) => ( ); const draftIndicator = hasUnsentDraft ? ( - - - } - > - - - - Unsent draft - - + + } + label={ + <> + Unsent draft + + } + > + + ) : null; const showPin = props.isPinned && (!sortable?.isDragging || (props.dragOverPinned && props.dropVerb === null)); const pinIndicator = showPin ? ( props.pinningSupported && canOperateThread && !sortable?.isDragging ? ( - - - } - > - - - - - Unpin thread - - + } + label={ + <> + Unpin thread + + } + > + + + ) : ( - - + } + > + {/* `contents` keeps one-line rows a single flex row. */} +
    + {inFolder ? null : ( + - } - > - {/* `contents` keeps one-line rows a single flex row. */} -
    - {inFolder ? null : ( - - {props.project ? ( - - ) : null} - - )} - {draftIndicator} - {title} - {multiline ? titleLineIcons : null} - {pinIndicator} - {multiline ? null : terminalStatusIcon} - {multiline ? null : issueBadge} - {isRegeneratingTitle ? ( - - Regenerating title - - ) : null} - {sortable?.isDragging ? ( - dragDestination - ) : ( + > + {props.project ? ( + + ) : null} + + )} + {draftIndicator} + {title} + {multiline ? titleLineIcons : null} + {pinIndicator} + {multiline ? null : terminalStatusIcon} + {multiline ? null : issueBadge} + {isRegeneratingTitle ? ( + + Regenerating title + + ) : null} + {sortable?.isDragging ? ( + dragDestination + ) : ( + - - {pendingSync ? ( - - - - ) : variantAction === "unsnooze" && props.snoozeWakeLabelText !== null ? ( - - {/* The clock tells a wake time from an age at a glance. */} - - {props.snoozeWakeLabelText} - - ) : (inFolder ? isWokeStatus : isWoke) ? ( - - - - - Woke - - - } - /> - + {pendingSync ? ( + + + + ) : variantAction === "unsnooze" && props.snoozeWakeLabelText !== null ? ( + + {/* The clock tells a wake time from an age at a glance. */} + + {props.snoozeWakeLabelText} + + ) : (inFolder ? isWokeStatus : isWoke) ? ( + + + + Woke + + + } + label={ + <> Dismiss Woke notification - - - ) : inFolder && topStatus ? ( - // Folder rows have no status line, so the status takes the time slot. - - - {topStatus.label} - - ) : ( - - - - )} - - {variantAction === "unsnooze" ? ( - !props.snoozeSupported ? null : ( + + } + /> + ) : inFolder && topStatus ? ( + // Folder rows have no status line, so the status takes the time slot. + + + {topStatus.label} + + ) : ( + + + + )} + + {variantAction === "unsnooze" ? ( + !props.snoozeSupported ? null : ( + + ) + ) : !props.settlementSupported ? null : variantAction === "unsettle" ? ( + - - - ) - ) : !props.settlementSupported ? null : variantAction === "unsettle" ? ( - - - } - > - - - + /> + } + label={ + <> Un-settle thread - - - ) : ( - - - } - > - - - + + } + > + + + ) : ( + + } + label={ + <> Settle thread - - - )} - {jumpHintLabel ? : null} - - )} - {props.sweepAction !== null ? dragDestination : null} -
    - {multiline ? metaLine : null} - - {detailsTooltip} - + + } + > + + + )} + {jumpHintLabel ? : null} +
    + )} + {props.sweepAction !== null ? dragDestination : null} +
    + {multiline ? metaLine : null} + ); } @@ -1551,209 +1552,208 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP sortable?.isDragging && "relative z-20", )} > - - - } - > + -
    - {draftIndicator} - {props.project ? ( - - ) : null} - {/* Left of the status slot, the pin would slide when hover swaps the + ref={rowRef} + role="button" + tabIndex={0} + data-sidebar-row={threadKey} + data-sidebar-parent={props.navigationParent} + aria-label={accessibility.label} + aria-current={accessibility.current} + data-testid="sidebar-row-card" + aria-busy={isRegeneratingTitle || undefined} + className={rowSurfaceClassName} + onClick={handleClick} + onPointerEnter={intentPrefetch.onPointerEnter} + onPointerLeave={intentPrefetch.onPointerLeave} + onPointerDown={intentPrefetch.onPointerDown} + onDoubleClick={handleDoubleClick} + onKeyDown={handleKeyDown} + onContextMenu={handleContextMenu} + /> + } + > +
    +
    + {draftIndicator} + {props.project ? ( + + ) : null} + {/* Left of the status slot, the pin would slide when hover swaps the label for the wider row controls. */} - {pinIndicator} - {props.projectDisplayName ? ( - - {props.projectDisplayName} - - ) : ( - - )} - {sortable?.isDragging ? ( - dragDestination - ) : ( + {pinIndicator} + {props.projectDisplayName ? ( + + {props.projectDisplayName} + + ) : ( + + )} + {sortable?.isDragging ? ( + dragDestination + ) : ( + + {pendingSync ? ( + + ) : topStatus ? ( + isWokeStatus ? ( + + + {topStatus.label} + + } + label={ + <> + Dismiss Woke notification + + } + /> + ) : ( + + + {/* Not a live region: a collapsed sidebar is inert, so + BackgroundThreadAnnouncer and the open thread's + timeline speak status changes instead. */} + {topStatus.label} + {status === "preparing" || status === "working" ? ( + + + + ) : status === "waiting" ? ( + + + + ) : null} + + ) + ) : ( + + )} + + {props.settlementSupported || showSnoozeButton || hasUnsentDraft ? ( - {pendingSync ? ( - - ) : topStatus ? ( - isWokeStatus ? ( - - - - {topStatus.label} - - } + {hasUnsentDraft ? ( + - - Dismiss Woke notification - - - ) : ( - - - {/* Not a live region: a collapsed sidebar is inert, so - BackgroundThreadAnnouncer and the open thread's - timeline speak status changes instead. */} - {topStatus.label} - {status === "preparing" || status === "working" ? ( - - - - ) : status === "waiting" ? ( - - - - ) : null} - - ) - ) : ( - - )} - - {props.settlementSupported || showSnoozeButton || hasUnsentDraft ? ( - - {hasUnsentDraft ? ( - - - } - > - - - + } + label={ + <> Discard draft - - - ) : null} - {showSnoozeButton ? ( - - ) : null} - {props.settlementSupported ? ( - - - } - > - - Settle - - + + } + > + + + ) : null} + {showSnoozeButton ? ( + + ) : null} + {props.settlementSupported ? ( + + } + label={ + <> Settle thread - - - ) : null} - - ) : null} - {jumpHintLabel ? : null} - - )} - {props.sweepAction !== null ? dragDestination : null} -
    -
    - {title} - {isRegeneratingTitle ? ( - - Regenerating title - - ) : null} - {titleLineIcons} -
    - {metaLine} + + } + > + + Settle + + ) : null} + + ) : null} + {jumpHintLabel ? : null} + + )} + {props.sweepAction !== null ? dragDestination : null}
    - - {detailsTooltip} - +
    + {title} + {isRegeneratingTitle ? ( + + Regenerating title + + ) : null} + {titleLineIcons} +
    + {metaLine} +
    +
    ); }); @@ -1875,120 +1875,118 @@ export const SidebarSearchResultRow = memo(function SidebarSearchResultRow(props className="list-none" {...fileDropHandlers} > - - { - dragListeners?.onPointerDown?.(event); - event.preventDefault(); - }} - onClick={props.onSelect} - onContextMenu={(event) => { - event.preventDefault(); - props.onContextMenu( - threadRef, - { x: event.clientX, y: event.clientY }, - contextMenuSourceOf(event), - ); - }} - className={cn( - "group/sidebar-row group/v2-row flex min-h-9 w-full cursor-pointer items-center gap-2.5 rounded-md px-2.5 py-1 text-left text-sm outline-none", - props.isHighlighted || props.isRouteActive - ? "bg-sidebar-row-active text-sidebar-foreground" - : "text-sidebar-muted-foreground/75 hover:bg-sidebar-row-hover hover:text-sidebar-foreground", - isFileDragOver && "ring-1 ring-inset ring-primary/70", - isFileDragOver && !props.isRouteActive && "bg-sidebar-row-hover", - )} - /> - } - > - {props.project ? ( - + } + render={ + + + , + ); + await userEvent.keyboard("{Tab}"); + await expect.element(screen.getByRole("button", { name: "Maximize" })).toHaveFocus(); + await expect.element(page.getByText("Maximize panel")).toBeVisible(); +}); diff --git a/apps/web/src/components/usage/UsageLimits.tsx b/apps/web/src/components/usage/UsageLimits.tsx index a36b220ee3efa..0307727573947 100644 --- a/apps/web/src/components/usage/UsageLimits.tsx +++ b/apps/web/src/components/usage/UsageLimits.tsx @@ -38,10 +38,10 @@ import { AlertDialogTitle, } from "../ui/alert-dialog"; import { Button } from "../ui/button"; -import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { UsageLimitsPooled } from "./UsageLimitsPooled"; import { formatResetsIn, resetCreditChoices } from "@t3tools/shared/usageLimitsCopy"; import { PROVIDER_PRESENTATION } from "./usageProviders"; +import { SharedTooltipTrigger } from "../ui/shared-tooltip"; const PACE: Record = { ahead: { @@ -66,20 +66,18 @@ export function PaceIcon({ pace }: { readonly pace: LimitPace }) { const Icon = PACE[pace].icon; const m = useMessages(); return ( - - - } - > - - - {m(PACE[pace].label)} - + + } + label={m(PACE[pace].label)} + > + + ); } @@ -160,58 +158,58 @@ function WindowBar({ }); return ( - - + } + label={ + <> +
    + + {timeLeft !== null + ? gt("{remaining}% left · {timeLeft}% of the window left", { remaining, timeLeft }) + : gt("{remaining}% left", { remaining })} + + {timeLeft !== null ? ( + + The line is where even spending would be. + + ) : null} + {resetsAt ? ( + + {resetsIn + ? gt("Resets {resetsAt} · {resetsIn}", { resetsAt, resetsIn }) + : gt("Resets {resetsAt}", { resetsAt })} + + ) : null} +
    + + } + > + {/* Clip both layers so the gap exposes even a translucent composer surface. */} +
    +
    + {remaining > 0 ? (
    - } - > - {/* Clip both layers so the gap exposes even a translucent composer surface. */} -
    -
    - {remaining > 0 ? ( -
    - ) : null} -
    - {paceMark ? ( - ) : null} - - -
    - - {timeLeft !== null - ? gt("{remaining}% left · {timeLeft}% of the window left", { remaining, timeLeft }) - : gt("{remaining}% left", { remaining })} - - {timeLeft !== null ? ( - - The line is where even spending would be. - - ) : null} - {resetsAt ? ( - - {resetsIn - ? gt("Resets {resetsAt} · {resetsIn}", { resetsAt, resetsIn }) - : gt("Resets {resetsAt}", { resetsAt })} - - ) : null} -
    -
    - +
    + {paceMark ? ( + + ) : null} + ); } diff --git a/apps/web/src/components/usage/UsageShareBar.tsx b/apps/web/src/components/usage/UsageShareBar.tsx index 6a4e1b841f6d8..5bc35111f0701 100644 --- a/apps/web/src/components/usage/UsageShareBar.tsx +++ b/apps/web/src/components/usage/UsageShareBar.tsx @@ -1,8 +1,7 @@ import { formatPercent } from "@t3tools/shared/usageFormat"; import { useMessages } from "gt-react"; import type { ReactNode } from "react"; - -import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; +import { SharedTooltipTrigger } from "../ui/shared-tooltip"; export interface ShareSegment { readonly label: string; @@ -35,19 +34,21 @@ export function UsageShareBar({ {/* The legend below carries every figure; the bar's tooltips are pointer-only. */}
    {visible.map((segment) => ( - - - } - /> - - {m(segment.label)} · {format(segment.value)} · {formatPercent(segment.value / total)} - - + + } + label={ + <> + {m(segment.label)} · {format(segment.value)} ·{" "} + {formatPercent(segment.value / total)} + + } + /> ))}
    ); diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index 7a03418ea384d..5b4958f95a652 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -6,6 +6,7 @@ import type { ComposerAttachmentInsertion } from "../composerAttachmentInsertion import { DESKTOP_PASTE_AS_TEXT_EVENT } from "../../lib/desktopPasteAsText"; import { BackgroundThreadContext, HiddenThreadContext } from "./backgroundThread"; import { + draftRuntimeModeLimitsInstance, draftSupportedRuntimeModes, resolveCompatibleRuntimeMode, runtimeModeConfig, @@ -289,6 +290,11 @@ import { } from "./ComposerCommandMenuLayer"; import { useRestingComposerControlsLayout } from "./useRestingComposerControlsLayout"; import { useProviderWorkspaceSnapshotRefresh } from "./useProviderWorkspaceSnapshotRefresh"; +import { + RuntimeModeLimitsTargetContext, + runtimeModeLimitsTarget, + useProviderRuntimeModeLimits, +} from "../../state/runtimeModeLimits"; import { useComposerProviderModel } from "./useComposerProviderModel"; import { useComposerImageGroups } from "./useComposerImageGroups"; import { useComposerStash } from "./useComposerStash"; @@ -1001,6 +1007,12 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) // Called before the derivation below: a hook between it and its uses stops React Compiler // from caching the mode options, and the footer then re-renders on every keystroke. const managedPolicy = useManagedPolicy(environmentId); + const runtimeModeLimitsFor = runtimeModeLimitsTarget( + environmentId, + draftRuntimeModeLimitsInstance(selectedProviderEntry?.instanceId, multipleModelSelections), + gitCwd, + ); + const runtimeModeLimits = useProviderRuntimeModeLimits(runtimeModeLimitsFor); const { modes: compatibleRuntimeModes, mode: compatibleRuntimeMode } = resolveCompatibleRuntimeMode( runtimeMode, @@ -1010,11 +1022,13 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) providerStatuses, ), ); - // Modes above an administrator's ceiling stay listed, disabled with the reason. + // Modes above an administrator's ceiling, or that the provider cannot run in this folder, + // stay listed, disabled with the reason. const compatibleRuntimeModeOptions = resolveRuntimeModeOptions( compatibleRuntimeModes, managedPolicy, m, + runtimeModeLimits, ); // A thread or draft already above the ceiling would be refused; offer the broadest mode left. const runtimeModeCeilingDenial = runtimeModeDenial(managedPolicy, compatibleRuntimeMode, m); @@ -2691,53 +2705,55 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) ? 0 : expandedControlsIconOnlyBlockCount; const composerControls = ( - + + + ); // An open question owns the space above the composer. Only a machine problem, // which is why an answer could not go through, stays beside it. diff --git a/apps/web/src/components/chat/ComposerFooterControls.tsx b/apps/web/src/components/chat/ComposerFooterControls.tsx index e8cd9134e2a9a..e49005753287b 100644 --- a/apps/web/src/components/chat/ComposerFooterControls.tsx +++ b/apps/web/src/components/chat/ComposerFooterControls.tsx @@ -1,7 +1,7 @@ import type { ModelSelection, ProviderInstanceId, RuntimeMode } from "@t3tools/contracts"; import { createModelSelection } from "@t3tools/shared/model"; import { T, useGT, useMessages } from "gt-react"; -import { type ComponentProps, memo, useId, useRef, useState } from "react"; +import { type ComponentProps, memo, use, useId, useRef, useState } from "react"; import { Menu as MenuPrimitive } from "@base-ui/react/menu"; import { Menu, MenuPopup, MenuTrigger } from "../ui/menu"; @@ -13,6 +13,10 @@ import { resolveModelPickerSelectedModel } from "./ModelPickerContent"; import { ProviderModelPicker } from "./ProviderModelPicker"; import { resolveRuntimeModeOption, runtimeModeConfig } from "./runtimeModeConfig"; import { useComposerMenuState } from "./useComposerMenuState"; +import { + RuntimeModeLimitsTargetContext, + useProviderRuntimeModeLimits, +} from "../../state/runtimeModeLimits"; export type RuntimeModeOption = { mode: RuntimeMode; @@ -118,6 +122,8 @@ export function ComposerPermissionsSection(props: { props.runtimeModeOptions.find((option) => option.mode === shownMode) ?? resolveRuntimeModeOption("approval-required", messages); const descriptionId = useId(); + // Mounted only while a picker is open, so this asks the server again each time one opens. + useProviderRuntimeModeLimits(use(RuntimeModeLimitsTargetContext), "picker"); return (
    diff --git a/apps/web/src/components/chat/ComposerPermissionsSection.browser.test.tsx b/apps/web/src/components/chat/ComposerPermissionsSection.browser.test.tsx index d16b3cdd45011..44f24f6dbc272 100644 --- a/apps/web/src/components/chat/ComposerPermissionsSection.browser.test.tsx +++ b/apps/web/src/components/chat/ComposerPermissionsSection.browser.test.tsx @@ -189,6 +189,8 @@ function ContextPermissions() { environmentId={null} runtimeMode={mode} supportedRuntimeModes={["approval-required", "full-access"]} + instanceId={undefined} + cwd={null} onRuntimeModeChange={setMode} /> ); diff --git a/apps/web/src/components/chat/runtimeModeConfig.test.ts b/apps/web/src/components/chat/runtimeModeConfig.test.ts index 580fe7e43a268..2a9ed985e6cff 100644 --- a/apps/web/src/components/chat/runtimeModeConfig.test.ts +++ b/apps/web/src/components/chat/runtimeModeConfig.test.ts @@ -1,6 +1,12 @@ import { describe, expect, it } from "vite-plus/test"; -import { draftSupportedRuntimeModes, resolveCompatibleRuntimeMode } from "./runtimeModeConfig"; +import { + draftRuntimeModeLimitsInstance, + draftSupportedRuntimeModes, + resolveCompatibleRuntimeMode, + resolveRuntimeModeOptions, + runtimeModeOptions, +} from "./runtimeModeConfig"; describe("draftSupportedRuntimeModes", () => { const supervisedOnly = { @@ -31,3 +37,32 @@ describe("draftSupportedRuntimeModes", () => { expect(resolveCompatibleRuntimeMode("auto", modes).mode).toBe("approval-required"); }); }); + +describe("draftRuntimeModeLimitsInstance", () => { + const claude = { instanceId: "claude" }; + const codex = { instanceId: "codex" }; + + it.each([ + { label: "no multi-model selection", selections: null, expected: "active" }, + { label: "an empty multi-model selection", selections: [], expected: "active" }, + { label: "one selected model", selections: [claude], expected: "claude" }, + { label: "models that share one provider", selections: [claude, claude], expected: "claude" }, + { label: "models on different providers", selections: [claude, codex], expected: undefined }, + ])("checks the limits of the provider every thread uses: $label", ({ selections, expected }) => { + expect(draftRuntimeModeLimitsInstance("active", selections)).toBe(expected); + }); +}); + +describe("resolveRuntimeModeOptions", () => { + it("keeps a mode the provider cannot run in this folder listed, disabled with the reason", () => { + const options = resolveRuntimeModeOptions(runtimeModeOptions, undefined, undefined, [ + { mode: "auto", reason: "project-settings" }, + ]); + expect(options.map((option) => [option.mode, option.disabledReason])).toEqual([ + ["approval-required", undefined], + ["auto-accept-edits", undefined], + ["auto", "This project's Claude settings turn auto mode off."], + ["full-access", undefined], + ]); + }); +}); diff --git a/apps/web/src/components/chat/runtimeModeConfig.ts b/apps/web/src/components/chat/runtimeModeConfig.ts index 89655258ff935..0e0506aed42ef 100644 --- a/apps/web/src/components/chat/runtimeModeConfig.ts +++ b/apps/web/src/components/chat/runtimeModeConfig.ts @@ -1,5 +1,12 @@ -import { managedRuntimeModeDenial } from "@t3tools/client-runtime/contract-labels"; -import type { ManagedPolicySummary, RuntimeMode } from "@t3tools/contracts"; +import { + managedRuntimeModeDenial, + providerRuntimeModeLimitMessage, +} from "@t3tools/client-runtime/contract-labels"; +import type { + ManagedPolicySummary, + ProviderRuntimeModeLimit, + RuntimeMode, +} from "@t3tools/contracts"; import { msg } from "gt-react"; import { m, type MessageResolver } from "~/i18n/messages"; import { @@ -76,6 +83,21 @@ export function draftSupportedRuntimeModes( return runtimeModeOptions.filter((mode) => supported.some((modes) => modes.includes(mode))); } +/** + * The provider whose folder limits a draft's send is under: the one every thread it starts will + * use. Selected models on different providers share none, so no one provider's limits apply. + */ +export function draftRuntimeModeLimitsInstance( + activeInstanceId: InstanceId | undefined, + multipleModelSelections: ReadonlyArray<{ readonly instanceId: InstanceId }> | null, +): InstanceId | undefined { + const first = multipleModelSelections?.[0]; + if (multipleModelSelections === null || first === undefined) return activeInstanceId; + return multipleModelSelections.every((selection) => selection.instanceId === first.instanceId) + ? first.instanceId + : undefined; +} + export function resolveRuntimeModeOption( mode: RuntimeMode, resolve: MessageResolver = m, @@ -113,14 +135,21 @@ export function runtimeModeDenial( ); } +/** + * `limits` are modes the provider cannot run in the current folder. They stay listed, disabled + * with the reason; a thread already in one keeps it and shows that reason as its description. + */ export function resolveRuntimeModeOptions( modes: ReadonlyArray, managedPolicy: ManagedPolicySummary | undefined, resolve: MessageResolver = m, + limits?: ReadonlyArray, ) { return modes.map((mode) => { const option = resolveRuntimeModeOption(mode, resolve); - const disabledReason = runtimeModeDenial(managedPolicy, mode, resolve); + const disabledReason = + runtimeModeDenial(managedPolicy, mode, resolve) ?? + providerRuntimeModeLimitMessage(limits, mode, resolve); return disabledReason === undefined ? option : { ...option, disabledReason }; }); } diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index bb4dbf0d19202..13f9761acd54a 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -20,6 +20,10 @@ "2aa1c01bf8014725": "{organization} beschränkt Threads auf „Änderungen automatisch annehmen“.", "89563a8fff8bb751": "{organization} beschränkt Threads auf „Auto“.", "5b7ff1208620c2c2": "{organization} beschränkt Threads auf „Vollzugriff“.", + "069e0382ff2496f5": "Die Claude-Einstellungen deiner Organisation schalten den Auto-Modus ab.", + "8ccf7e0def66d339": "Deine Claude-Einstellungen schalten den Auto-Modus ab.", + "04ac2410d2cc0666": "Die Claude-Einstellungen dieses Projekts schalten den Auto-Modus ab.", + "7e27789f5d58960e": "Die Claude-Einstellungen schalten den Auto-Modus ab.", "9bf017edd3847eb1": "Die Richtlinie von {organization} erlaubt keine Verbindungen von anderen Geräten.", "ef9533bcc048f17b": "Die Richtlinie von {organization} erlaubt T3 Connect nicht.", "986b0873f913a840": "Die Richtlinie von {organization} erlaubt keine Webhook-Aufgaben.", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index 1a4cf83185001..1a9d8cf9ec836 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -20,6 +20,10 @@ "2aa1c01bf8014725": "{organization} limits threads to Auto-accept edits.", "89563a8fff8bb751": "{organization} limits threads to Auto.", "5b7ff1208620c2c2": "{organization} limits threads to Full access.", + "069e0382ff2496f5": "Your organization's Claude settings turn auto mode off.", + "8ccf7e0def66d339": "Your Claude settings turn auto mode off.", + "04ac2410d2cc0666": "This project's Claude settings turn auto mode off.", + "7e27789f5d58960e": "Claude's settings turn auto mode off.", "9bf017edd3847eb1": "{organization}'s policy does not allow connecting from other devices.", "ef9533bcc048f17b": "{organization}'s policy does not allow T3 Connect.", "986b0873f913a840": "{organization}'s policy does not allow webhook tasks.", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index 3741d30788810..183fd2a80ac4b 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -20,6 +20,10 @@ "2aa1c01bf8014725": "{organization} limita los hilos a Aceptar ediciones automáticamente.", "89563a8fff8bb751": "{organization} limita los hilos a Automático.", "5b7ff1208620c2c2": "{organization} limita los hilos a Acceso total.", + "069e0382ff2496f5": "La configuración de Claude de tu organización desactiva el modo automático.", + "8ccf7e0def66d339": "Tu configuración de Claude desactiva el modo automático.", + "04ac2410d2cc0666": "La configuración de Claude de este proyecto desactiva el modo automático.", + "7e27789f5d58960e": "La configuración de Claude desactiva el modo automático.", "9bf017edd3847eb1": "La política de {organization} no permite conectarse desde otros dispositivos.", "ef9533bcc048f17b": "La política de {organization} no permite T3 Connect.", "986b0873f913a840": "La política de {organization} no permite tareas de webhook.", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index 1c60b0470df31..cfb8f6aa14bc2 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -20,6 +20,10 @@ "2aa1c01bf8014725": "{organization} limite les fils au mode Acceptation auto des modifications.", "89563a8fff8bb751": "{organization} limite les fils au mode Auto.", "5b7ff1208620c2c2": "{organization} limite les fils au mode Accès complet.", + "069e0382ff2496f5": "Les paramètres Claude de votre organisation désactivent le mode Auto.", + "8ccf7e0def66d339": "Vos paramètres Claude désactivent le mode Auto.", + "04ac2410d2cc0666": "Les paramètres Claude de ce projet désactivent le mode Auto.", + "7e27789f5d58960e": "Les paramètres de Claude désactivent le mode Auto.", "9bf017edd3847eb1": "La politique de {organization} n’autorise pas la connexion depuis d’autres appareils.", "ef9533bcc048f17b": "La politique de {organization} n’autorise pas T3 Connect.", "986b0873f913a840": "La politique de {organization} n’autorise pas les tâches webhook.", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index f98ef7e93260f..f508c1e438dd7 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -20,6 +20,10 @@ "2aa1c01bf8014725": "{organization} により、スレッドは「編集を自動承認」に制限されています。", "89563a8fff8bb751": "{organization} により、スレッドは「自動」に制限されています。", "5b7ff1208620c2c2": "{organization} により、スレッドは「フルアクセス」に制限されています。", + "069e0382ff2496f5": "組織の Claude 設定で自動モードが無効になっています。", + "8ccf7e0def66d339": "あなたの Claude 設定で自動モードが無効になっています。", + "04ac2410d2cc0666": "このプロジェクトの Claude 設定で自動モードが無効になっています。", + "7e27789f5d58960e": "Claude の設定で自動モードが無効になっています。", "9bf017edd3847eb1": "{organization} のポリシーでは、他のデバイスからの接続は許可されていません。", "ef9533bcc048f17b": "{organization} のポリシーでは、T3 Connect は許可されていません。", "986b0873f913a840": "{organization} のポリシーでは、Webhook タスクは許可されていません。", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index 032042b111b7f..33246edd75cdb 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -20,6 +20,10 @@ "2aa1c01bf8014725": "{organization}에서 스레드를 편집 자동 수락 모드로 제한합니다.", "89563a8fff8bb751": "{organization}에서 스레드를 자동 모드로 제한합니다.", "5b7ff1208620c2c2": "{organization}에서 스레드를 전체 액세스 모드로 제한합니다.", + "069e0382ff2496f5": "조직의 Claude 설정에서 자동 모드가 꺼져 있습니다.", + "8ccf7e0def66d339": "내 Claude 설정에서 자동 모드가 꺼져 있습니다.", + "04ac2410d2cc0666": "이 프로젝트의 Claude 설정에서 자동 모드가 꺼져 있습니다.", + "7e27789f5d58960e": "Claude 설정에서 자동 모드가 꺼져 있습니다.", "9bf017edd3847eb1": "{organization}의 정책상 다른 기기에서 연결할 수 없습니다.", "ef9533bcc048f17b": "{organization}의 정책상 T3 Connect를 사용할 수 없습니다.", "986b0873f913a840": "{organization}의 정책상 웹후크 작업을 사용할 수 없습니다.", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index 307c29cf0ec4d..e32375e6581ce 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -20,6 +20,10 @@ "2aa1c01bf8014725": "{organization} limita as threads a Aceitar edições automaticamente.", "89563a8fff8bb751": "{organization} limita as threads a Auto.", "5b7ff1208620c2c2": "{organization} limita as threads a Acesso total.", + "069e0382ff2496f5": "As configurações do Claude da sua organização desativam o modo automático.", + "8ccf7e0def66d339": "Suas configurações do Claude desativam o modo automático.", + "04ac2410d2cc0666": "As configurações do Claude deste projeto desativam o modo automático.", + "7e27789f5d58960e": "As configurações do Claude desativam o modo automático.", "9bf017edd3847eb1": "A política de {organization} não permite conexões de outros dispositivos.", "ef9533bcc048f17b": "A política de {organization} não permite o T3 Connect.", "986b0873f913a840": "A política de {organization} não permite tarefas de webhook.", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 0f0d97eccea27..f6b5006a97e6e 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -20,6 +20,10 @@ "2aa1c01bf8014725": "{organization} ограничивает треды режимом «Автопринятие правок».", "89563a8fff8bb751": "{organization} ограничивает треды режимом «Авто».", "5b7ff1208620c2c2": "{organization} ограничивает треды режимом «Полный доступ».", + "069e0382ff2496f5": "Настройки Claude вашей организации отключают режим «Авто».", + "8ccf7e0def66d339": "Ваши настройки Claude отключают режим «Авто».", + "04ac2410d2cc0666": "Настройки Claude этого проекта отключают режим «Авто».", + "7e27789f5d58960e": "Настройки Claude отключают режим «Авто».", "9bf017edd3847eb1": "Политика {organization} запрещает подключение с других устройств.", "ef9533bcc048f17b": "Политика {organization} запрещает T3 Connect.", "986b0873f913a840": "Политика {organization} запрещает задачи по вебхуку.", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index f9e852760e4a0..3a78a170acb9c 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -20,6 +20,10 @@ "2aa1c01bf8014725": "{organization} begränsar trådar till Godkänn ändringar automatiskt.", "89563a8fff8bb751": "{organization} begränsar trådar till Auto.", "5b7ff1208620c2c2": "{organization} begränsar trådar till Full åtkomst.", + "069e0382ff2496f5": "Din organisations Claude-inställningar stänger av autoläget.", + "8ccf7e0def66d339": "Dina Claude-inställningar stänger av autoläget.", + "04ac2410d2cc0666": "Projektets Claude-inställningar stänger av autoläget.", + "7e27789f5d58960e": "Claudes inställningar stänger av autoläget.", "9bf017edd3847eb1": "Policyn för {organization} tillåter inte anslutning från andra enheter.", "ef9533bcc048f17b": "Policyn för {organization} tillåter inte T3 Connect.", "986b0873f913a840": "Policyn för {organization} tillåter inte webhook-uppgifter.", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index 86e48d8af0199..6a5ff6df38a45 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -20,6 +20,10 @@ "2aa1c01bf8014725": "{organization} 将会话权限限制为自动接受编辑。", "89563a8fff8bb751": "{organization} 将会话权限限制为自动。", "5b7ff1208620c2c2": "{organization} 将会话权限限制为完全访问。", + "069e0382ff2496f5": "你所在组织的 Claude 设置关闭了自动模式。", + "8ccf7e0def66d339": "你的 Claude 设置关闭了自动模式。", + "04ac2410d2cc0666": "此项目的 Claude 设置关闭了自动模式。", + "7e27789f5d58960e": "Claude 的设置关闭了自动模式。", "9bf017edd3847eb1": "{organization} 的策略不允许其他设备连接。", "ef9533bcc048f17b": "{organization} 的策略不允许使用 T3 Connect。", "986b0873f913a840": "{organization} 的策略不允许使用 webhook 任务。", diff --git a/apps/web/src/state/runtimeModeLimits.ts b/apps/web/src/state/runtimeModeLimits.ts new file mode 100644 index 0000000000000..acef03d93f555 --- /dev/null +++ b/apps/web/src/state/runtimeModeLimits.ts @@ -0,0 +1,51 @@ +import type { + EnvironmentId, + ProviderInstanceId, + ProviderRuntimeModeLimit, +} from "@t3tools/contracts"; +import { createContext } from "react"; + +import { useEnvironmentQuery } from "./query"; +import { serverEnvironment } from "./server"; + +export interface RuntimeModeLimitsTarget { + readonly environmentId: EnvironmentId; + readonly instanceId: ProviderInstanceId; + readonly cwd: string; +} + +const NO_LIMITS: ReadonlyArray = []; + +/** The folder and provider whose limits an open mode picker should check again. */ +export const RuntimeModeLimitsTargetContext = createContext(null); + +export function runtimeModeLimitsTarget( + environmentId: EnvironmentId | null, + instanceId: ProviderInstanceId | undefined, + cwd: string | null, +): RuntimeModeLimitsTarget | null { + return environmentId && instanceId && cwd ? { environmentId, instanceId, cwd } : null; +} + +/** + * Modes the provider offers that cannot run in `target`'s folder. Empty until the server + * answers and when it cannot, so a mode is only ever marked on a known reason. `mountScope` + * gives a second reader its own mount, which asks again when the answer is a few seconds old. + */ +export function useProviderRuntimeModeLimits( + target: RuntimeModeLimitsTarget | null, + mountScope?: "picker", +): ReadonlyArray { + const { data } = useEnvironmentQuery( + target === null + ? null + : serverEnvironment.providerRuntimeModeLimits( + { + environmentId: target.environmentId, + input: { instanceId: target.instanceId, cwd: target.cwd }, + }, + mountScope, + ), + ); + return data?.limits ?? NO_LIMITS; +} diff --git a/docs/user/permission-modes.md b/docs/user/permission-modes.md index a6141b91f4cf4..3078f16dbdbee 100644 --- a/docs/user/permission-modes.md +++ b/docs/user/permission-modes.md @@ -73,7 +73,9 @@ asking. Codex still asks before network access its managed network settings don' you already allowed commands for the session. In **Auto**, Claude asks you about the actions its review leaves open. Where Claude's settings turn -its Auto mode off, or the model has none, a Claude thread set to **Auto** asks like **Supervised**. +its Auto mode off, the permissions menu shows **Auto** as unavailable for that project, with whose +settings do it. A Claude thread that is set to **Auto** anyway, or whose model has no Auto mode, +asks like **Supervised** and says so once in the thread. Claude can still ask in **Full access** when its settings disable bypass permissions or require approval for an action. Dangerous-removal safety checks in bypass mode reject the command with diff --git a/docs/user/providers-claude.md b/docs/user/providers-claude.md index 00b27e02ae23d..009a237a67574 100644 --- a/docs/user/providers-claude.md +++ b/docs/user/providers-claude.md @@ -118,6 +118,12 @@ To show Claude task lists in the web and desktop apps, add **Environment** section in **Settings > Providers**. Each update shows as a Tasks row in the thread; open it to see every step. +## Auto mode + +**Auto** on a Claude thread is Claude Code's own auto mode. `disableAutoMode` in Claude's managed, +user, or project settings turns it off: T3 Code then shows **Auto** as unavailable in that project, +and a thread already set to it asks about each action. See [Permission modes](permission-modes.md). + ## Sign in to an MCP server When an MCP server you added to Claude needs you to sign in, the thread shows a notice with diff --git a/packages/client-runtime/src/contractLabels.ts b/packages/client-runtime/src/contractLabels.ts index f46bd6d12762c..767f82b35dfec 100644 --- a/packages/client-runtime/src/contractLabels.ts +++ b/packages/client-runtime/src/contractLabels.ts @@ -10,6 +10,7 @@ import { type ManagedPolicySummary, type ProjectCloneSnapshot, type ProjectCloneStage, + type ProviderRuntimeModeLimit, type RuntimeMode, type WorktreeSetupStageId, worktreeSetupStageLabel as contractsWorktreeSetupStageLabel, @@ -125,6 +126,27 @@ export function managedRuntimeModeDenial( : undefined; } +/** Why a provider cannot run `mode` in the current folder, or undefined when it can. */ +export function providerRuntimeModeLimitMessage( + limits: ReadonlyArray | undefined, + mode: RuntimeMode, + resolve: MFunctionType = mFallback, +): string | undefined { + const limit = limits?.find((candidate) => candidate.mode === mode); + if (limit === undefined) return undefined; + // Only Claude's auto mode reports limits today. + switch (limit.reason) { + case "managed-settings": + return resolve(msg("Your organization's Claude settings turn auto mode off.")); + case "user-settings": + return resolve(msg("Your Claude settings turn auto mode off.")); + case "project-settings": + return resolve(msg("This project's Claude settings turn auto mode off.")); + case "settings": + return resolve(msg("Claude's settings turn auto mode off.")); + } +} + export type ManagedCapability = | "remoteClients" | "connect" diff --git a/packages/client-runtime/src/state/server.ts b/packages/client-runtime/src/state/server.ts index a318f91b0ffbb..492a9e9268714 100644 --- a/packages/client-runtime/src/state/server.ts +++ b/packages/client-runtime/src/state/server.ts @@ -1620,6 +1620,12 @@ export function createServerEnvironmentAtoms( label: "environment-data:provider:install-remove", tag: WS_METHODS.providerInstallRemove, }), + // Short-lived so opening a mode picker shows a setting changed a moment ago. + providerRuntimeModeLimits: createEnvironmentRpcQueryAtomFamily(runtime, { + label: "environment-data:server:provider-runtime-mode-limits", + tag: WS_METHODS.serverGetProviderRuntimeModeLimits, + staleTimeMs: 5_000, + }), traceDiagnostics: createEnvironmentRpcQueryAtomFamily(runtime, { label: "environment-data:server:trace-diagnostics", tag: WS_METHODS.serverGetTraceDiagnostics, diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts index 29cea4095c2a1..f10819d20fcd5 100644 --- a/packages/contracts/src/rpc.ts +++ b/packages/contracts/src/rpc.ts @@ -383,6 +383,8 @@ import { ServerRemoveKeybindingInput, ServerRemoveKeybindingResult, ServerProviderUpdatedPayload, + ProviderRuntimeModeLimitsInput, + ProviderRuntimeModeLimitsResult, ServerSelfUpdateError, ServerNpmRelease, ServerNpmReleaseError, @@ -591,6 +593,7 @@ export const WS_METHODS = { serverGetConfig: "server.getConfig", serverGetNpmRelease: "server.getNpmRelease", serverRefreshProviders: "server.refreshProviders", + serverGetProviderRuntimeModeLimits: "server.getProviderRuntimeModeLimits", serverUpdateProvider: "server.updateProvider", serverUpdateServer: "server.updateServer", serverUpdateServerWithProgress: "server.updateServerWithProgress", @@ -812,6 +815,15 @@ export const WsServerRefreshProvidersRpc = Rpc.make(WS_METHODS.serverRefreshProv error: Schema.Union([EnvironmentAuthorizationError, ProviderSetupError]), }); +const WsServerGetProviderRuntimeModeLimitsRpc = Rpc.make( + WS_METHODS.serverGetProviderRuntimeModeLimits, + { + payload: ProviderRuntimeModeLimitsInput, + success: ProviderRuntimeModeLimitsResult, + error: EnvironmentAuthorizationError, + }, +); + const WsServerUpdateProviderRpc = Rpc.make(WS_METHODS.serverUpdateProvider, { payload: ServerProviderUpdateInput, success: ServerProviderUpdatedPayload, @@ -2551,6 +2563,7 @@ export const WsRpcGroup = RpcGroup.make( WsServerImportAcpRegistrySessionRpc, WsServerDeleteAcpRegistrySessionRpc, WsServerListAcpRegistryProvidersRpc, + WsServerGetProviderRuntimeModeLimitsRpc, WsServerSetAcpRegistryProviderRpc, WsServerDisableAcpRegistryProviderRpc, WsServerLogoutAcpRegistryRpc, diff --git a/packages/contracts/src/server.ts b/packages/contracts/src/server.ts index 68ef9c37f0386..94933a71d6e76 100644 --- a/packages/contracts/src/server.ts +++ b/packages/contracts/src/server.ts @@ -164,6 +164,34 @@ export function isProviderWorkspaceSnapshotPending( return snapshot.slashCommandsPending === true || snapshot.modelsPending === true; } +/** Whose settings keep a provider from running a mode; "settings" when the source is not known. */ +export const ProviderRuntimeModeLimitReason = Schema.Literals([ + "managed-settings", + "user-settings", + "project-settings", + "settings", +]); +export type ProviderRuntimeModeLimitReason = typeof ProviderRuntimeModeLimitReason.Type; + +/** + * A mode a provider offers that cannot run in one folder. The mode stays selectable by every + * caller; clients show it as unavailable with the reason. + */ +export const ProviderRuntimeModeLimit = Schema.Struct({ + mode: RuntimeMode, + reason: ProviderRuntimeModeLimitReason, +}); +export type ProviderRuntimeModeLimit = typeof ProviderRuntimeModeLimit.Type; + +export const ProviderRuntimeModeLimitsInput = Schema.Struct({ + instanceId: ProviderInstanceId, + cwd: TrimmedNonEmptyString, +}); +export const ProviderRuntimeModeLimitsResult = Schema.Struct({ + limits: ForwardCompatibleArray(ProviderRuntimeModeLimit), +}); +export type ProviderRuntimeModeLimitsResult = typeof ProviderRuntimeModeLimitsResult.Type; + /** Unavailable snapshots must set installed and enabled false. */ export const ServerProviderAvailability = Schema.Literals(["available", "unavailable"]); export type ServerProviderAvailability = typeof ServerProviderAvailability.Type; diff --git a/packages/provider-core/src/server/driver.ts b/packages/provider-core/src/server/driver.ts index 9bba228fcaa16..192a14978556c 100644 --- a/packages/provider-core/src/server/driver.ts +++ b/packages/provider-core/src/server/driver.ts @@ -8,6 +8,7 @@ import type { ProviderDriverKind, ResolvedProviderInstanceEnvironment, ProviderInstanceId, + ProviderRuntimeModeLimit, ServerProvider, ServerProviderWorkspaceSnapshot, } from "@t3tools/contracts"; @@ -51,6 +52,13 @@ export interface ProviderInstance { readonly snapshotForCwd?: ( cwd: string, ) => Effect.Effect; + /** + * Modes this instance offers that cannot run in `cwd`. Must stay cheap: clients ask whenever a + * mode picker opens, so read configuration and never start the provider. + */ + readonly runtimeModeLimitsForCwd?: ( + cwd: string, + ) => Effect.Effect>; /** * Cwds whose workspace skills or models may have changed. The registry rescans only cwds already * requested. The stream must end when the instance is torn down. From e75534b3e5658002b9a47c7881fa1efef9797fbd Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 25 Nov 2026 17:14:04 -0800 Subject: [PATCH 169/238] fix(web): a full prompt stash no longer discards your oldest prompt (#43183) --- .../src/components/chat/useComposerStash.ts | 40 ++++++++----------- apps/web/src/i18n/translations/de.json | 6 +-- apps/web/src/i18n/translations/en.json | 6 +-- apps/web/src/i18n/translations/es.json | 6 +-- apps/web/src/i18n/translations/fr.json | 6 +-- apps/web/src/i18n/translations/ja.json | 6 +-- apps/web/src/i18n/translations/ko.json | 6 +-- apps/web/src/i18n/translations/pt-BR.json | 6 +-- apps/web/src/i18n/translations/ru.json | 6 +-- apps/web/src/i18n/translations/sv.json | 6 +-- apps/web/src/i18n/translations/zh.json | 6 +-- apps/web/src/promptStashStore.test.ts | 11 ++--- apps/web/src/promptStashStore.ts | 22 ++++++---- docs/user/composer.md | 4 ++ 14 files changed, 70 insertions(+), 67 deletions(-) diff --git a/apps/web/src/components/chat/useComposerStash.ts b/apps/web/src/components/chat/useComposerStash.ts index 2d86d12305dcf..7fc74a9f9f02b 100644 --- a/apps/web/src/components/chat/useComposerStash.ts +++ b/apps/web/src/components/chat/useComposerStash.ts @@ -603,7 +603,7 @@ export function useComposerStash(input: { // crash or closed tab mid-encode still leaves the prompt recoverable, // while clearing before the async image work means edits typed during // encoding are not wiped. - const { evicted, written, durable } = stashEntryToQueue({ + const { full, written, durable } = stashEntryToQueue({ id: entryId, createdAt: new Date().toISOString(), prompt, @@ -615,9 +615,21 @@ export function useComposerStash(input: { ...(stashedRecords.length > 0 ? { records: stashedRecords } : {}), }); - // If it was rejected (quota) the store has already rolled itself back, - // so leave the composer untouched rather than making it the second - // casualty of a reload. + // A full or rejected write kept nothing, so leave the composer untouched. + if (full) { + toastManager.add({ + type: "warning", + title: m(msg("Stash is full")), + description: m( + msg( + "The stash holds {max} prompts. Restore or delete one to make room; the composer was left as-is.", + { max: MAX_STASH_ENTRIES }, + ), + ), + data: { hideCopyButton: true }, + }); + return; + } if (!written) { toastManager.add({ type: "error", @@ -665,26 +677,6 @@ export function useComposerStash(input: { setComposerTrigger(null); pulseStashBadge(); - if (evicted) { - for (const file of evicted.files ?? []) { - releasePersistedAttachmentUpload({ - id: file.id, - environmentId: file.environmentId, - attachmentId: file.attachmentId, - }); - } - toastManager.add({ - type: "warning", - title: m(msg("Oldest stashed prompt discarded")), - description: m( - msg("The stash holds {max} prompts; the oldest was removed to make room.", { - max: MAX_STASH_ENTRIES, - }), - ), - data: { hideCopyButton: true }, - }); - } - // Images are re-encoded for the stash rather than stored verbatim: the // composer allows up to 10MB per image, but localStorage gives the whole // origin ~5MB. diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 13f9761acd54a..f2107901d0e26 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -4939,8 +4939,6 @@ "3f5c37167aa5034f": "Der Browserspeicher hat das Schreiben abgelehnt, daher wurde das Eingabefeld unverändert gelassen. Gib Websitedaten frei und versuche es erneut.", "41ba6c0b5c5e8b22": "Abgelegter Prompt übersteht kein Neuladen", "94d7f150b3f7b291": "Der Browserspeicher ist nicht verfügbar, daher wird diese Ablage nur für diese Sitzung im Arbeitsspeicher gehalten.", - "f421c24666cd8c71": "Ältester abgelegter Prompt verworfen", - "1123f816ea2a6e3e": "Die Ablage fasst {max} Prompts; der älteste wurde entfernt, um Platz zu schaffen.", "c3a8f9b1b2e7d588": "Abgelegte Bilder wurden nicht gespeichert", "fc3feba263971bce": "Der Prompt wurde abgelegt, aber der Browserspeicher hat seine Bilder abgelehnt. Sie fehlen, wenn du neu lädst.", "9e36559d0fa0cca8": "Abgelegte Bilder wurden nicht angehängt", @@ -12990,5 +12988,7 @@ "99451a5d2d40440f": "Zurückgezogen von {by}.", "3ee30a50b70fffab": "Zurückgezogen von {by}: {reason}", "92e129bf413a1220": "zurückgezogen", - "800966eb58181745": "Prüfe, welche Sprachen das Modell unterstützt…" + "800966eb58181745": "Prüfe, welche Sprachen das Modell unterstützt…", + "410dded6e21c280d": "Ablage ist voll", + "1af8d12ac21cb183": "Die Ablage fasst {max} Prompts. Stelle einen wieder her oder lösche einen, um Platz zu schaffen; das Eingabefeld wurde unverändert gelassen." } diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index 1a9d8cf9ec836..2226a137fbf33 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -4938,8 +4938,6 @@ "3f5c37167aa5034f": "Browser storage rejected the write, so the composer was left as-is. Free up site data and try again.", "41ba6c0b5c5e8b22": "Stashed prompt will not survive a reload", "94d7f150b3f7b291": "Browser storage is unavailable, so this stash is kept in memory only for this session.", - "f421c24666cd8c71": "Oldest stashed prompt discarded", - "1123f816ea2a6e3e": "The stash holds {max} prompts; the oldest was removed to make room.", "c3a8f9b1b2e7d588": "Stashed images were not saved", "fc3feba263971bce": "The prompt was stashed, but browser storage rejected its images. They will be missing if you reload.", "9e36559d0fa0cca8": "Stashed images did not attach", @@ -12999,5 +12997,7 @@ "99451a5d2d40440f": "Withdrawn by {by}.", "3ee30a50b70fffab": "Withdrawn by {by}: {reason}", "92e129bf413a1220": "withdrawn", - "800966eb58181745": "Checking which languages the model supports…" + "800966eb58181745": "Checking which languages the model supports…", + "410dded6e21c280d": "Stash is full", + "1af8d12ac21cb183": "The stash holds {max} prompts. Restore or delete one to make room; the composer was left as-is." } diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index 183fd2a80ac4b..0eda6769c881f 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -4936,8 +4936,6 @@ "3f5c37167aa5034f": "El almacenamiento del navegador rechazó la escritura, así que el cuadro de mensaje se quedó como estaba. Libera datos del sitio y vuelve a intentarlo.", "41ba6c0b5c5e8b22": "El prompt del stash no sobrevivirá a una recarga", "94d7f150b3f7b291": "El almacenamiento del navegador no está disponible, así que este stash solo se guarda en memoria durante esta sesión.", - "f421c24666cd8c71": "Se descartó el prompt más antiguo del stash", - "1123f816ea2a6e3e": "El stash admite {max} prompts; se quitó el más antiguo para hacer sitio.", "c3a8f9b1b2e7d588": "Las imágenes del stash no se guardaron", "fc3feba263971bce": "El prompt se guardó en el stash, pero el almacenamiento del navegador rechazó sus imágenes. Faltarán si recargas.", "9e36559d0fa0cca8": "Las imágenes del stash no se adjuntaron", @@ -12985,5 +12983,7 @@ "99451a5d2d40440f": "Retirada por {by}.", "3ee30a50b70fffab": "Retirada por {by}: {reason}", "92e129bf413a1220": "retirada", - "800966eb58181745": "Comprobando qué idiomas admite el modelo…" + "800966eb58181745": "Comprobando qué idiomas admite el modelo…", + "410dded6e21c280d": "El stash está lleno", + "1af8d12ac21cb183": "El stash admite {max} prompts. Restaura o elimina uno para hacer sitio; el campo de texto se dejó como estaba." } diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index cfb8f6aa14bc2..0633348ff404e 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -4937,8 +4937,6 @@ "3f5c37167aa5034f": "Le stockage du navigateur a refusé l’écriture ; la zone de saisie a donc été laissée telle quelle. Libérez des données de site et réessayez.", "41ba6c0b5c5e8b22": "Le prompt mis de côté ne survivra pas à un rechargement", "94d7f150b3f7b291": "Le stockage du navigateur est indisponible ; cette réserve est donc gardée en mémoire pour cette session uniquement.", - "f421c24666cd8c71": "Le plus ancien prompt mis de côté a été supprimé", - "1123f816ea2a6e3e": "La réserve contient {max} prompts ; le plus ancien a été supprimé pour faire de la place.", "c3a8f9b1b2e7d588": "Les images mises de côté n’ont pas été enregistrées", "fc3feba263971bce": "Le prompt a été mis de côté, mais le stockage du navigateur a refusé ses images. Elles manqueront si vous rechargez.", "9e36559d0fa0cca8": "Les images mises de côté n’ont pas été jointes", @@ -12990,5 +12988,7 @@ "99451a5d2d40440f": "Retirée par {by}.", "3ee30a50b70fffab": "Retirée par {by} : {reason}", "92e129bf413a1220": "retirée", - "800966eb58181745": "Vérification des langues prises en charge par le modèle…" + "800966eb58181745": "Vérification des langues prises en charge par le modèle…", + "410dded6e21c280d": "La réserve est pleine", + "1af8d12ac21cb183": "La réserve contient {max} prompts. Restaurez-en ou supprimez-en un pour faire de la place ; la zone de saisie a été laissée telle quelle." } diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index f508c1e438dd7..f906439530d57 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -4925,8 +4925,6 @@ "3f5c37167aa5034f": "ブラウザーのストレージが書き込みを拒否したため、入力欄はそのままです。サイトのデータを空けて、もう一度お試しください。", "41ba6c0b5c5e8b22": "退避したプロンプトは再読み込みすると失われます", "94d7f150b3f7b291": "ブラウザーのストレージを利用できないため、この退避はこのセッションの間だけメモリに保持されます。", - "f421c24666cd8c71": "最も古い退避したプロンプトを破棄しました", - "1123f816ea2a6e3e": "退避できるプロンプトは {max} 件までです。空きを作るため、最も古いものを削除しました。", "c3a8f9b1b2e7d588": "退避した画像は保存されませんでした", "fc3feba263971bce": "プロンプトは退避されましたが、ブラウザーのストレージが画像を拒否しました。再読み込みすると画像は失われます。", "9e36559d0fa0cca8": "退避した画像は添付されませんでした", @@ -12926,5 +12924,7 @@ "99451a5d2d40440f": "{by} が取り下げました。", "3ee30a50b70fffab": "{by} が取り下げました: {reason}", "92e129bf413a1220": "取り下げ済み", - "800966eb58181745": "モデルが対応している言語を確認しています…" + "800966eb58181745": "モデルが対応している言語を確認しています…", + "410dded6e21c280d": "退避がいっぱいです", + "1af8d12ac21cb183": "退避できるプロンプトは {max} 件までです。空きを作るには、どれかを復元するか削除してください。入力欄はそのままにしてあります。" } diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index 33246edd75cdb..035647987a74c 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -4922,8 +4922,6 @@ "3f5c37167aa5034f": "브라우저 저장소가 쓰기를 거부해서 입력창을 그대로 두었습니다. 사이트 데이터를 정리한 후 다시 시도하세요.", "41ba6c0b5c5e8b22": "임시 저장한 프롬프트는 새로 고치면 사라집니다", "94d7f150b3f7b291": "브라우저 저장소를 사용할 수 없어 이 임시 저장함은 이번 세션 동안 메모리에만 유지됩니다.", - "f421c24666cd8c71": "가장 오래된 임시 저장 프롬프트 삭제됨", - "1123f816ea2a6e3e": "임시 저장함에는 프롬프트를 {max}개까지 저장할 수 있어 가장 오래된 항목을 삭제했습니다.", "c3a8f9b1b2e7d588": "임시 저장한 이미지가 저장되지 않았습니다", "fc3feba263971bce": "프롬프트는 임시 저장되었지만 브라우저 저장소가 이미지를 거부했습니다. 새로 고치면 이미지가 사라집니다.", "9e36559d0fa0cca8": "임시 저장한 이미지가 첨부되지 않았습니다", @@ -12923,5 +12921,7 @@ "99451a5d2d40440f": "{by}에서 철회했습니다.", "3ee30a50b70fffab": "{by}에서 철회했습니다: {reason}", "92e129bf413a1220": "철회됨", - "800966eb58181745": "모델이 지원하는 언어를 확인하는 중…" + "800966eb58181745": "모델이 지원하는 언어를 확인하는 중…", + "410dded6e21c280d": "임시 저장함이 가득 찼습니다", + "1af8d12ac21cb183": "임시 저장함에는 프롬프트를 {max}개까지 저장할 수 있습니다. 공간을 만들려면 하나를 복원하거나 삭제하세요. 입력란은 그대로 두었습니다." } diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index e32375e6581ce..f9a9375bc6c32 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -4936,8 +4936,6 @@ "3f5c37167aa5034f": "O armazenamento do navegador rejeitou a gravação, então o editor de mensagens ficou como estava. Libere dados do site e tente novamente.", "41ba6c0b5c5e8b22": "O prompt guardado não vai sobreviver a uma recarga", "94d7f150b3f7b291": "O armazenamento do navegador não está disponível, então estes guardados ficam só na memória durante esta sessão.", - "f421c24666cd8c71": "Prompt guardado mais antigo descartado", - "1123f816ea2a6e3e": "Os guardados comportam {max} prompts; o mais antigo foi removido para abrir espaço.", "c3a8f9b1b2e7d588": "As imagens guardadas não foram salvas", "fc3feba263971bce": "O prompt foi guardado, mas o armazenamento do navegador rejeitou as imagens. Elas vão faltar se você recarregar.", "9e36559d0fa0cca8": "As imagens guardadas não foram anexadas", @@ -12990,5 +12988,7 @@ "99451a5d2d40440f": "Retirada por {by}.", "3ee30a50b70fffab": "Retirada por {by}: {reason}", "92e129bf413a1220": "retirada", - "800966eb58181745": "Verificando quais idiomas o modelo suporta…" + "800966eb58181745": "Verificando quais idiomas o modelo suporta…", + "410dded6e21c280d": "Os guardados estão cheios", + "1af8d12ac21cb183": "Os guardados comportam {max} prompts. Restaure ou exclua um para abrir espaço; o campo de texto ficou como estava." } diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index f6b5006a97e6e..633c35f66ce05 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -4936,8 +4936,6 @@ "3f5c37167aa5034f": "Хранилище браузера отклонило запись, поэтому поле ввода не изменилось. Освободите данные сайта и повторите попытку.", "41ba6c0b5c5e8b22": "Спрятанный промпт не сохранится после перезагрузки", "94d7f150b3f7b291": "Хранилище браузера недоступно, поэтому тайник хранится в памяти только в этом сеансе.", - "f421c24666cd8c71": "Самый старый спрятанный промпт удалён", - "1123f816ea2a6e3e": "В тайнике помещается промптов: {max}; самый старый удалён, чтобы освободить место.", "c3a8f9b1b2e7d588": "Спрятанные изображения не сохранены", "fc3feba263971bce": "Промпт спрятан, но хранилище браузера отклонило его изображения. После перезагрузки их не будет.", "9e36559d0fa0cca8": "Спрятанные изображения не прикрепились", @@ -12990,5 +12988,7 @@ "99451a5d2d40440f": "Отозван: {by}.", "3ee30a50b70fffab": "Отозван ({by}): {reason}", "92e129bf413a1220": "отозван", - "800966eb58181745": "Проверяем, какие языки поддерживает модель…" + "800966eb58181745": "Проверяем, какие языки поддерживает модель…", + "410dded6e21c280d": "Тайник заполнен", + "1af8d12ac21cb183": "В тайнике помещается промптов: {max}. Восстановите или удалите один, чтобы освободить место; поле ввода осталось без изменений." } diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index 3a78a170acb9c..540ba6b7f4f34 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -4937,8 +4937,6 @@ "3f5c37167aa5034f": "Webbläsarens lagring avvisade skrivningen, så inmatningsfältet lämnades som det var. Frigör webbplatsdata och försök igen.", "41ba6c0b5c5e8b22": "Den undanlagda prompten överlever inte en omladdning", "94d7f150b3f7b291": "Webbläsarens lagring är inte tillgänglig, så undanlagda promptar finns bara i minnet under den här sessionen.", - "f421c24666cd8c71": "Den äldsta undanlagda prompten kastades", - "1123f816ea2a6e3e": "Du kan lägga undan högst {max} promptar; den äldsta togs bort för att göra plats.", "c3a8f9b1b2e7d588": "Undanlagda bilder sparades inte", "fc3feba263971bce": "Prompten lades undan, men webbläsarens lagring avvisade dess bilder. De saknas om du laddar om.", "9e36559d0fa0cca8": "Undanlagda bilder bifogades inte", @@ -12997,5 +12995,7 @@ "99451a5d2d40440f": "Återkallad av {by}.", "3ee30a50b70fffab": "Återkallad av {by}: {reason}", "92e129bf413a1220": "återkallad", - "800966eb58181745": "Kontrollerar vilka språk modellen stöder…" + "800966eb58181745": "Kontrollerar vilka språk modellen stöder…", + "410dded6e21c280d": "Undanlagringen är full", + "1af8d12ac21cb183": "Du kan lägga undan högst {max} promptar. Återställ eller ta bort en för att göra plats; inmatningsfältet lämnades som det var." } diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index 6a5ff6df38a45..b8cba154a1d29 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -4942,8 +4942,6 @@ "3f5c37167aa5034f": "浏览器存储拒绝了写入,输入框保持原样。请清理网站数据后重试。", "41ba6c0b5c5e8b22": "刷新后暂存的提示词将会丢失", "94d7f150b3f7b291": "浏览器存储不可用,这次暂存只保存在内存中,关闭页面后就会丢失。", - "f421c24666cd8c71": "已丢弃最早的暂存提示词", - "1123f816ea2a6e3e": "暂存最多保存 {max} 条提示词;已移除最早的一条以腾出空间。", "c3a8f9b1b2e7d588": "暂存的图片未能保存", "fc3feba263971bce": "提示词已暂存,但浏览器存储拒绝了其中的图片,刷新后图片会丢失。", "9e36559d0fa0cca8": "暂存的图片未能附加", @@ -13004,5 +13002,7 @@ "99451a5d2d40440f": "已由 {by} 撤回。", "3ee30a50b70fffab": "已由 {by} 撤回:{reason}", "92e129bf413a1220": "已撤回", - "800966eb58181745": "正在检查模型支持哪些语言…" + "800966eb58181745": "正在检查模型支持哪些语言…", + "410dded6e21c280d": "暂存已满", + "1af8d12ac21cb183": "暂存最多保存 {max} 条提示词。请恢复或删除一条以腾出空间;输入框保持不变。" } diff --git a/apps/web/src/promptStashStore.test.ts b/apps/web/src/promptStashStore.test.ts index 1e40dfc884bfd..ecad8594d1502 100644 --- a/apps/web/src/promptStashStore.test.ts +++ b/apps/web/src/promptStashStore.test.ts @@ -115,16 +115,17 @@ describe("promptStashStore", () => { expect(usePromptStashStore.getState().takeEntry("citation-stash").entry).toBeNull(); }); - it("evicts the oldest entry past the cap and returns it", () => { + it("refuses a new entry when full instead of discarding the oldest", () => { const store = usePromptStashStore.getState(); for (let index = 0; index < MAX_STASH_ENTRIES; index += 1) { - expect(store.stashEntry(makeEntry({ id: `entry-${index}` })).evicted).toBeNull(); + expect(store.stashEntry(makeEntry({ id: `entry-${index}` })).written).toBe(true); } - const { evicted } = store.stashEntry(makeEntry({ id: "overflow" })); - expect(evicted?.id).toBe("entry-0"); + const result = store.stashEntry(makeEntry({ id: "overflow" })); + expect(result).toEqual({ full: true, written: false, durable: false }); const entries = usePromptStashStore.getState().entries; expect(entries).toHaveLength(MAX_STASH_ENTRIES); - expect(entries[0]?.id).toBe("overflow"); + expect(entries.map((entry) => entry.id)).not.toContain("overflow"); + expect(entries.map((entry) => entry.id)).toContain("entry-0"); }); // regression: #4787 stashed prompts were lost when switching providers diff --git a/apps/web/src/promptStashStore.ts b/apps/web/src/promptStashStore.ts index 0afb52eb01838..32ad81234148f 100644 --- a/apps/web/src/promptStashStore.ts +++ b/apps/web/src/promptStashStore.ts @@ -12,7 +12,8 @@ export const PROMPT_STASH_STORAGE_KEY = "t3code:prompt-stash:v2"; const LEGACY_PROMPT_STASH_STORAGE_KEY = "t3code:prompt-stash:v1"; const PROMPT_STASH_STORAGE_VERSION = 2; -export const MAX_STASH_ENTRIES = 20; +// A sanity bound; storage quota is the real limit and reports its own failure. +export const MAX_STASH_ENTRIES = 100; // Share localStorage's ~5MB quota with drafts; record oversized attachments in droppedImageNames. export const MAX_STASH_ENTRY_ATTACHMENT_CHARS = 2_700_000; @@ -153,8 +154,9 @@ function latestEntries(memory: ReadonlyArray): ReadonlyArray

    ; stashEntry: (entry: PromptStashEntry) => { - evicted: PromptStashEntry | null; - /** False when the write failed outright (e.g. quota); nothing was kept. */ + /** True when the stash already holds MAX_STASH_ENTRIES; nothing was written. */ + full: boolean; + /** False when the write failed outright (e.g. quota or a full stash); nothing was kept. */ written: boolean; /** False for failed writes or in-memory fallback; the entry will not survive reload. */ durable: boolean; @@ -175,15 +177,19 @@ interface PromptStashStoreState { export const usePromptStashStore = create()((set, get) => ({ entries: [], stashEntry: (entry) => { - const nextEntries = [entry, ...latestEntries(get().entries)]; - const evicted = nextEntries.length > MAX_STASH_ENTRIES ? (nextEntries.pop() ?? null) : null; + const currentEntries = latestEntries(get().entries); + // Never discard a stashed prompt to make room; the user decides what to remove. + if (currentEntries.length >= MAX_STASH_ENTRIES) { + return { full: true, written: false, durable: false }; + } + const nextEntries = [entry, ...currentEntries]; const { written, durable } = persistEntries(nextEntries); - // Failed writes must not duplicate the intact composer; eviction also commits only on success. + // Failed writes must not duplicate the intact composer. if (!written) { - return { evicted: null, written: false, durable: false }; + return { full: false, written: false, durable: false }; } set(() => ({ entries: nextEntries })); - return { evicted, written: true, durable }; + return { full: false, written: true, durable }; }, takeEntry: (entryId) => { const entries = latestEntries(get().entries); diff --git a/docs/user/composer.md b/docs/user/composer.md index 53017052a2a01..cb6dabcfdf883 100644 --- a/docs/user/composer.md +++ b/docs/user/composer.md @@ -212,6 +212,10 @@ the current prompt and its attachments for later. Wait for uploads to finish fir With an empty composer, the same shortcut restores a single stash or opens the stash menu when there are several. +The stash holds up to 100 prompts, and images take up most of its browser +storage. When it is full, stashing leaves the composer as it is; restore or +delete a stash to make room. Stashes are never discarded automatically. + Stashes containing uploaded files must be restored in their original environment. Those files are retained for 24 hours. After an upload expires, restore the prompt and use **Attach again** or remove the missing file before sending. From 428684301aa466ee63cd211e195c864227f9333c Mon Sep 17 00:00:00 2001 From: Simone Date: Thu, 26 Nov 2026 02:26:53 +0100 Subject: [PATCH 170/238] fix(server): preserve EPUB thematic breaks in attachment text (#43177) Co-authored-by: Simone <185146821+Lucenx9@users.noreply.github.com> --- .../server/src/provider/documentTextWorker.ts | 21 +++++++++++++++++++ .../src/provider/userInputAttachments.test.ts | 6 +++++- 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/apps/server/src/provider/documentTextWorker.ts b/apps/server/src/provider/documentTextWorker.ts index 829b9d62ba0b5..c2bac75c93be6 100644 --- a/apps/server/src/provider/documentTextWorker.ts +++ b/apps/server/src/provider/documentTextWorker.ts @@ -13,12 +13,14 @@ const MAX_OUTPUT = 1_000_000; const CELL_START = Symbol("cell-start"); const CELL_END = Symbol("cell-end"); const LINE_START = Symbol("line-start"); +const THEMATIC_BREAK = Symbol("thematic-break"); const MARKUP_COMPATIBILITY_NS = "http://schemas.openxmlformats.org/markup-compatibility/2006"; type TextPart = | string | typeof CELL_START | typeof CELL_END | typeof LINE_START + | typeof THEMATIC_BREAK | { imageDescription: string } | { fallback: string }; @@ -325,6 +327,7 @@ function* paragraphs(node: XmlNode): Generator { for (const child of node.children) { if (typeof child === "string") yield child; else if (["br", "line-break", "cr"].includes(child.name)) yield "\n"; + else if (child.name === "hr") yield THEMATIC_BREAK; else if (["tbl", "table"].includes(child.name)) yield* table(child); else if (child.name === "pre" && child.hasText) { yield LINE_START; @@ -1132,6 +1135,7 @@ export async function extractDocumentText(path: string, extension: string): Prom let started = false; let space = false; let midLine = false; + let pendingThematicBreak: string | undefined; let endsWithWord = false; let afterImageDescription = false; let truncated = false; @@ -1146,10 +1150,16 @@ export async function extractDocumentText(path: string, extension: string): Prom continue; } if (part === CELL_END) { + remaining -= pendingThematicBreak?.length ?? 0; + pendingThematicBreak = undefined; cellDepth--; if (cellDepth > 0 && started) space = true; continue; } + if (part === THEMATIC_BREAK) { + if (midLine) pendingThematicBreak ??= ""; + continue; + } if (part === LINE_START) { // A list starts its own line unless the text before it already ended one. if (!midLine) continue; @@ -1165,6 +1175,17 @@ export async function extractDocumentText(path: string, extension: string): Prom if (started) continue; raw = part.fallback; } + if (pendingThematicBreak !== undefined) { + const next = pendingThematicBreak + raw; + const hasContent = /[^ \t]/u.test(raw); + // Inline markup can split significant indentation across chunks. + if (!hasContent && next.length < remaining) { + pendingThematicBreak = next; + continue; + } + raw = hasContent && !/^[ \t]*\n/u.test(raw) ? "\n" + next : next; + pendingThematicBreak = undefined; + } // Resolve image boundaries here, after inline markup has been flattened. // Pending cell whitespace has already used its share of the output budget. if ( diff --git a/apps/server/src/provider/userInputAttachments.test.ts b/apps/server/src/provider/userInputAttachments.test.ts index b98031e9a2bea..ec3dc56cb11ed 100644 --- a/apps/server/src/provider/userInputAttachments.test.ts +++ b/apps/server/src/provider/userInputAttachments.test.ts @@ -672,7 +672,7 @@ describe("question answer paths", () => { "book.opf": '', "chapter.xhtml": - 'Guide

    1. Before boarding
      • Check passports
    Intro
    • Read the checklist
    Visa
    Requirements
    • Photo
    Carry
    Passport
    Required
    Leave
      room
      Keep
      walking
      Safety note
      Check the gate.
      Continue to the terminal.
      Keep some
      space.
      ', + 'Guide
      1. Before boarding
        • Check passports
      Intro
      • Read the checklist
      Visa
      Requirements
      • Photo
      Carry
      Passport
      Required
      Leave
        room
        Keep
        walking
        Safety note
        Check the gate.
        Continue to the terminal.
        Keep some
        space.
        Arrive at the platform.
        Collect your luggage.
        One scene.
        Check the time.
        Board promptly.
        Example
          check()
        ', }, expected: [ "Before boarding\nCheck passports", @@ -683,6 +683,10 @@ describe("question answer paths", () => { "Keep walking", "Safety note\nCheck the gate.\nContinue to the terminal.", "Keep some space.", + "Arrive at the platform.\nCollect your luggage.", + "One scene.", + "Check the time.\nBoard promptly.", + "Example\n check()", ], }, { From be0b94683a42dc92b038434b6d3ee0a55c2f5a15 Mon Sep 17 00:00:00 2001 From: Victor Date: Wed, 25 Nov 2026 19:35:23 -0600 Subject: [PATCH 171/238] fix(client-runtime): workflow feed lines keep underscores in identifiers and paths (#43176) Co-authored-by: Julius Marminge --- packages/client-runtime/src/workflows.test.ts | 15 +++++++++++++++ packages/client-runtime/src/workflows.ts | 10 +++++++--- 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/packages/client-runtime/src/workflows.test.ts b/packages/client-runtime/src/workflows.test.ts index 0536c296b74e4..95355ccee2e80 100644 --- a/packages/client-runtime/src/workflows.test.ts +++ b/packages/client-runtime/src/workflows.test.ts @@ -729,6 +729,21 @@ describe("workflowOneLine", () => { expect(workflowOneLine("- See [the issue](https://x.test/2) first")).toBe( "See the issue first", ); + expect(workflowOneLine("_italic_ __bold__ *italic* **bold** (_nested_) **yes**_now_.")).toBe( + "italic bold italic bold (nested) yesnow.", + ); + expect(workflowOneLine("Fixed **`foo_bar`** and _see `x`_ now.")).toBe( + "Fixed foo_bar and see x now.", + ); + }); + + it("keeps underscores inside identifiers, paths and code", () => { + expect(workflowOneLine("Set MY_API_KEY in src/__tests__/my_module.test.ts and a__b__c.")).toBe( + "Set MY_API_KEY in src/__tests__/my_module.test.ts and a__b__c.", + ); + expect(workflowOneLine("Run `__init__`, ``*glob*`` and `[api](url)` now.")).toBe( + "Run __init__, *glob* and [api](url) now.", + ); }); }); diff --git a/packages/client-runtime/src/workflows.ts b/packages/client-runtime/src/workflows.ts index 1862542023054..b96b78e0ec61a 100644 --- a/packages/client-runtime/src/workflows.ts +++ b/packages/client-runtime/src/workflows.ts @@ -952,7 +952,8 @@ export function workflowStepTime(ms: number): string { /** * The first sentence of a reply, as one line of plain text: a heading, list mark, inline code, - * emphasis or link reads as its words. + * emphasis or link reads as its words. Code keeps its text, and an underscore inside a word, as in + * snake_case, is not emphasis. */ export function workflowOneLine(text: string): string { const line = @@ -961,10 +962,13 @@ export function workflowOneLine(text: string): string { .map((candidate) => candidate.trim()) .find((candidate) => candidate !== "" && !/^(#|```|\|)/.test(candidate)) ?.replace(/^([-*>]|\d+\.)\s+/, "") ?? ""; + const code: string[] = []; const plain = line + .replace(/(`+)(.+?)\1(?!`)/g, (_, _ticks, inner: string) => `\0${code.push(inner) - 1}\0`) .replace(/\[([^\]]*)\]\([^)]*\)/g, "$1") - .replace(/`([^`]*)`/g, "$1") - .replace(/(\*\*|__|\*|_)(\S(?:.*?\S)?)\1/g, "$2"); + .replace(/(? code[Number(index)] ?? match); const end = plain.search(/[.!?](\s|$)/); return end === -1 ? plain : plain.slice(0, end + 1); } From be5b14d842f6075624d439b46f7bdb2b6172404f Mon Sep 17 00:00:00 2001 From: Alex Southwell Date: Thu, 26 Nov 2026 12:36:08 +1100 Subject: [PATCH 172/238] fix(web): unknown shortcut conditions can incorrectly enable commands (#43181) Co-authored-by: SAPHID Co-authored-by: Julius Marminge --- apps/web/src/keybindings.test.ts | 15 +++++++++++++++ apps/web/src/keybindings.ts | 2 +- 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/apps/web/src/keybindings.test.ts b/apps/web/src/keybindings.test.ts index 8371b71e74645..728797735e741 100644 --- a/apps/web/src/keybindings.test.ts +++ b/apps/web/src/keybindings.test.ts @@ -627,6 +627,21 @@ describe("resolveChatShortcutCommand", () => { }); describe("resolveShortcutCommand", () => { + it.each(["constructor", "!constructor"])( + "treats inherited object properties in when-condition %s as unset", + (when) => { + const keybindings = compileResolvedKeybindingsConfig([ + { key: "mod+j", command: "terminal.toggle", when }, + ]); + assert.strictEqual( + resolveShortcutCommand(event({ code: "KeyJ", ctrlKey: true }), keybindings, { + platform: "Linux", + }), + when.startsWith("!") ? "terminal.toggle" : null, + ); + }, + ); + it("routes mod+w to the terminal while focused and to the right panel otherwise", () => { const closeEvent = event({ key: "w", metaKey: true }); assert.strictEqual( diff --git a/apps/web/src/keybindings.ts b/apps/web/src/keybindings.ts index 3361faa3e54f7..0b15c4d9a64c9 100644 --- a/apps/web/src/keybindings.ts +++ b/apps/web/src/keybindings.ts @@ -89,7 +89,7 @@ function evaluateWhenNode(node: KeybindingWhenNode, context: ShortcutMatchContex case "identifier": if (node.name === "true") return true; if (node.name === "false") return false; - return Boolean(context[node.name]); + return Object.hasOwn(context, node.name) && Boolean(context[node.name]); case "not": return !evaluateWhenNode(node.node, context); case "and": From 8515b31c8db301ad4d6a7247578b161b3d72eb9e Mon Sep 17 00:00:00 2001 From: Yash Singh Date: Wed, 25 Nov 2026 19:47:11 -0600 Subject: [PATCH 173/238] feat(web): stop devices individually or all at once from the Device panel (#43191) Co-authored-by: Claude Opus 5.5 --- .../device/DevicePanel.browser.test.tsx | 59 ++++++++++- .../web/src/components/device/DevicePanel.tsx | 99 +++++++++++++++++-- apps/web/src/i18n/translations/de.json | 5 +- apps/web/src/i18n/translations/en.json | 5 +- apps/web/src/i18n/translations/es.json | 5 +- apps/web/src/i18n/translations/fr.json | 5 +- apps/web/src/i18n/translations/ja.json | 5 +- apps/web/src/i18n/translations/ko.json | 5 +- apps/web/src/i18n/translations/pt-BR.json | 5 +- apps/web/src/i18n/translations/ru.json | 5 +- apps/web/src/i18n/translations/sv.json | 5 +- apps/web/src/i18n/translations/zh.json | 5 +- 12 files changed, 187 insertions(+), 21 deletions(-) diff --git a/apps/web/src/components/device/DevicePanel.browser.test.tsx b/apps/web/src/components/device/DevicePanel.browser.test.tsx index 2212d96927255..13206f2913a66 100644 --- a/apps/web/src/components/device/DevicePanel.browser.test.tsx +++ b/apps/web/src/components/device/DevicePanel.browser.test.tsx @@ -21,6 +21,7 @@ const mocks = vi.hoisted(() => ({ open: vi.fn<(request: unknown) => Promise>(), close: vi.fn<(request: unknown) => Promise>(), list: vi.fn<(request: unknown) => Promise>(), + shutdown: vi.fn<(request: unknown) => Promise>(), openDevice: vi.fn(), closeSurface: vi.fn(), })); @@ -67,7 +68,7 @@ vi.mock("~/state/device", async () => { const Effect = await import("effect/Effect"); const { AsyncResult, Atom } = await import("effect/reactivity"); return { - deviceEnvironment: { list: "list", open: "open", close: "close" }, + deviceEnvironment: { list: "list", open: "open", close: "close", shutdown: "shutdown" }, deviceHostProbeAtom: Atom.family((environmentId: string) => Atom.make(() => Effect.promise(() => mocks.list({ environmentId, input: {} }))), ), @@ -83,7 +84,9 @@ vi.mock("~/state/use-atom-command", () => ({ ? mocks.close : command === "list" ? mocks.list - : () => Promise.resolve({ _tag: "Success", value: {} }), + : command === "shutdown" + ? mocks.shutdown + : () => Promise.resolve({ _tag: "Success", value: {} }), })); vi.mock("~/state/query", () => ({ formatEnvironmentQueryError: () => "Device failed" })); vi.mock("~/rightPanelStore", () => ({ @@ -234,3 +237,55 @@ describe("DevicePanel discovery warning", () => { await expect.element(screen.getByText(warning)).toBeVisible(); }); }); + +describe("DevicePanel stopping devices", () => { + const tablet = { ...phone, id: "tablet", name: "Tablet", booted: true } as const; + const usbPhone = { + ...phone, + id: "usb", + name: "USB Phone", + booted: true, + physical: true, + } as const; + const shutdownOf = (device: { readonly id: string }) => [ + { + environmentId: threadA.environmentId, + input: { hostId: "local", deviceId: device.id, platform: "ios" }, + }, + ]; + + it("stops one running device, and stop all stops every running simulator", async () => { + setup(); + const runningPhone = { ...phone, booted: true }; + currentState = { ...deviceState, devices: [runningPhone, tablet, usbPhone] }; + mocks.shutdown.mockResolvedValue(opened); + await using screen = await render(devicePanel(threadA), { container }); + + await expect + .element(screen.getByRole("button", { name: "Stop USB Phone" })) + .not.toBeInTheDocument(); + await screen.getByRole("button", { name: "Stop Tablet" }).click(); + await vi.waitFor(() => expect(mocks.shutdown.mock.calls).toEqual([shutdownOf(tablet)])); + + mocks.shutdown.mockClear(); + await screen.getByRole("button", { name: "Stop all devices" }).click(); + await vi.waitFor(() => + expect(mocks.shutdown.mock.calls).toEqual([shutdownOf(runningPhone), shutdownOf(tablet)]), + ); + }); + + it("hides stop all when nothing is running and reports a failed stop", async () => { + setup(); + await using screen = await render(devicePanel(threadA), { container }); + await expect + .element(screen.getByRole("button", { name: "Stop all devices" })) + .not.toBeInTheDocument(); + + currentState = { ...deviceState, devices: [tablet] }; + mocks.shutdown.mockResolvedValue(failed); + await screen.rerender(devicePanel(threadA)); + await screen.getByRole("button", { name: "Stop Tablet" }).click(); + await expect.element(screen.getByRole("alert")).toHaveTextContent("Device failed"); + await expect.element(screen.getByRole("button", { name: "Stop Tablet" })).toBeEnabled(); + }); +}); diff --git a/apps/web/src/components/device/DevicePanel.tsx b/apps/web/src/components/device/DevicePanel.tsx index 22059aeb33912..522b605c98f91 100644 --- a/apps/web/src/components/device/DevicePanel.tsx +++ b/apps/web/src/components/device/DevicePanel.tsx @@ -5,7 +5,7 @@ import type { DeviceSummary, ScopedThreadRef, } from "@t3tools/contracts"; -import { ArrowUpRight, CircleAlert, Play, Smartphone, X } from "lucide-react"; +import { ArrowUpRight, CircleAlert, Play, Smartphone, Square, X } from "lucide-react"; import { useAtomMount } from "@effect/atom-react"; import { T, useGT, Var } from "gt-react"; import { type ReactNode, useState } from "react"; @@ -22,6 +22,7 @@ import { Dialog } from "~/components/ui/dialog"; import { Popover, PopoverPopup, PopoverTrigger } from "~/components/ui/popover"; import { WizardPopup } from "~/components/ui/wizard"; import { Spinner } from "~/components/ui/spinner"; +import { Tooltip, TooltipPopup, TooltipTrigger } from "~/components/ui/tooltip"; import { cn } from "~/lib/utils"; import { focusPanelTerminalAfterClose } from "~/lib/terminalFocus"; import { @@ -58,6 +59,7 @@ export function DevicePanel(props: { const list = useAtomCommand(deviceEnvironment.list, { reportFailure: false }); const open = useAtomCommand(deviceEnvironment.open); const close = useAtomCommand(deviceEnvironment.close); + const shutdown = useAtomCommand(deviceEnvironment.shutdown, { reportFailure: false }); // The panel stays mounted across thread switches, so an in-flight open or // power-off is tagged with the thread it belongs to and only shown there. const scope = `${environmentId}\u0000${threadId}`; @@ -69,6 +71,19 @@ export function DevicePanel(props: { const pendingDevice = operation?.scope === scope ? operation.pending : null; const operationError = operation?.scope === scope ? operation.error : null; const pendingDeviceKey = pendingDevice ? deviceKey(pendingDevice) : null; + // Power-offs act on the environment, not the thread, so they outlive thread switches. + const [stopping, setStopping] = useState>(() => new Set()); + const [stopErrors, setStopErrors] = useState>>({}); + const stopError = stopErrors[environmentId]; + const setStopError = (message: string | undefined) => + setStopErrors((current) => { + const next = { ...current }; + if (message === undefined) delete next[environmentId]; + else next[environmentId] = message; + return next; + }); + const stoppingKey = (device: DeviceSummary) => `${environmentId}\u0000${deviceKey(device)}`; + const isStopping = (device: DeviceSummary) => stopping.has(stoppingKey(device)); const hostDisabled = state.hostStatus === "disabled"; @@ -96,6 +111,7 @@ export function DevicePanel(props: { : undefined; const grouped = groupDevices(state); + const stoppable = state.devices.filter((device) => device.booted && !device.physical); const startOperation = (pending: DeviceSummary | null) => { const started = { scope, pending, error: null }; @@ -133,6 +149,27 @@ export function DevicePanel(props: { } }; + const stopDevices = async (devices: readonly DeviceSummary[]) => { + setStopError(undefined); + setStopping((current) => new Set([...current, ...devices.map(stoppingKey)])); + const results = await Promise.all( + devices.map((device) => + shutdown({ + environmentId, + input: { hostId: device.hostId, deviceId: device.id, platform: device.platform }, + }).finally(() => + setStopping((current) => { + const next = new Set(current); + next.delete(stoppingKey(device)); + return next; + }), + ), + ), + ); + const failure = results.find((result) => result._tag === "Failure"); + if (failure?._tag === "Failure") setStopError(formatEnvironmentQueryError(failure.cause)); + }; + const floatActive = () => { if (!activeDevice) return; usePreviewMiniPlayerStore.getState().open(props.threadRef, { @@ -246,6 +283,9 @@ export function DevicePanel(props: { {operationError ? ( setOperation(null)}>{operationError} ) : null} + {stopError !== undefined ? ( + setStopError(undefined)}>{stopError} + ) : null}
        {activeDevice && activeSession ? ( @@ -340,10 +380,33 @@ export function DevicePanel(props: { {`${state.hosts.find((host) => host.id === device.hostId)?.label} · ${device.version} · ${device.booted ? gt("Running", { $context: "device state" }) : gt("Stopped", { $context: "device state" })}`}
        + {device.booted && !device.physical ? ( + + void stopDevices([device])} + /> + } + > + {isStopping(device) ? : } + + + {gt("Stop", { $context: "verb, powers off a running device" })} + + + ) : null} + + {stoppable.length > 0 ? ( + + ) : null} +
        ) : null} diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index f2107901d0e26..35ff63d6d5e02 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -12990,5 +12990,8 @@ "92e129bf413a1220": "zurückgezogen", "800966eb58181745": "Prüfe, welche Sprachen das Modell unterstützt…", "410dded6e21c280d": "Ablage ist voll", - "1af8d12ac21cb183": "Die Ablage fasst {max} Prompts. Stelle einen wieder her oder lösche einen, um Platz zu schaffen; das Eingabefeld wurde unverändert gelassen." + "1af8d12ac21cb183": "Die Ablage fasst {max} Prompts. Stelle einen wieder her oder lösche einen, um Platz zu schaffen; das Eingabefeld wurde unverändert gelassen.", + "381ceed77cb8b2b3": "{name} stoppen", + "5b9fda36b610d25c": "Stoppen", + "1d372f6d555dde3c": "Alle Geräte stoppen" } diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index 2226a137fbf33..5f0720d5e9801 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -12999,5 +12999,8 @@ "92e129bf413a1220": "withdrawn", "800966eb58181745": "Checking which languages the model supports…", "410dded6e21c280d": "Stash is full", - "1af8d12ac21cb183": "The stash holds {max} prompts. Restore or delete one to make room; the composer was left as-is." + "1af8d12ac21cb183": "The stash holds {max} prompts. Restore or delete one to make room; the composer was left as-is.", + "381ceed77cb8b2b3": "Stop {name}", + "5b9fda36b610d25c": "Stop", + "1d372f6d555dde3c": "Stop all devices" } diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index 0eda6769c881f..bee246d7e5434 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -12985,5 +12985,8 @@ "92e129bf413a1220": "retirada", "800966eb58181745": "Comprobando qué idiomas admite el modelo…", "410dded6e21c280d": "El stash está lleno", - "1af8d12ac21cb183": "El stash admite {max} prompts. Restaura o elimina uno para hacer sitio; el campo de texto se dejó como estaba." + "1af8d12ac21cb183": "El stash admite {max} prompts. Restaura o elimina uno para hacer sitio; el campo de texto se dejó como estaba.", + "381ceed77cb8b2b3": "Detener {name}", + "5b9fda36b610d25c": "Detener", + "1d372f6d555dde3c": "Detener todos los dispositivos" } diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index 0633348ff404e..b871f92a4b721 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -12990,5 +12990,8 @@ "92e129bf413a1220": "retirée", "800966eb58181745": "Vérification des langues prises en charge par le modèle…", "410dded6e21c280d": "La réserve est pleine", - "1af8d12ac21cb183": "La réserve contient {max} prompts. Restaurez-en ou supprimez-en un pour faire de la place ; la zone de saisie a été laissée telle quelle." + "1af8d12ac21cb183": "La réserve contient {max} prompts. Restaurez-en ou supprimez-en un pour faire de la place ; la zone de saisie a été laissée telle quelle.", + "381ceed77cb8b2b3": "Arrêter {name}", + "5b9fda36b610d25c": "Arrêter", + "1d372f6d555dde3c": "Arrêter tous les appareils" } diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index f906439530d57..8bf7356cfc9ae 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -12926,5 +12926,8 @@ "92e129bf413a1220": "取り下げ済み", "800966eb58181745": "モデルが対応している言語を確認しています…", "410dded6e21c280d": "退避がいっぱいです", - "1af8d12ac21cb183": "退避できるプロンプトは {max} 件までです。空きを作るには、どれかを復元するか削除してください。入力欄はそのままにしてあります。" + "1af8d12ac21cb183": "退避できるプロンプトは {max} 件までです。空きを作るには、どれかを復元するか削除してください。入力欄はそのままにしてあります。", + "381ceed77cb8b2b3": "{name} を停止", + "5b9fda36b610d25c": "停止", + "1d372f6d555dde3c": "すべてのデバイスを停止" } diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index 035647987a74c..efd17b0b2713d 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -12923,5 +12923,8 @@ "92e129bf413a1220": "철회됨", "800966eb58181745": "모델이 지원하는 언어를 확인하는 중…", "410dded6e21c280d": "임시 저장함이 가득 찼습니다", - "1af8d12ac21cb183": "임시 저장함에는 프롬프트를 {max}개까지 저장할 수 있습니다. 공간을 만들려면 하나를 복원하거나 삭제하세요. 입력란은 그대로 두었습니다." + "1af8d12ac21cb183": "임시 저장함에는 프롬프트를 {max}개까지 저장할 수 있습니다. 공간을 만들려면 하나를 복원하거나 삭제하세요. 입력란은 그대로 두었습니다.", + "381ceed77cb8b2b3": "{name} 중지", + "5b9fda36b610d25c": "중지", + "1d372f6d555dde3c": "모든 기기 중지" } diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index f9a9375bc6c32..e8bb17d412655 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -12990,5 +12990,8 @@ "92e129bf413a1220": "retirada", "800966eb58181745": "Verificando quais idiomas o modelo suporta…", "410dded6e21c280d": "Os guardados estão cheios", - "1af8d12ac21cb183": "Os guardados comportam {max} prompts. Restaure ou exclua um para abrir espaço; o campo de texto ficou como estava." + "1af8d12ac21cb183": "Os guardados comportam {max} prompts. Restaure ou exclua um para abrir espaço; o campo de texto ficou como estava.", + "381ceed77cb8b2b3": "Parar {name}", + "5b9fda36b610d25c": "Parar", + "1d372f6d555dde3c": "Parar todos os dispositivos" } diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 633c35f66ce05..cef7f32eba2f9 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -12990,5 +12990,8 @@ "92e129bf413a1220": "отозван", "800966eb58181745": "Проверяем, какие языки поддерживает модель…", "410dded6e21c280d": "Тайник заполнен", - "1af8d12ac21cb183": "В тайнике помещается промптов: {max}. Восстановите или удалите один, чтобы освободить место; поле ввода осталось без изменений." + "1af8d12ac21cb183": "В тайнике помещается промптов: {max}. Восстановите или удалите один, чтобы освободить место; поле ввода осталось без изменений.", + "381ceed77cb8b2b3": "Остановить {name}", + "5b9fda36b610d25c": "Остановить", + "1d372f6d555dde3c": "Остановить все устройства" } diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index 540ba6b7f4f34..1fe040bf58a8d 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -12997,5 +12997,8 @@ "92e129bf413a1220": "återkallad", "800966eb58181745": "Kontrollerar vilka språk modellen stöder…", "410dded6e21c280d": "Undanlagringen är full", - "1af8d12ac21cb183": "Du kan lägga undan högst {max} promptar. Återställ eller ta bort en för att göra plats; inmatningsfältet lämnades som det var." + "1af8d12ac21cb183": "Du kan lägga undan högst {max} promptar. Återställ eller ta bort en för att göra plats; inmatningsfältet lämnades som det var.", + "381ceed77cb8b2b3": "Stoppa {name}", + "5b9fda36b610d25c": "Stoppa", + "1d372f6d555dde3c": "Stoppa alla enheter" } diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index b8cba154a1d29..36ce6ab4d7e7b 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -13004,5 +13004,8 @@ "92e129bf413a1220": "已撤回", "800966eb58181745": "正在检查模型支持哪些语言…", "410dded6e21c280d": "暂存已满", - "1af8d12ac21cb183": "暂存最多保存 {max} 条提示词。请恢复或删除一条以腾出空间;输入框保持不变。" + "1af8d12ac21cb183": "暂存最多保存 {max} 条提示词。请恢复或删除一条以腾出空间;输入框保持不变。", + "381ceed77cb8b2b3": "停止 {name}", + "5b9fda36b610d25c": "停止", + "1d372f6d555dde3c": "停止所有设备" } From 6d21ad2b25075b8246120aba5d478ba946a44fa8 Mon Sep 17 00:00:00 2001 From: Victor Date: Wed, 25 Nov 2026 19:47:14 -0600 Subject: [PATCH 174/238] fix(desktop): desktop update error messages no longer end in a broken emoji (#43182) Co-authored-by: Julius Marminge --- apps/desktop/src/updates/DesktopUpdates.test.ts | 9 +++++++++ apps/desktop/src/updates/DesktopUpdates.ts | 7 +++++-- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/apps/desktop/src/updates/DesktopUpdates.test.ts b/apps/desktop/src/updates/DesktopUpdates.test.ts index c1115f314e015..e72028b747302 100644 --- a/apps/desktop/src/updates/DesktopUpdates.test.ts +++ b/apps/desktop/src/updates/DesktopUpdates.test.ts @@ -1390,6 +1390,15 @@ describe("describeUpdateErrorCause", () => { cyclic.cause = cyclic; assert.include(DesktopUpdates.describeUpdateErrorCause(cyclic), "[truncated cause]"); assert.isAtMost(DesktopUpdates.describeUpdateErrorCause(cyclic).length, 1024); + + const describeCause = (outer: string, inner: string) => + DesktopUpdates.describeUpdateErrorCause( + Object.assign(new Error(outer), { cause: new Error(inner) }), + ); + const a = "a".repeat(512); + const b = "b".repeat(485); + assert.equal(describeCause(`${a.slice(1)}🚀`, "b"), `Error: ${a.slice(1)}; caused by Error: b`); + assert.equal(describeCause(a, `${b}🚀`), `Error: ${a}; caused by Error: ${b}`); }); it("does not serialize arbitrary payloads or let unreadable errors break logging", () => { diff --git a/apps/desktop/src/updates/DesktopUpdates.ts b/apps/desktop/src/updates/DesktopUpdates.ts index 32e64502d9333..b6a9aa0ac64a2 100644 --- a/apps/desktop/src/updates/DesktopUpdates.ts +++ b/apps/desktop/src/updates/DesktopUpdates.ts @@ -244,7 +244,8 @@ function redactMessage(message: string): string { /\b[\w-]*(?:token|password|secret|credential|api[_-]?key)[\w-]*\s*[:=]\s*(?:"[^"]*"|'[^']*'|[^\s,;]+)/gi, "[redacted credential]", ) - .slice(0, 512); + .slice(0, 512) + .replace(/\p{Surrogate}$/u, ""); } function summarizeCause(cause: unknown, depth: number): string { @@ -281,7 +282,9 @@ function summarizeCause(cause: unknown, depth: number): string { export function describeUpdateErrorCause(cause: unknown): string { try { - return summarizeCause(cause, 0).slice(0, 1024); + return summarizeCause(cause, 0) + .slice(0, 1024) + .replace(/\p{Surrogate}$/u, ""); } catch { return "UnknownError"; } From f839ab40410de2db36b3fff07728fa64b6129682 Mon Sep 17 00:00:00 2001 From: Simone Date: Thu, 26 Nov 2026 03:01:28 +0100 Subject: [PATCH 175/238] fix(server): separate EPUB figure captions from nearby text (#43190) Co-authored-by: Simone <185146821+Lucenx9@users.noreply.github.com> Co-authored-by: Julius Marminge --- apps/server/src/provider/documentTextWorker.ts | 2 +- apps/server/src/provider/userInputAttachments.test.ts | 11 +++++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/apps/server/src/provider/documentTextWorker.ts b/apps/server/src/provider/documentTextWorker.ts index c2bac75c93be6..f9439464b1836 100644 --- a/apps/server/src/provider/documentTextWorker.ts +++ b/apps/server/src/provider/documentTextWorker.ts @@ -345,7 +345,7 @@ function* paragraphs(node: XmlNode): Generator { if (level) yield `${"#".repeat(Math.min(6, level))} `; yield* text(child); yield "\n"; - } else if (child.name === "blockquote" && child.hasText) { + } else if (["blockquote", "figcaption"].includes(child.name) && child.hasText) { yield LINE_START; yield* paragraphs(child); yield LINE_START; diff --git a/apps/server/src/provider/userInputAttachments.test.ts b/apps/server/src/provider/userInputAttachments.test.ts index ec3dc56cb11ed..c01eea281ba95 100644 --- a/apps/server/src/provider/userInputAttachments.test.ts +++ b/apps/server/src/provider/userInputAttachments.test.ts @@ -712,6 +712,17 @@ describe("question answer paths", () => { }, expected: ["Example command:\ngit status --short\n git log -1\nInspect the output."], }, + { + ext: "epub", + parts: { + "META-INF/container.xml": '', + "book.opf": + '', + "chapter.xhtml": + '
        Map of the river
        Figure 1. River crossings

        Water levels rose in May.

        ', + }, + expected: ["Map of the river\nFigure 1. River crossings\nWater levels rose in May."], + }, // A prefixed span attribute is foreign markup, not an XHTML span. { ext: "epub", From a03c43363ba31f3699883e099b60cbf15d881016 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 25 Nov 2026 18:05:12 -0800 Subject: [PATCH 176/238] docs(user): copy pass on user docs, add missing feature guides and onboarding index (#43206) --- docs/README.md | 54 +- docs/user/README.md | 114 +++ docs/user/activity-log.md | 68 +- docs/user/appearance.md | 122 +--- docs/user/background-service.md | 216 ++---- docs/user/browser-import.md | 25 +- docs/user/browser.md | 31 + docs/user/cli.md | 52 ++ docs/user/composer.md | 456 +++--------- docs/user/cursor.md | 108 +-- docs/user/default-browser.md | 18 +- docs/user/devices.md | 196 +---- docs/user/diagnostics.md | 36 + docs/user/diffs.md | 38 + docs/user/faq.md | 56 +- docs/user/guest-links.md | 53 +- docs/user/html-renders.md | 22 +- docs/user/install.md | 318 ++------ docs/user/keybindings.md | 250 ++----- docs/user/keyboard-focus.md | 41 +- docs/user/managed-policy.md | 278 ++----- docs/user/mobile-notifications.md | 19 +- docs/user/multi-repo-projects.md | 214 ++---- docs/user/open-source-licenses.md | 13 +- docs/user/outside-agents.md | 203 +----- docs/user/permission-modes.md | 104 +-- docs/user/portable-handoffs.md | 54 +- docs/user/project-settings.md | 326 ++------- docs/user/prompt-links.md | 69 +- docs/user/providers-acp.md | 150 +--- docs/user/providers-antigravity.md | 189 +---- docs/user/providers-claude.md | 195 +---- docs/user/providers-codex.md | 184 +---- docs/user/providers-fx.md | 78 +- docs/user/providers-grok.md | 26 + docs/user/providers-kiro.md | 67 +- docs/user/providers-muse.md | 72 +- docs/user/providers-opencode.md | 95 +-- docs/user/providers-pi.md | 101 +-- docs/user/question-attachments.md | 13 +- docs/user/remote-access.md | 686 ++---------------- docs/user/secrets-1password-connect.md | 55 +- .../user/secrets-1password-service-account.md | 50 +- docs/user/secrets.md | 66 +- docs/user/snap-shot.md | 108 +-- docs/user/source-control.md | 481 ++---------- docs/user/subagents.md | 21 + docs/user/t3-connect-troubleshooting.md | 171 ++--- docs/user/t3-json.md | 80 ++ docs/user/telemetry.md | 142 +--- docs/user/terminal.md | 67 +- docs/user/text-generation.md | 42 +- docs/user/thread-migration.md | 54 +- docs/user/thread-sidebar.md | 454 ++---------- docs/user/triage.md | 34 +- docs/user/updating.md | 223 +----- docs/user/usage.md | 230 +----- docs/user/voice-input.md | 180 +---- docs/user/welcome-page.md | 120 +-- docs/user/workflows.md | 148 +--- 60 files changed, 1816 insertions(+), 6320 deletions(-) create mode 100644 docs/user/README.md create mode 100644 docs/user/browser.md create mode 100644 docs/user/cli.md create mode 100644 docs/user/diagnostics.md create mode 100644 docs/user/diffs.md create mode 100644 docs/user/providers-grok.md create mode 100644 docs/user/subagents.md create mode 100644 docs/user/t3-json.md diff --git a/docs/README.md b/docs/README.md index 00e60de0e7063..135ad21a2bbb0 100644 --- a/docs/README.md +++ b/docs/README.md @@ -2,34 +2,32 @@ ## Using T3 Code -- [Install T3 Code](./user/install.md) -- [Messages and context](./user/composer.md) -- [Working with threads](./user/thread-sidebar.md) -- [Permission modes](./user/permission-modes.md) -- [Terminal history](./user/terminal.md) -- [Source control](./user/source-control.md) -- [Project settings](./user/project-settings.md) -- [Projects with several repositories](./user/multi-repo-projects.md) -- [Appearance and themes](./user/appearance.md) -- [Keyboard shortcuts](./user/keybindings.md) -- [Voice input](./user/voice-input.md) -- [Text generation models](./user/text-generation.md) -- [SnapShots](./user/snap-shot.md) -- [Visual replies](./user/html-renders.md) -- [Import browser sessions](./user/browser-import.md) -- [Use T3 Code as your default browser](./user/default-browser.md) -- [Devices](./user/devices.md) -- [Usage and limits](./user/usage.md) -- [Secrets](./user/secrets.md) -- [Product usage data](./user/telemetry.md) -- [Remote access](./user/remote-access.md) -- [Guest links](./user/guest-links.md) -- [T3 Connect troubleshooting](./user/t3-connect-troubleshooting.md) -- [Outside agents (MCP)](./user/outside-agents.md) -- [Running in the background](./user/background-service.md) -- [Updating T3 Code](./user/updating.md) -- [Triage an issue](./user/triage.md) -- Provider guides: [Codex](./user/providers-codex.md) · [Claude](./user/providers-claude.md) · [OpenCode](./user/providers-opencode.md) · [Antigravity](./user/providers-antigravity.md) · [Kiro](./user/providers-kiro.md) · [Pi](./user/providers-pi.md) · [Muse Code](./user/providers-muse.md) · [fx](./user/providers-fx.md) +New to T3 Code? Start with the **[User Guide & Index](./user/README.md)** for how T3 Code works, prerequisites, expectations, and the complete directory of feature guides. + +### Essentials + +- [Install T3 Code](./user/install.md) · [Welcome page](./user/welcome-page.md) · [FAQ](./user/faq.md) +- [Working with threads](./user/thread-sidebar.md) · [Messages and context](./user/composer.md) · [Permission modes](./user/permission-modes.md) +- [Diffs and workspace files](./user/diffs.md) · [Source control](./user/source-control.md) · [Subagents and delegation](./user/subagents.md) +- [Settings and project overrides](./user/project-settings.md) · [Project config (`t3.json`)](./user/t3-json.md) · [Multi-repo projects](./user/multi-repo-projects.md) + +### Workspace tools & automation + +- [Built-in browser](./user/browser.md) ([import sessions](./user/browser-import.md) · [default browser](./user/default-browser.md)) · [Devices](./user/devices.md) +- [Terminal](./user/terminal.md) · [Visual replies & MCP apps](./user/html-renders.md) · [SnapShots](./user/snap-shot.md) · [Voice input](./user/voice-input.md) +- [Workflows](./user/workflows.md) · [Text generation models](./user/text-generation.md) · [Prompt links](./user/prompt-links.md) +- [Activity log](./user/activity-log.md) · [Appearance and themes](./user/appearance.md) · [Keybindings](./user/keybindings.md) · [Keyboard focus](./user/keyboard-focus.md) + +### Remote, security & operations + +- [Remote access](./user/remote-access.md) · [T3 Connect troubleshooting](./user/t3-connect-troubleshooting.md) · [Mobile notifications](./user/mobile-notifications.md) · [Guest links](./user/guest-links.md) +- [Outside agents (MCP)](./user/outside-agents.md) · [Secrets](./user/secrets.md) ([1Password service account](./user/secrets-1password-service-account.md) · [1Password Connect](./user/secrets-1password-connect.md)) +- [Background service](./user/background-service.md) · [Updating T3 Code](./user/updating.md) · [Usage and limits](./user/usage.md) · [Maintenance & diagnostics](./user/diagnostics.md) +- [CLI reference (`t3`)](./user/cli.md) · [Product usage data](./user/telemetry.md) · [Managed policy](./user/managed-policy.md) · [Triage an issue](./user/triage.md) · [V1 migration](./user/thread-migration.md) · [Portable handoffs](./user/portable-handoffs.md) · [Question attachments](./user/question-attachments.md) · [Open source licenses](./user/open-source-licenses.md) + +### Providers + +[Codex](./user/providers-codex.md) · [Claude](./user/providers-claude.md) · [Cursor](./user/cursor.md) · [Grok Build](./user/providers-grok.md) · [Antigravity](./user/providers-antigravity.md) · [OpenCode](./user/providers-opencode.md) · [Kiro](./user/providers-kiro.md) · [Pi](./user/providers-pi.md) · [Muse Code](./user/providers-muse.md) · [fx](./user/providers-fx.md) · [ACP providers](./user/providers-acp.md) --- diff --git a/docs/user/README.md b/docs/user/README.md new file mode 100644 index 0000000000000..dfc68fc07ed71 --- /dev/null +++ b/docs/user/README.md @@ -0,0 +1,114 @@ +# T3 Code User Guide + +Welcome to T3 Code. This guide explains how T3 Code works, what you need before starting, what to expect, and where to find documentation for every feature. + +## How T3 Code works + +T3 Code is an open-source control plane for coding agents. It gives the coding agents already installed on your computer (or server) one fast, unified interface across **desktop**, **web** (`app.t3.codes` or local), and **mobile** (iOS and Android). + +### Core concepts + +- **Host (Environment) vs. Clients**: A T3 Code **server** runs on the machine that holds your code and provider CLIs (your laptop, desktop, workstation, or VPS). Your desktop app, browser, and phone are **clients** connected to one or more environments. +- **T3 Code is not a harness**: It drives the agent harnesses you already have—Claude Code, Codex, Cursor, Grok Build, Google Antigravity, OpenCode, Kiro, Pi, Muse Code, fx, or any [ACP](./providers-acp.md) agent. You can switch providers or models mid-thread and even let one agent delegate tasks to another. +- **Projects**: A project points to a folder on an environment (a single Git repo, a [multi-repo folder](./multi-repo-projects.md), or a plain folder). You can also start scratch threads [without a project](./thread-sidebar.md#start-without-a-project). +- **Threads & Worktrees**: Each task gets its own **thread**. Run a thread in the project's main checkout, or choose **New worktree** to give it an isolated Git branch and working directory so multiple agents can work in parallel without stepping on each other. +- **Permission modes**: Control per thread whether an agent asks before acting (**Supervised**), auto-approves file edits (**Auto-accept edits**), uses provider auto-review (**Auto**), or runs without prompts (**Full access**). + +## Prerequisites and expectations + +- **Bring your own subscription or API keys**: T3 Code is free and does not resell tokens. You need at least **one installed, authenticated provider** on the host machine before starting a thread (Codex via ChatGPT and Google Antigravity can install and sign in directly from T3 Code). +- **Code stays on your machine**: Your code and prompts go directly from your host machine to your chosen provider—never through T3 Code servers. +- **Your host must stay awake**: Your phone and `app.t3.codes` are remote controls. If the host machine sleeps or shuts down, agents pause until it wakes. Use the [background service](./background-service.md) for always-on hosts. +- **Git is optional but unlocks the best features**: Branching, isolated worktrees, turn diffs, and one-click PRs require a Git repository (and a signed-in host CLI or token for PRs/issues). +- **No local-model focus**: T3 Code is designed for frontier coding agents (though OpenAI-compatible local endpoints like Ollama can be used for lightweight [text generation](./text-generation.md) like thread titles). +- **Device vs. server settings**: Appearance, keybinding preferences, and saved PR views live per device; provider configs, thread rules, worktree cleanup, and scheduled tasks live on each server environment (with per-project overrides). + +## Quickstart + +1. **Install T3 Code** on the machine where your agents will run ([Install T3 Code](./install.md)). +2. **Set up at least one agent** via the [Welcome page](./welcome-page.md) or **Settings → Providers** (for example, `claude auth login` or `codex login`). +3. **Open or clone a project** and start a thread ([Working with threads](./thread-sidebar.md)). +4. **Optional — connect your phone or another computer**: Run `t3 up` on the host or enable **T3 Connect** in **Settings → Sharing & access** ([Remote access](./remote-access.md)). + +--- + +## Documentation index + +### Getting started + +- [Install T3 Code](./install.md) — Desktop app, `t3` CLI, mobile app, WSL, and provider setup. +- [Welcome page](./welcome-page.md) — First-run setup and importing existing Claude, Codex, and Pi sessions. +- [FAQ](./faq.md) — Common questions on pricing, subscriptions, privacy, limits, and troubleshooting. +- [Threads from older T3 Code versions](./thread-migration.md) — V1 → V2 database migration and recovery backups. + +### Everyday workflow + +- [Working with threads](./thread-sidebar.md) — Starting threads, scratch threads, pinning, settling, snoozing, archiving, and side chats. +- [Messages and context](./composer.md) — Composer formatting, attachments, queueing/steering, `@` threads/models, `#` PRs, `/goal`, stash, and rewind. +- [Permission modes](./permission-modes.md) — Supervised, Auto-accept edits, Auto, Full access, push-hook prompts, and provider differences. +- [Diffs and workspace files](./diffs.md) — Turn diffs, branch comparisons, commits view, file editor, and inline review comments. +- [Source control](./source-control.md) — GitHub, GitLab, Forgejo/Gitea, Bitbucket, Azure DevOps, GitCafe, Cursor Origin, Linear issues, PR review guides, stacks, and PR watching. +- [Activity log](./activity-log.md) — Inspecting tool calls, hiding work logs / Zen mode, and screen reader announcements. +- [Subagents and delegation](./subagents.md) — Parallel T3-delegated and provider-native subagents. +- [Context in portable handoffs](./portable-handoffs.md) — How conversation context transfers across provider switches and forks. +- [Files in question answers](./question-attachments.md) — Attaching files and images when answering agent questions. +- [Terminal](./terminal.md) — Integrated host terminals, scrollback limits, custom shells, and fish config. + +### Workspace tools & media + +- [Built-in browser](./browser.md) — Preview tabs, profiles, viewports, element picker, annotations, recordings, and agent browser access. +- [Import browser sessions](./browser-import.md) — Copying cookies from Chrome, Safari, Firefox, Zen, or Helium into the desktop preview browser. +- [Use T3 Code as your default browser](./default-browser.md) — Opening links and HTML files in T3 Code on macOS. +- [Devices](./devices.md) — Live iOS Simulators, Android Emulators, physical Android devices, SSH device hosts, and Simlock pools. +- [Visual replies and MCP apps](./html-renders.md) — Inline HTML charts/diagrams/mockups and interactive MCP Apps. +- [SnapShots](./snap-shot.md) — Desktop window capture with accessibility text attached to drafts. +- [Voice input](./voice-input.md) — On-device, environment, and cloud speech-to-text dictation and transcript cleanup. +- [Prompt links](./prompt-links.md) — Shareable prefilled draft links and thread links. + +### Projects, automation & customization + +- [Settings and project overrides](./project-settings.md) — Scope inheritance, pinning/archiving projects, worktree cleanup, scheduled tasks, and webhooks. +- [Project configuration (`t3.json`) and actions](./t3-json.md) — Checked-in repo config, setup/dev/settle scripts, and schema reference. +- [Projects with several repositories](./multi-repo-projects.md) — Multi-repo folders, external folders, submodules, and custom worktree layouts. +- [Workflows](./workflows.md) — Durable multi-stage TypeScript workflows (Labs) with schedules, webhooks, and approvals. +- [Text generation models](./text-generation.md) — Fast/cheap API models for titles, commits, PR descriptions, and voice cleanup. +- [Appearance and themes](./appearance.md) — Built-in themes, custom palettes/CSS, background images, LaTeX math, and environment themes. +- [Keybindings](./keybindings.md) — Shortcuts, `keybindings.json` syntax, `when` conditions, and hardware keyboards. +- [Keyboard focus](./keyboard-focus.md) — Full keyboard workspace navigation (`F6`, sidebar, and settings). + +### Providers + +- [Codex](./providers-codex.md) — ChatGPT sign-in, CLI/shadow-home multi-account, image generation, async questions, Daybreak. +- [Claude](./providers-claude.md) — Multi-account `CLAUDE_CONFIG_DIR`, idle compaction, skills, MCP OAuth, Claude in Chrome, OpenRouter. +- [Cursor](./cursor.md) — Local Cursor SDK sign-in, MCP/plugins, and Windows sandbox notes. +- [Grok Build](./providers-grok.md) — Grok CLI setup, `XAI_API_KEY`, `GROK_HOME`, and permissions. +- [Antigravity](./providers-antigravity.md) — Managed runtime, Google/Vertex sign-in methods, skills, and quotas. +- [OpenCode](./providers-opencode.md) — OpenCode 1.x/2.x, local vs. external servers, compaction, and approvals. +- [Kiro](./providers-kiro.md) — Kiro CLI V3, custom agents, and permissions. +- [Pi](./providers-pi.md) — Pi setup, extensions, thinking/speed tiers, and folder trust. +- [Muse Code](./providers-muse.md) — Muse CLI, `META_API_KEY`, and limitations. +- [fx](./providers-fx.md) — fx backends, effort, skills, and permissions. +- [ACP providers](./providers-acp.md) — ACP Registry agents and local ACP commands. + +### Remote, mobile & integrations + +- [Remote access](./remote-access.md) — T3 Connect, LAN/Tailscale pairing, desktop SSH, multi-route failover, load balancing, and linked environments. +- [T3 Connect troubleshooting](./t3-connect-troubleshooting.md) — Diagnosing tunnel, port 7844, DNS, clock, and account errors. +- [Mobile notifications](./mobile-notifications.md) — Push alerts, iOS Live Activities/widgets, and Android Live Updates. +- [Guest links](./guest-links.md) — Sharing a live thread with a teammate in their browser (no account needed). +- [Outside agents](./outside-agents.md) — Connecting Claude Code, Codex, ChatGPT, or bots to T3 Code over MCP, plus `t3 thread` host scripting. +- [Secrets](./secrets.md) — 1Password CLI references and private in-thread agent secret cards. +- [1Password service account](./secrets-1password-service-account.md) — Headless 1Password setup with a service account token. +- [1Password Connect](./secrets-1password-connect.md) — Headless 1Password setup with a Connect server. + +### Operations, monitoring & admin + +- [Running T3 Code in the background](./background-service.md) — Background user service, `service.env`, Linux OOM protection, and `t3 doctor`. +- [Updating T3 Code](./updating.md) — Updating desktop, servers, providers, Stable/Nightly tracks, and restart continuation. +- [Usage and limits](./usage.md) — Token/cost tracking, custom model pricing, pooled subscription quotas, CLIProxyAPI hubs, and HTTP quota sources. +- [Maintenance, power, and diagnostics](./diagnostics.md) — Background activity profiles, keep awake, Diagnostics UI, and `t3 trace`. +- [CLI reference (`t3`)](./cli.md) — Complete overview of `t3` subcommands. +- [Product usage data and diagnostics](./telemetry.md) — Telemetry opt-outs, agent feedback, mobile diagnostics, and OTLP export. +- [Triage an issue](./triage.md) — Letting an agent investigate a T3 Code bug and draft an issue. +- [Managed policy](./managed-policy.md) — Machine-wide enterprise configuration via JSON, macOS profiles, and Windows GPO/registry. +- [Open source licenses](./open-source-licenses.md) — Viewing third-party license notices in the app. diff --git a/docs/user/activity-log.md b/docs/user/activity-log.md index 93b198aa18f68..b6f88e2073890 100644 --- a/docs/user/activity-log.md +++ b/docs/user/activity-log.md @@ -1,50 +1,38 @@ # Activity log -On web and desktop, consecutive tool calls appear as an expandable summary. Open it to inspect -commands, tool inputs, status, and exit codes. Expand a tool call to see its output. A running -command's output updates live, and long output shows only its most recent part. Use **Open diff** on -a file change to review its contents. +The activity log shows what an agent is doing during a turn—shell commands, file edits, searches, and tool calls—as expandable summaries in the conversation. -T3 Orchestrator summaries describe the actions taken, such as **Ran 2 commands and sent messages -to 3 threads**. Repeated messages to the same destinations show both counts: **Sent 5 messages to -2 threads**. Thread creation counts the threads returned by the tool, including batches. +## Inspect tool calls -Groups with many kinds of activity show up to two specific action categories and a count of the -remaining actions. Commands, file changes, and orchestration changes take priority over reads and -status checks. Expand the group for the full list. - -Failed calls do not count as successful messages or creations. Waiting on a thread does not mean -it finished, and an interrupt or cancellation request does not mean the thread stopped. When tool -details are unavailable, summaries use a broader description instead of guessing how many threads -were affected. +- Expand a summary group on web and desktop to inspect commands, tool inputs, status, and exit codes. +- Expand an individual tool call to view its output. Running commands stream live, showing the most recent output for long logs. +- Select **Open diff** on a file change to review the edit. ## Hide tool calls -**Tool calls in chat** in **Settings → Chat** (web and desktop) or **Settings → Appearance** -(mobile) hides commands, file edits, searches, and MCP tool calls -from the conversation. **Hide successful** shows a call while it runs and keeps -it only if it fails. **Hide all** hides every call and shows **Thinking** while the agent works. -**Zen** also hides the agent's in-between messages, so each turn shows your message -and the agent's last reply, which appears when the turn ends. If you steer while the agent is -answering, the answer it finished before reading your steer stays too. On web and desktop, Find -shows the in-between messages while it is open. Approvals, questions, and errors always show. The -setting applies to this browser or device only. +Configure **Settings → Chat → Tool calls in chat** (web and desktop) or **Settings → Appearance → Tool calls in chat** (mobile) to reduce noise in the conversation. This setting applies per device or browser. + +| Mode | Behavior | +| ---------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **Show all** (default) | Shows all tool calls and summaries. | +| **Hide successful** | Shows a call while it runs and keeps it only if it fails. | +| **Hide all** | Hides every tool call and shows **Thinking** while the agent works. | +| **Zen** | Also hides intermediate agent messages, showing only your prompt and the agent's final reply once the turn ends (plus any reply finished before a steer). | + +Approvals, questions, and errors are always shown. On web and desktop, opening Find temporarily reveals hidden intermediate messages. ## Screen reader announcements -On web and desktop, a screen reader hears the open thread's turn as it runs. **Screen reader -announcements** in **Settings → Chat** sets how much. **Status only** says when a turn starts, -needs your approval or input, and ends. **Status and messages** also reads each message the agent -writes and then keeps working after, once that message is complete. A very long message is cut -short. The reply that closes the turn is not read, so you can read it yourself when you hear -**Done**. **Everything** adds the step the agent is on, such as the command it is running. Steps -are spaced out, so a quick step can be skipped for a newer one. -The agent's reasoning text is never read. The setting follows the agent's real activity, whatever -**Tool calls in chat** hides, and applies to this browser or device only. - -To hear the open thread and what it's doing when you switch to T3 Code, turn on **Screen reader -window title** in the same section. The window title then starts with the thread's status -(**Working**, **Needs approval**, or **Needs your input**) and its name, then the project, so a -screen reader says them first. When the turn ends, only the status goes away. -Anyone who can see your taskbar, window switcher, or shared screen sees it too, and time trackers -that group by window title count each status separately. +On web and desktop, configure **Settings → Chat → Screen reader announcements** to hear turn progress for the open thread (per device/browser): + +- **Status only**: Announces when a turn starts, needs approval or input, and finishes. +- **Status and messages**: Also reads intermediate agent messages once complete (long messages are truncated). The final reply is not read automatically so you can read it yourself after hearing **Done**. +- **Everything**: Adds the current step (such as the command running); rapid steps may be skipped for newer ones. + +Agent reasoning text is never read. Announcements follow actual agent activity regardless of **Tool calls in chat**. + +### Screen reader window title + +Turn on **Settings → Chat → Screen reader window title** to prefix the window title with the open thread's status (**Working**, **Needs approval**, or **Needs your input**), thread title, and project name. The status prefix clears when the turn ends. + +> Note: This title is visible in your taskbar, window switcher, and shared screens, and time trackers that group by window title will count each status separately. diff --git a/docs/user/appearance.md b/docs/user/appearance.md index 340e9e5ff5f1f..dc978be08a03a 100644 --- a/docs/user/appearance.md +++ b/docs/user/appearance.md @@ -1,117 +1,67 @@ # Appearance and themes -On web and desktop, open **Settings → Appearance** to choose a theme and follow the system -appearance or stay in light or dark mode. To use different themes for light and dark mode, select -the corresponding preview within each theme. Appearance preferences are saved separately on each -device or browser. - -On web and desktop, use **Change theme** in the command palette to select a theme without leaving chat. -Press **Cmd+Option+A** on macOS or **Ctrl+Alt+A** on Windows/Linux to open the theme picker directly. -Use **Change appearance** in the command palette to choose System, Light, or Dark independently of -the theme. **Cmd+Option+Shift+A** on macOS or **Ctrl+Alt+Shift+A** on Windows/Linux cycles through -those modes. Customize these shortcuts under **Settings → Keybindings**. - -On mobile, open **Settings → Appearance**. Mobile has its own themes and text, -code, and terminal preferences. It does not follow environment themes or defaults. - -On Android 12 or newer, choose the **Material You** theme in Appearance to use colors from -your wallpaper. Selecting another theme replaces those colors. Like other themes, Material You -can be selected separately for light and dark appearances. -Android uses **Material You Layout** by default unless you have turned it off in Appearance. -It changes shapes, spacing, and controls independently -of the selected theme. +Customize T3 Code's theme, light/dark appearance, math rendering, motion, and custom CSS. Appearance settings are saved per device or browser. -## Composer context +## Switch themes and appearance + +- **Web and desktop**: Open **Settings → Appearance** to choose a theme and light, dark, or system mode. Select the light or dark preview on a theme card to pair different themes with each mode. + - Open theme picker from anywhere: `Cmd+Option+A` (macOS) or `Ctrl+Alt+A` (Windows/Linux), or **Change theme** in the command palette. + - Cycle System / Light / Dark: `Cmd+Option+Shift+A` (macOS) or `Ctrl+Alt+Shift+A` (Windows/Linux), or **Change appearance** in the command palette. +- **Mobile**: Open **Settings → Appearance**. Mobile uses its own themes and text/code/terminal preferences and does not follow environment themes. + - On Android 12+, **Material You** pulls colors from your wallpaper (configurable separately for light and dark), and **Material You Layout** controls Material You shapes and spacing independently of the theme. -Git-backed projects show branch and worktree controls below the composer while you create a thread. -The controls retreat as the composer docks after you send the first message. +## Composer context -Turn on **Composer context** to keep those controls visible after the thread starts. This preference -applies to the web and desktop clients. +Git-backed projects show branch and worktree controls below the composer before the first message. Turn on **Settings → Appearance → Composer context** (web and desktop) to keep those controls visible after the thread starts. ## Math -Turn on **Render math** in **Settings → Appearance** to typeset LaTeX in messages and Markdown -previews on web, desktop, and mobile. It reads `$…$`, `$$…$$`, `\(…\)`, and `\[…\]`, outside of code. -Fenced `math` blocks also render. Formulas work in tables, including absolute-value bars. -Dollar amounts such as `$5 and $10` stay text; write `\$` to keep any other dollar sign literal. -Wide formulas scroll horizontally while the surrounding text wraps. Copying a formula or -exporting a table preserves the TeX. +Turn on **Settings → Appearance → Render math** (per device) to render LaTeX in messages and Markdown previews on web, desktop, and mobile. -The composer keeps TeX source editable, including when rich text is enabled. The Render math -preference is saved separately on each device. +- Supports `$…$`, `$$…$$`, `\(…\)`, `\[…\]`, and fenced `math` blocks outside of code. +- Currency like `$5 and $10` stays plain text; use `\$` to escape other literal dollar signs. +- Copying a formula or exporting a table preserves the raw TeX. The composer keeps TeX source editable. ## Motion -The main sidebar, right panel, and terminal drawer open and close immediately by default. Move the -**Panel animations** slider above 0 ms to add motion, up to 400 ms, unless reduced motion is enabled -in your operating system. Moving between threads always snaps to the selected thread's panel state -without replaying its transitions. +Sidebars, the right panel, and the terminal drawer open immediately by default. Adjust **Settings → Appearance → Panel animations** (0–400 ms) to enable transitions, unless OS reduced motion is enabled. ## Custom themes -On web and desktop, choose **Create theme** to adjust a palette, or import a T3 Code or VS Code -theme. The theme editor's color picker lets you select an area of the app to find the color to -change. Export your theme as JSON to share it. +On web and desktop, choose **Create theme** in **Settings → Appearance** to edit a palette, import a T3 Code or VS Code theme, or export your theme as JSON. ### Custom CSS -For a change that colors cannot make, open **Custom CSS** in the theme editor. The CSS is saved with -the theme, applies after T3 Code's own styles on web and desktop, and is included in exports. Use -`.dark` or `:root:not(.dark)` to target one appearance. - -Custom CSS cannot load files. `@import`, `image-set()`, and `url()` are ignored, except `url()` -with a `data:` address or an `#id`. This keeps an imported theme from sending what is on your screen -to another site. For a full-size image, use a [background image](#background-image). +Open **Custom CSS** in the theme editor for styling beyond palette colors. Custom CSS is saved with the theme and included in exports. -Class names in the app change between releases. For rules that keep working, target `data-slot` -and other `data-` attributes, such as `[data-chat-header]` or `[data-slot="button"]`. - -If a rule hides something you need, run `t3 theme set t3-chat` on the server to switch to a -built-in theme, or press **Cmd+Option+A** on macOS or **Ctrl+Alt+A** on Windows/Linux to pick -another theme. +- Use `.dark` or `:root:not(.dark)` to target one appearance. +- Target `data-slot` and other `data-` attributes (such as `[data-chat-header]` or `[data-slot="button"]`) rather than class names, which change between releases. +- External resource loading (`@import`, `image-set()`, and non-`data:`/`#id` `url()`) is blocked for security. Use a [background image](#background-image) for full-size images. +- **Recovery**: If custom CSS hides something you need, run `t3 theme set t3-chat` on the server or press `Cmd+Option+A` / `Ctrl+Alt+A` to switch themes. ### Ask an agent -An agent on the same machine as the server can restyle T3 Code for you. Ask it to change the look, -for example "make T3 Code's chat header taller" or "give T3 Code a solarized theme". It publishes -an [environment theme](#environment-themes) with colors and CSS, and web and desktop clients of that -server switch to it. It can also switch them to light, dark, or system mode. The thread must run -in Full access. Ask the agent to set a built-in theme to undo it. +An agent running on the same machine as the server in **Full access** mode can restyle T3 Code for you (for example, "give T3 Code a solarized theme"). It publishes an [environment theme](#environment-themes) and switches connected web and desktop clients to it. Ask the agent to switch back to a built-in theme to undo. ## Environment themes -Environment themes and defaults come from the server serving your web app or the desktop app's -main local environment. With the desktop app's local environment off, they come from the -[background service](./background-service.md) on the same machine while the app is connected to -it. app.t3.codes and other connections do not use them. +Environment themes come from the server serving your web app or the desktop app's local environment (or local [background service](./background-service.md) when the built-in local environment is off). Hosted `app.t3.codes` and remote connections do not apply them. -Select a published theme in **Settings → Appearance** to follow its palette as the server updates -it. **Duplicate** makes an independent copy you can edit. A saved custom theme with the same ID -takes precedence. If the server stops publishing the selected theme, T3 Code falls back to its -standard theme. +Select a published theme in **Settings → Appearance** to track server updates, or **Duplicate** it for an independent editable copy. -Run this on the server to set a default and switch connected clients to it: +Manage the server default from the CLI: ```bash -t3 theme set nightfall +t3 theme set nightfall # Set default and switch connected/reconnecting clients once +t3 theme clear # Remove the default without changing current client themes +t3 theme show # List the default and all published themes ``` -Clients that are offline apply it when they reconnect. Each client applies the setting once; -choosing another theme afterward sticks until the next `t3 theme set`. Run the command again to -reapply it, even if the name is unchanged. - -`t3 theme clear` removes the default without changing anyone's current theme. `t3 theme show` lists -the default and published themes. - ### Publish a theme -Save a theme exported from T3 Code into `~/.t3/userdata/themes/` on the server, or the `themes` -directory under your custom state directory. The filename supplies the theme ID: `nightfall.json` -can be selected with `t3 theme set nightfall`. Keep the filename stable when updating its colors. -Do not use `system`, `light`, `dark`, or a built-in theme's ID. +Save an exported theme JSON into `~/.t3/userdata/themes/` on the server (or `themes/` under your custom state directory). The filename sets the theme ID (e.g. `nightfall.json` → `t3 theme set nightfall`). Avoid reserved IDs (`system`, `light`, `dark`, or built-in theme IDs). -For an integration that generates a palette, this shorter format also works: +You can also use a minimal palette format—T3 Code generates the remaining tokens: ```json { @@ -126,19 +76,11 @@ For an integration that generates a palette, this shorter format also works: } ``` -Set `appearance` to `light` or `dark` and supply hex colors for `canvas` and `accent`. T3 Code -generates the rest. The optional `colors` overrides use the names in the theme editor's advanced -view. An optional `css` string adds [custom CSS](#custom-css). - -Write updates to a temporary file and rename it into place so clients never read a partial theme. -Invalid files are not published. +Include an optional `css` string for [custom CSS](#custom-css). Write updates atomically (temp file + rename) so clients never read a partial file. ### Background image -A published theme can have a full-size background image. Ask an agent, for example "use -~/Pictures/wallpaper.jpg as T3 Code's background", or save a JPEG, PNG, or WebP file of up to -16 MB beside the theme file: `nightfall.jpg` beside `nightfall.json`. The theme's CSS decides -where the image shows: +Place a JPEG, PNG, or WebP file (up to 16 MB) next to a published theme file with the same base name (e.g. `nightfall.jpg` beside `nightfall.json`), or ask an agent to set one. Reference it in the theme's CSS: ```css [data-workspace-area="conversation"] { diff --git a/docs/user/background-service.md b/docs/user/background-service.md index b9df9c0662195..36ad31d2dd17b 100644 --- a/docs/user/background-service.md +++ b/docs/user/background-service.md @@ -1,208 +1,84 @@ # Running T3 Code in the background -On Linux, macOS, and Windows, T3 Code can run as a service for your user so you -do not need to keep a terminal open. +Run T3 Code as a background user service on Linux, macOS, or Windows so your host stays reachable without keeping a terminal open. ## Manage the service -Install the `t3` CLI first ([Install T3 Code](./install.md#command-line)), then -run these commands on the machine that will host T3 Code: - -| Task | Command | -| ------------------------------------- | ---------------------- | -| Set up access from your other devices | `t3 up` | -| See how your other devices reach it | `t3 status` | -| Install and start | `t3 service install` | -| Inspect status and log location | `t3 service status` | -| Move to a newer release | `t3 update` | -| Restart | `t3 service restart` | -| Stop and remove from startup | `t3 service uninstall` | - -The service never writes a pairing code to its log. To connect a device, run -`t3 pair` on the host, or `t3 up` to set up access from your other devices. - -Uninstalling the service leaves your projects, threads, and settings intact. -Running `t3 service install` again repairs a service that `t3 service status` -reports as broken. - -`t3 update` downloads the newest release on your channel and switches `t3` -and the service to it. Restarting interrupts running agent turns, terminals, -and remote clients, so it asks first; answer no and the service keeps running -the old version until you run `t3 service restart`. Pass `--yes` from a -script. A server you started by hand is left running; stop and start it again -to pick up the new version. Wait for any remote update already in progress -before updating; to match a remote client's version, follow -[Updating T3 Code](./updating.md). - -Pass an exact version (`t3 update 0.0.42`) to pin one, `--channel nightly` to -switch trains, or `--allow-downgrade` to move backwards. `preview` is a -maintainers' test train: its builds can be broken and are never offered as -updates, so the installer and `t3 update` ask for confirmation before -installing one. - -`t3 uninstall` removes the background service, the `t3` launcher, and the -downloaded versions after showing you the list and asking once. Your projects, -threads, and settings under `~/.t3/userdata` are kept, along with `service.env` -under T3 home. Pass `--yes` from a script. +Install the `t3` CLI first ([Command line](./install.md#command-line)), then run these commands on the host machine: -## Local network access +| Task | Command | +| --------------------------------------- | --------------------------------------------------------- | +| Set up access from other devices | `t3 up` | +| Check how other devices reach it | `t3 status` | +| Install and start (or repair) | `t3 service install` | +| Check status and log path | `t3 service status` | +| Update to a newer release | `t3 update` | +| Restart | `t3 service restart` | +| Stop and remove from startup | `t3 service uninstall` | +| Remove service, launcher, and downloads | `t3 uninstall` (keeps `~/.t3/userdata` and `service.env`) | + +- Pairing codes are never written to logs; run `t3 pair` or `t3 up` on the host to connect a device. +- `t3 update` asks before restarting (pass `--yes` in scripts). Pin a version with `t3 update 0.0.42`, switch tracks with `--channel nightly`, or downgrade with `--allow-downgrade`. -A new service answers only on this machine. Other devices reach it through -T3 Connect, or directly once you choose the local network in `t3 up` (or run -`t3 up --lan`, which sets `T3CODE_LAN=true` in `service.env`). It then listens on -your local network and Tailscale addresses, so the desktop and mobile apps on -the same network connect directly instead of through T3 Connect. It still does -not answer on public addresses. Anyone on the same network can reach the port, -so a pairing code is all that keeps them out. The hosted web app at app.t3.codes -stays on T3 Connect, because browsers block plain HTTP from an HTTPS page. +## Local network access -A service installed before `T3CODE_LAN` existed keeps listening on the local -network. `t3 status` says so, and `t3 up --no-lan` turns it off. Any -`T3CODE_HOST` value replaces this setting. +New services bind to localhost only. Run `t3 up --lan` (sets `T3CODE_LAN=true` in `service.env`) to listen on LAN and Tailscale addresses for direct desktop/mobile connections, or `t3 up --no-lan` to disable it. Anyone on that network can reach the port (gated by pairing). `T3CODE_HOST` overrides `T3CODE_LAN`. Hosted `app.t3.codes` always uses T3 Connect. ## Configure the service environment -Put custom environment variables in `service.env` under the service's T3 home -directory, normally `~/.t3/service.env`. This file survives service installation -and updates. For example: +Add `KEY=VALUE` entries to `service.env` in your T3 home directory (`~/.t3/service.env` by default). Values are literal (quote spaces or `#`; no shell expansion) and survive installs and updates. ```dotenv T3CODE_PORT=3773 T3CODE_HOST=127.0.0.1 ``` -Use `KEY=VALUE` entries, quoting values that contain spaces or `#`. Values are -literal: shell commands and variable expansion are not evaluated. Entries -override the inherited service environment, except for `PATH`, `T3CODE_HOME`, -`T3_BOOT_SERVICE_UNIT`, and `T3_SERVICE_LAUNCHER_CONTEXT` (including case variants). - -Run `t3 service restart` after changing the file. Changes apply when the service -starts again; switching the server version alone keeps the current values. -For a service installed before env-file support, run `t3 service install` once -with an up-to-date CLI. -A missing file is ignored; other read failures stop service startup. -If the file contains credentials, restrict access to that file with `chmod 600` -(for the default T3 home, `chmod 600 ~/.t3/service.env`). +- `PATH`, `T3CODE_HOME`, `T3_BOOT_SERVICE_UNIT`, and `T3_SERVICE_LAUNCHER_CONTEXT` cannot be overridden here. +- Run `t3 service restart` after editing (and `chmod 600 ~/.t3/service.env` if it holds secrets). ## Platform support -Linux needs systemd user services. Setup enables lingering so T3 Code starts at -boot and keeps running after logout. If this needs administrator permission, -setup prints a recovery command before changing the service. - -macOS starts the service when you log in and stops it when you log out. Keep the -Mac logged in and awake for unattended remote access. Installing over SSH while -nobody is logged in at the Mac's screen can fail at the final start step; the -service is still installed and will start at the next login. +- **Linux**: Requires systemd user services with lingering enabled so T3 Code starts at boot and survives logout. +- **macOS**: Starts at login, stops at logout. Keep the Mac logged in and awake for unattended access. If agents can't read Desktop/Documents/Downloads, grant Full Disk Access to the `t3` path in `~/Library/LaunchAgents/com.t3tools.t3code.service.plist`. +- **Windows**: Runs windowless via Task Scheduler (`t3code--`) while signed in and auto-restarts on exit. Lock the screen instead of signing out for unattended access. -Windows starts the service when you log in and stops it when you sign out. It -runs without a window as the `t3code--` task in Task Scheduler, and Task -Scheduler starts it again within a minute if it exits. Lock the screen instead -of signing out, and keep the PC awake, for unattended remote access. Installing -over SSH while nobody is signed in at the PC can fail at the final start step; -the service is still installed and will start at the next sign-in. +> Note: Signing out of T3 Connect does not stop or uninstall the background service. -`t3 up` installs the service when you set up T3 Connect, but the two are managed -separately. Signing out of T3 Connect does not stop or uninstall the service. +## Keep the server responsive under memory pressure (Linux) -## Keep the server responsive when agents use all memory - -On Linux, agents already run with lower priority than the server. When they -fill the machine's memory, though, the kernel may still slow down or stop the -server, because only an administrator can reserve memory for it. Run, as your -normal user: +On Linux, agents run at lower priority than the server, but heavy memory use can still trigger the OOM killer. Run as your normal user: ```sh t3 service protect ``` -It shows the system settings it will change, asks before applying them, and -then asks for your sudo password. If the machine runs Tailscale or SSH, it -also offers to protect them, so you can still reach the machine. Memory -protection takes effect at once. The server's protection from the kernel's -out-of-memory killer takes effect after `t3 service restart`. `t3 service status` reports whether -the protection is in place, and `t3 service protect --undo` removes it. +It previews system changes, asks for confirmation and `sudo`, and optionally protects Tailscale and SSH too. Run `t3 service restart` for OOM-killer protection to take effect, or `t3 service protect --undo` to remove it. ## Troubleshooting -Start with `t3 service status` on the host. It prints the log path and, on Linux, -checks whether the installed service is running, enabled, and allowed to survive -logout. - -If it stops when your SSH session closes, check for `linger-disabled`. An -administrator can enable lingering with: +Run `t3 service status` on the host to see the log path and health checks: -```sh -sudo loginctl enable-linger "$(id -un)" -``` +| Status | Fix | +| -------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- | +| `linger-disabled` | Run `sudo loginctl enable-linger "$(id -un)"` (or `ssh -t your-server '...'`), then retry setup as your normal user. Never run T3 Code as root. | +| `linger-unavailable` | Check `loginctl show-user "$(id -un)" --property=Linger` and verify `systemd-logind`. | +| `user-manager-unavailable` | Run `systemctl --user status` in a login session to verify systemd user support. | +| `service-disabled` / `service-stopped` | Check the log and `systemctl --user status t3code.service`, then run `t3 service install`. | +| `restart-pending` | Run `t3 service restart` to switch to the newly installed version. | -Over SSH, allow sudo to prompt: +For T3 Connect issues, see [T3 Connect troubleshooting](./t3-connect-troubleshooting.md). -```sh -ssh -t your-server 'sudo loginctl enable-linger "$(id -un)"' -``` - -Then retry service setup as your normal user. Run only the `loginctl` command -with sudo; running T3 Code as root creates a separate installation and Connect -identity. Without administrator access, run `t3 serve` in a terminal and keep -that session open. - -| Status problem | Next step | -| --------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ | -| `linger-unavailable` | Run `loginctl show-user "$(id -un)" --property=Linger` and check that systemd-logind is available. | -| `user-manager-unavailable` | Run `systemctl --user status` in a login session for the service user; check your distribution's systemd user-session support. | -| `service-disabled` or `service-stopped` | Read the log and, on Linux, `systemctl --user status t3code.service`, then use the repair command printed by T3 Code. | -| `restart-pending` | A newer version is installed but the service still runs the previous one. Run `t3 service restart`. | +## Reclaim database space -On macOS, check **System Settings → General → Login Items** if the service no -longer starts at login. If agent work cannot access Desktop, Documents, or -Downloads, it may need Full Disk Access for the `t3` executable listed in -`ProgramArguments` in -`~/Library/LaunchAgents/com.t3tools.t3code.service.plist`. +T3 Code automatically prunes old internal history while keeping conversations. Older databases that still hold freed space show a **Reclaim** button in **Settings → Maintenance** when at least 1 GiB is reclaimable (pauses the server/agents during repair). -For failures after signing in to T3 Connect, see -[connection troubleshooting](./t3-connect-troubleshooting.md). +For manually started servers (or CLI use), stop any hand-started server or desktop app and run: -## Reclaim database space +```sh +t3 doctor # Interactive repair (auto-stops/restarts a background service) +t3 doctor --dry-run +t3 doctor --fix # Non-interactive recommended repairs +``` -T3 Code removes internal history older than a day on its own while it runs; -your conversations are kept. Databases created before this shrank automatically -still hold the freed space on disk until a one-time offline repair returns it -and turns on automatic shrinking. Settings > Maintenance (web and desktop) or -Settings > Maintenance (mobile) suggests the repair when at least 1 GiB can be -reclaimed. - -When the desktop app or the background service runs T3 Code on that machine, -select **Reclaim** in Settings on web or desktop. T3 Code checks for free disk -space, then stops, repairs the database, and starts again. It is offline while -the repair runs, and running agents stop. If the repair fails, Settings shows -why. - -In other cases, such as a server you started by hand, run `t3 doctor` on the -machine that hosts the environment. It reports the database size and the -space it can reclaim, then asks which repairs to run; -pass `--fix` to run the recommended ones without a prompt (for scripts), or -`--dry-run` to only report. An installed background service for the same data -directory is stopped for the repair and started again afterwards, also when -the repair fails. Quit a server you started by hand, or the desktop app, first: -the repair refuses to touch a database that is in use, and names the server -process that holds it when it can tell. While the repair runs, a server started -for the same data directory, for example by a desktop app connecting over SSH, -is refused until the repair ends. Use `--base-dir` for a different data -directory. - -The repair's time grows with the size of the whole database, not only the -space it reclaims, and can exceed an hour on a large database or a slow disk; -`t3 doctor` shows each step as it runs. It rebuilds the database through a -temporary copy, so it needs free space of about twice the data still in use -(the database size minus the reclaimable space): once in the system temporary -directory (on Linux and macOS, `TMPDIR`, or `/var/tmp` when it is not set) and -once next to the database for its write-ahead log. - -If you upgraded from a version before 0.1.0, its database (`state.sqlite`) is -still kept next to the current one so you can roll back. `t3 doctor` offers to -delete it, but never selects that repair for you and `--fix` skips it: once it -is gone, a version before 0.1.0 starts with no threads or settings. It does -not offer to delete it while any project or thread you have not deleted is -missing from the current database, so the old file stays available for -recovery. +- Needs free disk space of ~2× active data size (in `TMPDIR`/`/var/tmp` and beside the database). Large databases can take over an hour. +- `t3 doctor` optionally offers to remove the legacy pre-0.1.0 `state.sqlite` backup only when all active projects and threads exist in the current database (`--fix` never deletes it automatically). diff --git a/docs/user/browser-import.md b/docs/user/browser-import.md index 194249d691022..a1f5b01b3bfb7 100644 --- a/docs/user/browser-import.md +++ b/docs/user/browser-import.md @@ -1,20 +1,17 @@ # Import browser sessions -The desktop app can import cookies from another browser so you can reuse its signed-in sessions -in the preview browser. +Import cookies from another browser into the desktop app's [preview browser](./browser.md) so you can reuse existing signed-in sessions. -Open **Settings → Browser → Browser profiles → Add profile**, then choose a browser under -**Import from**. Close the source browser before importing, and allow an operating-system keyring -unlock prompt if one appears. +## Import a profile -This is a one-time copy. Later login changes stay separate between the two browsers, and some -sites may still require you to sign in again. +1. Close the source browser. +2. Open **Settings → Browser → Browser profiles → Add profile** and choose a browser under **Import from**. +3. Allow any OS keyring unlock prompt. -On macOS, Safari imports need Full Disk Access. Choose **Allow**, drag T3 Code into the -System Settings permission list, and turn access on. **Continue** becomes available when access -is detected. macOS may require you to quit and reopen T3 Code before the grant applies; reopen -the import wizard afterward. You can revoke Full Disk Access once the import is done. +This is a one-time copy—later login changes stay separate, and some sites may still require signing in again. -On Windows, import supports Firefox, Zen, and Helium profiles that use standard profile encryption. -Other Chromium-based browsers use app-bound encryption and cannot be imported. Partitioned cookies -are skipped on all platforms. +## Platform notes + +- **macOS (Safari)**: Requires temporary **Full Disk Access** (grant in System Settings, quit/reopen T3 Code if macOS requires it, then reopen the import wizard). You can revoke Full Disk Access afterward. +- **Windows**: Supports Firefox, Zen, and Helium profiles using standard encryption. Other Chromium browsers use app-bound encryption and cannot be imported. +- Partitioned cookies are skipped on all platforms. Administrators can disable cookie import via [managed policy](./managed-policy.md#other-capabilities). diff --git a/docs/user/browser.md b/docs/user/browser.md new file mode 100644 index 0000000000000..c93fbb9d1a42b --- /dev/null +++ b/docs/user/browser.md @@ -0,0 +1,31 @@ +# Built-in browser + +T3 Code includes a built-in preview browser beside your conversation so you and your agents can inspect local dev servers, annotate UI issues, record flows, and test web apps without leaving the thread. + +## Open and navigate + +- Open the right panel in a thread and choose **Browser** (or click a running dev server in the thread's **Servers** list). +- **Local vs. remote**: On the desktop app, tabs for your local environment run natively. On web, mobile, or remote environments, tabs stream from the host's headless Chromium (~120 MB one-time download; see [Browser host setup](./remote-access.md#browser-host-setup)). On desktop, tabs you open for a remote environment can also load locally over the [preview tunnel](./remote-access.md#browser-on-a-remote-environment). +- **Find on page**: Press `mod+f` inside a desktop browser tab (or use its **⋮** menu if the page intercepts `mod+f`). +- **Default browser (macOS)**: You can set the desktop app as your [default web browser](./default-browser.md). + +## Profiles, viewports, and settings + +Configure defaults in **Settings → Browser**: + +- **Browser profiles**: Maintain separate cookie/storage profiles and set a **Default browser profile**. Desktop users can copy signed-in cookies from Chrome, Safari, Firefox, Zen, or Helium ([Import browser sessions](./browser-import.md)). +- **Viewport, zoom & appearance**: Set **Default browser viewport** (fill, freeform, or phone/tablet presets with portrait/landscape rotation), **Default browser zoom**, and **Default browser appearance** (system/light/dark). +- **Links & search**: Configure **Open links in** and **Search engine**. + +## Pick elements, annotate, and record + +- **Element picker & annotations**: Pick elements or annotate regions on the page to attach them directly into the composer as inline context chips. +- **Screen recordings**: Record browser interactions directly from the tab toolbar. Configure **Browser recording frame rate**, **Show key presses in recordings**, and **Show mouse presses in recordings** in **Settings → Browser**. + +## Agent browser access + +Agents can open tabs, navigate, click, type, inspect accessibility snapshots, and take screenshots using T3 Code's `preview_*` tools. + +- Toggle **Settings → Browser → Agent browser access** (per environment or project override; takes effect when the next agent session starts). +- **Floating preview**: By default, agent-opened tabs float over chat (**Settings → Browser → Auto-show floating preview**). Turn this off to open them in the right panel instead. +- **Take control**: Click **Take control** before interacting with an agent's tab, and release control when you want the agent to resume. diff --git a/docs/user/cli.md b/docs/user/cli.md new file mode 100644 index 0000000000000..1db46c5f36a99 --- /dev/null +++ b/docs/user/cli.md @@ -0,0 +1,52 @@ +# CLI reference (`t3`) + +The `t3` command runs and manages T3 Code servers, background services, remote access, threads, workflows, and diagnostics. Run `t3 --help` or `t3 --help` for full flags. + +See [Install T3 Code](./install.md#command-line) for installation (`curl -fsSL https://t3.codes/install.sh | sh`, `irm https://t3.codes/install.ps1 | iex`, or `npx t3@latest`). + +## Running and connecting + +| Command | Description | +| ------------------------ | -------------------------------------------------------------------------------------------------------------------------------- | +| `t3 [path]` / `t3 start` | Start a foreground server and open the web app (optionally in a project directory). | +| `t3 serve` | Start the server without opening a browser (`--lan`, `--tailscale-serve`, `--host`, `--port`, `--base-dir`). | +| `t3 app [path]` | Open a directory as a project/thread in the running desktop app. | +| `t3 up` | Interactive setup for remote access (T3 Connect and/or LAN) plus background service (`--connect`, `--lan`, `--no-lan`, `--yes`). | +| `t3 connect` | Manage T3 Connect (`t3 connect`, `status`, `login`, `logout`, `link`, `unlink`). | +| `t3 status` | Show how other devices can reach this host (`--json`). | +| `t3 pair` | Generate a one-time pairing URL / QR code (`--tailscale`, `--scope `). | + +## Background service and updates + +| Command | Description | +| ----------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- | +| `t3 service` | Manage the background service (`install`, `status`, `restart`, `uninstall`, `protect [--undo]`). See [Background service](./background-service.md). | +| `t3 update [version]` | Update `t3` and the service (`--channel nightly`, `--allow-downgrade`, `--yes`). | +| `t3 install` / `t3 uninstall` | Install or remove the `t3` launcher and background service (keeps `~/.t3/userdata`). | + +## Threads, projects, and workflows + +| Command | Description | +| ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `t3 thread` | Script threads on the host (`start`, `send`, `show`, `list`; supports `--wait`, `--json`, `--worktree`, `--provider`, `--model`, `--option`). See [Host scripts](./outside-agents.md#host-scripts-t3-thread). | +| `t3 project` | Manage projects on the host (e.g. `t3 project add --track `). | +| `t3 workflow` | Start and steer durable workflows (`start`, `list`, `show`, `resume`, `cancel`, `questions`, `signal`, `withdraw`, `hooks`, `store`). See [Workflows](./workflows.md). | + +## Environments, auth, themes, and policy + +| Command | Description | +| ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `t3 environment` | Link or manage peer environments (`t3 environment link --pairing-code --access `, `--from `). | +| `t3 auth` | Manage pairing codes, sessions, and T3 Connect device approvals (`pairing create`, `session list/revoke/issue`, `connect-device list/approve/revoke`). | +| `t3 theme` | Manage server-published themes (`set `, `clear`, `show`). See [Appearance](./appearance.md#environment-themes). | +| `t3 policy` | Validate, inspect, and generate MDM/GPO templates for [managed policies](./managed-policy.md) (`check`, `show`, `settings`, `templates`). | + +## Diagnostics and maintenance + +| Command | Description | +| ------------------ | ---------------------------------------------------------------------------------------------------------- | +| `t3 doctor` | Inspect database size and reclaim disk space (`--dry-run`, `--fix`). | +| `t3 browser setup` | One-time Linux host setup (AppArmor sandbox profile, libraries, fonts) for the headless preview browser. | +| `t3 trace summary` | Summarize local server trace latency and errors (`--since 30m`, `--limit 50`). | +| `t3 triage` | Launch Claude Code, Codex, or Antigravity in your terminal with the T3 triage playbook. | +| `t3 feedback` | Send or inspect agent feedback reports (`list [--json]`, `--kind`, `--subject`, `--expected`, `--actual`). | diff --git a/docs/user/composer.md b/docs/user/composer.md index cb6dabcfdf883..5f068ea756e94 100644 --- a/docs/user/composer.md +++ b/docs/user/composer.md @@ -1,89 +1,46 @@ # Messages and context -Give the agent a task in the composer. Add files, quote a previous response, or -include a skill when the task needs more context. +Use the composer to send prompts, attach files, reference threads or pull requests, invoke skills, and steer or queue follow-ups. -Messages can contain up to 120,000 characters. Longer drafts stay in the composer -so you can shorten them or split them into several messages. +## Limits and large pastes -Pasting 32 KiB or more of text adds that fragment as a text-file attachment so -the agent can inspect it without filling the model context. A smaller paste also -becomes an attachment when inserting it would exceed the message limit. On a -hardware keyboard, use `Cmd+Shift+V` on Apple devices or `Ctrl+Shift+V` elsewhere -to keep a large paste editable in the composer instead. +- **Message length**: Up to 120,000 characters. +- **Large pastes**: Pasting 32 KiB+ of text (or any paste that would exceed the message limit) turns it into a text-file attachment so it doesn't bloat the prompt. Use `Cmd+Shift+V` (Apple) or `Ctrl+Shift+V` (Windows/Linux) to paste inline instead. ## Formatting -The composer writes Markdown and shows it styled as you type. When your cursor -is on styled text, its Markdown shows instead, such as `**bold**`, and the -markers edit like any other text: delete them to remove the style, or change -`**` to `*` for italic. The style updates when your cursor leaves. To write -plain Markdown with no styling, turn off **Settings → Chat → Rich text -composer**. Lines starting with `- `, `1. `, `- [ ] `, `> `, `# ` or `---` -become lists, task lists, quotes, headings and rules; ` ``` ` followed by Enter -opens a code block. What you typed is what the agent receives, markers and -numbering included, and `#1234` without a space still looks up a pull request. - -Some styled text containing or touching literal Markdown characters, such as a -bold `path\` or `2*3`, keeps its styling without showing markers. Use formatting -shortcuts or turn off rich text to edit the formatting of those ranges. - -Enter sends. In a list or quote, **Shift+Enter** continues it, and Shift+Enter -on an empty line moves out one level, then leaves it; **Tab** nests a list item -under the one above and **Shift+Tab** moves it back out. In a code block, Enter -starts a new line at the current indentation, **Tab** and **Shift+Tab** indent -the selected lines, and a closing ` ``` ` followed by Enter, or two blank lines -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. +The composer renders Markdown live as you type and reveals raw markers when your cursor enters styled text. The agent receives the exact Markdown you typed. + +- Disable live styling in **Settings → Chat → Rich text composer**. +- Standard Markdown triggers (`- `, `1. `, `- [ ] `, `> `, `# `, `---`, and ` ``` ` + Enter) create lists, quotes, headings, rules, and code blocks. +- In lists/quotes, `Shift+Enter` continues (or exits on an empty line), and `Tab` / `Shift+Tab` indents or outdents. +- In code blocks, `Enter` keeps indentation, `Tab` / `Shift+Tab` indents selected lines, and closing ` ``` ` + Enter (or two blank lines) exits the block. ## Attach files -Attach up to 100 files per message. Each image can be up to 10 MiB, with at most -80 MiB of images in one message. Other files, including videos, can be up to -50 MiB each, subject to the environment's upload support and limit. The agent -receives them on the environment's machine. Provider and model limits still -apply, including images already in the conversation. A video attachment gives -the agent a file path; only [Antigravity](./providers-antigravity.md#skills-and-attachments) -sends supported videos to Gemini models as video. - -Uploads begin when you add an attachment. All uploads must finish before the -message can send. Retry or remove a failed upload. On web and desktop, reloading -before an upload finishes requires you to attach that file again. - -You can drag or paste images into the web or desktop composer. HEIC and HEIF -photos are converted to JPEG there and when selected from the mobile photo -library; photos over the image limit are also resized to fit. On mobile, you can -also send files to T3 Code through another app's system share sheet. -On Android, you can also drag images from another app into the message input -in split screen. +Attach up to **100 files** per message: + +- **Images**: Up to 10 MiB each, 80 MiB total per message. HEIC/HEIF photos are converted to JPEG, and oversized photos are resized automatically. +- **Other files (including videos)**: Up to 50 MiB each (subject to environment limits). Video attachments pass a file path; only [Antigravity](./providers-antigravity.md#skills-and-attachments) sends supported videos natively to Gemini models. + +Files upload to the environment's machine as soon as you attach them, and all uploads must finish before sending. Provider and model limits still apply. + +- **Web and desktop**: Drag, paste, or pick files. Reloading before an upload finishes requires re-attaching. +- **Mobile**: Pick files, share into T3 Code via the system share sheet, or drag images in Android split screen. See [images and videos](#images-and-videos-in-messages) for previewing and saving media. ## Send while the agent is working -On web and desktop, choose **Settings → Chat → Follow-up behavior** to queue -new messages for a later turn or steer the running turn immediately. The setting -applies to this client; already queued messages keep their place. Queued messages -are saved on the server and can be edited or removed before they send. -When Enter sends, `Cmd+Enter` on macOS or `Ctrl+Enter` on Windows and Linux uses -the opposite action: it steers when your default is Queue and queues when your -default is Steer. -A slash command such as `/compact` or `/context` waits for the current turn to -finish, because a command steered into a turn would replace the agent's task. -Sending a queued command now moves it to the front of the queue. [Goal](#goals) -commands are the exception: some can stop the current turn. -If your **Send shortcut** requires `Cmd+Enter` or `Ctrl+Enter`, that shortcut uses -your default follow-up behavior; add **Shift** to use the opposite action. This -applies only to multiline messages when you choose the multiline send option. - -Use `Cmd+Shift+Enter` on macOS or `Ctrl+Shift+Enter` on Windows and Linux to send -the oldest queued message as a steer. This leaves the current draft intact and -requires an active turn that supports steering. If that shortcut sends the opposite -action for your draft, move focus outside the composer to steer the queued message. Change -`thread.steerQueuedMessage` in **Settings → Keybindings** to use another shortcut. To make -`Cmd+Enter` or `Ctrl+Enter` steer the oldest queued message when the composer is empty, add -this rule to your [keybindings file](keybindings.md#edit-the-configuration-file): +Choose your default follow-up behavior in **Settings → Chat → Follow-up behavior** (per client): + +- **Queue**: Holds the message on the server for the next turn. +- **Steer**: Injects the message into the running turn (when supported by the agent). + +Shortcuts while a turn is running: + +- **Opposite action**: `Cmd+Enter` (macOS) or `Ctrl+Enter` (Windows/Linux) uses the non-default action. If your send shortcut already requires `Cmd/Ctrl+Enter`, add `Shift`. On mobile, long-press the send button or use `Cmd/Ctrl+Return` on a hardware keyboard. +- **Steer oldest queued message**: `Cmd+Shift+Enter` (macOS) or `Ctrl+Shift+Enter` (Windows/Linux) sends the first queued message as a steer without touching your current draft. Remap `thread.steerQueuedMessage` in **Settings → Keybindings**, or add a rule in your [keybindings file](./keybindings.md#edit-the-configuration-file) to trigger it on `mod+enter` when the composer is empty: ```json { @@ -93,33 +50,19 @@ this rule to your [keybindings file](keybindings.md#edit-the-configuration-file) } ``` -Press `Option+Up` on macOS or `Alt+Up` on Windows and Linux with the cursor at the -start of the composer to edit the most recently queued message. Change -`thread.editQueuedMessage` to use another shortcut. +- **Edit most recently queued message**: `Option+Up` (macOS) or `Alt+Up` (Windows/Linux) at the start of the composer (`thread.editQueuedMessage`). -Mobile has the same choice under **Settings → Chat**. While a turn is -running the send button shows which action it will take. Long-press it to use the -other action for a single message. From a hardware keyboard, `Cmd+Return` -(`Ctrl+Return` on Android) uses the other action, or `Cmd+Shift+Return` -(`Ctrl+Shift+Return`) when Return inserts a new line. The button only offers -Steer when the running agent supports it. +Slash commands (such as `/compact` or `/context`) wait for the current turn to finish rather than steering into it. [Goal](#goals) commands are the exception. ## Queue messages offline on mobile -Mobile keeps local copies of draft attachments, so you can preview them and queue -messages while disconnected. Uploads resume when you reconnect. Drafts and queued -messages survive app restarts. Signing out of T3 Connect keeps that work on your -device until you sign back into the same account. +Mobile keeps local copies of draft attachments so you can preview them and queue messages offline. Uploads resume on reconnect, and drafts/queued messages survive app restarts and T3 Connect sign-out (restored when signing back into the same account). -## Custom models +## Custom models and defaults -On web and desktop, use Settings → Providers → **Models** to add an unlisted model with a custom -name and options. Only options supported by the provider integration affect turns. Antigravity -uses its account catalog and does not support custom models. - -To rename a built-in model on every client, edit the server's `settings.json` in its `userdata` -directory. Add a custom model entry with the built-in model ID and a new name under that provider -instance: +- **Remembered defaults**: T3 Code remembers your last provider, model, and options for new threads. A project's configured model overrides this. Leaving reasoning level or service tier unset uses the provider's default. +- **Custom models**: Add unlisted models in **Settings → Providers → Models** (web and desktop; not supported for Antigravity, which uses its account catalog). +- **Rename a built-in model across all clients**: Add an entry in the server's `userdata/settings.json`: ```json { @@ -132,324 +75,101 @@ instance: } ``` -## Model defaults - -T3 Code remembers your provider, model, and model options for new threads. A -project's configured model takes precedence; resetting that project setting -returns to the remembered selection. - -Leaving reasoning level or service tier unset uses the provider's own configuration. - ## Quote an assistant response -On web and desktop, select text within one assistant response and choose -**Cite in composer**. You can add a comment about the quote and write instructions -around it. +- **Web and desktop**: Select text in an assistant message and click **Cite in composer**. Click the pencil on the chip to add or edit a comment; click the chip to jump back to the source. +- **Mobile**: Long-press an assistant response, select text, and tap **Cite**. Tap a quote chip to edit its comment, remove it, or jump to the source message. -Select the quote in a draft or sent message to return to its source. If the source -is unavailable or has changed, the saved quote remains readable. - -The chip shows your comment when it has one, or a short quote preview otherwise. Use the pencil -button to add or change the comment. To remove the citation, place the caret beside its chip and -delete it like other inline context. Copying, reloading, and restoring a -[stashed prompt](#prompt-stash) keep each comment -with its quote, and sending tells the agent which words were quoted and which comment you wrote. -The quoted text and comment count toward the message limit. - -On mobile, long-press an assistant response, adjust the text selection, and choose -**Cite** to insert a quote at the composer cursor. If the passage appears more than -once in that section, choose its source occurrence. Select more surrounding text -if a short passage appears too often. Tap a quote in a draft to add -or edit its comment, or to remove it. To open the source message, tap a quote in -a draft or sent message, then choose **Go to message**. +Quoted text and comments count toward the message length limit and are preserved across copy/paste and [stashed prompts](#prompt-stash). ## Recall a sent prompt -Press `ArrowUp` in an empty composer to bring back the last prompt you sent in this thread. Press -`ArrowUp` again to go further back, and `ArrowDown` to come forward. Moving forward past the newest -prompt clears the composer. Recall walks the prompts loaded in the thread. Attachments, terminal -context, and other extras from the original message are not restored, only the text you typed. A -composer that holds an attachment or a picked element does not count as empty. - -When the composer has text, the arrow keys move the caret as usual. Recall takes over only while -the text is an unedited recalled prompt, with the caret on the first visual line for `ArrowUp` or -the last visual line for `ArrowDown`, counting wrapped lines. Editing a recalled prompt turns it -into a normal draft. +Press `ArrowUp` in an empty composer to cycle backward through earlier prompts in the thread, and `ArrowDown` to move forward. Only prompt text is restored (not attachments or context chips). Editing a recalled prompt turns it into a normal draft. ## Suggested next prompt -Turn on **Suggest next prompt** in Settings > Labs. After a Claude or Codex turn completes, the -empty composer shows a predicted next message. Press `Tab` to fill it in, then edit or send it, or -press `Escape` to dismiss it. Each suggestion is one extra request that reuses the turn's prompt -cache, so it uses a little of your plan's usage. Claude skips suggestions on the first turn of a -thread and near usage limits. Codex needs version 0.165 or later; if T3 Code manages -Codex, update it in Settings > Providers. Codex follows a change to the setting at once; open Claude -threads follow it after they restart. Suggestions show on web and desktop. +Enable **Settings → Labs → Suggest next prompt** (web and desktop) to show a predicted next message in the empty composer after a Claude or Codex turn completes. + +- Press `Tab` to accept or `Escape` to dismiss. +- Each suggestion uses one cached request against your plan's usage. Claude skips suggestions on the first turn and near usage limits. +- Codex requires CLI version 0.165+ (update in **Settings → Providers**). Open Claude threads pick up the setting after restarting. ## Edit an earlier prompt -On web and desktop, choose **Edit from here** beneath a sent message to rewind -the conversation to before that message. Choose **Revert and keep changes** to -leave workspace files as they are, or **Revert files too** to put the workspace back -to its checkpoint from before that message. That also undoes edits you made yourself. -File restore is only offered for threads running in a worktree, and it is -refused when another thread or agent session also uses that directory, a folder -inside it, or a folder that contains it, since -restoring would erase their changes. Completed subagents belonging to the reverting -thread do not block restoring that same worktree, provided they have no queued or -active work, pending requests, or background tasks. A thread that works in the project -directory rewinds the conversation only. The selected prompt and its attachments return to the composer for editing and -resending. Any unsent draft stays above the restored prompt. - -This removes the selected message and later conversation from the active thread -and provider history. It does not undo external actions or separate provider -memory. The action is available only when the provider supports rewind. +On web and desktop, select **Edit from here** under a sent message to rewind the conversation to before that message and return it to the composer: -## Prompt stash +- **Revert and keep changes**: Rewinds the conversation only. +- **Revert files too**: Restores workspace files to the checkpoint before that message (including your own edits). Only available for worktree threads when no other thread or active session shares that directory. -On web and desktop, press `Cmd+S` on macOS or `Ctrl+S` on Windows and Linux to save -the current prompt and its attachments for later. Wait for uploads to finish first. -With an empty composer, the same shortcut restores a single stash or opens the -stash menu when there are several. - -The stash holds up to 100 prompts, and images take up most of its browser -storage. When it is full, stashing leaves the composer as it is; restore or -delete a stash to make room. Stashes are never discarded automatically. - -Stashes containing uploaded files must be restored in their original environment. -Those files are retained for 24 hours. After an upload expires, restore the prompt -and use **Attach again** or remove the missing file before sending. - -## Voice input on web and desktop - -Use the composer's microphone or `mod+shift+d` to dictate into your draft. Audio -is transcribed on an environment you choose in **Settings → Voice**, or on the Mac -with Apple Speech in the macOS desktop app; nothing is sent until you choose one. -See [Voice input](./voice-input.md). - -## Voice input on mobile - -Use the composer's microphone to record, then confirm to transcribe. Text is -inserted where your selection was when recording started, ready for you to review -and edit before sending. - -By default, audio stays on the phone. Local transcription needs a supported iPhone -with iOS 26 or later, or Android 12 or later with compatible Google speech services. -To use a paired environment instead, open **Settings → Voice → Transcribe on**, -choose the environment, and confirm. Finished recordings go only to that environment, -even when a draft belongs to another one. This also works on phones without local -speech recognition. If the chosen environment disconnects, dictation stops; it never -switches hosts. Choose **This device** to revoke access and discard pending audio. -For [cloud dictation](./voice-input.md#choose-where-audio-goes), open **Cloud providers** -under the environment in **Settings → Voice** and confirm which provider may receive recordings. -On Android, keep T3 Code open while recording and transcribing. - -On-device dictation may need a network connection to download a speech model the -first time. After that it works offline for that language. iPhone dictates in the -first of your preferred languages (**Settings → General → Language & Region**) -that Apple’s speech model supports. If none is supported, it tries the app’s -language. Android transcribes on the device while you -record and finishes after you stop. Recordings can be up to five -minutes long. Canceling or an audio interruption discards the recording and -preserves your existing draft. Navigating to another screen keeps dictation active; -use the floating controls to finish or cancel. While recording, the screen stays -awake; it can sleep normally once recording stops. - -Choose a preferred order in **Settings → Voice**. Voice input requests the first -connected microphone in the list. The list mixes kinds (built-in, other wired, other -Bluetooth, and CarPlay on iOS) with wired and Bluetooth devices you have dictated -with, listed by name. Drag to rank them together: -for example, put **Other Bluetooth** above your AirPods so a new headset is preferred -while the AirPods microphone stays low. By default, CarPlay comes after the built-in -microphone on iOS. Swipe a device left to forget it. Android may use another input -when the preferred microphone cannot be routed. Devices with the same name may share -a saved preference, but simultaneous same-name inputs remain separately selectable. - -T3 Code deletes the temporary recording from your phone after transcription or -cancellation. The transcript stays in your draft until you send the message to the agent. +Rewinding removes later messages from the active thread and provider history (requires provider rewind support), but cannot undo external actions or separate provider memory. -## Queued messages +## Prompt stash -On web and desktop, the composer shows **Interrupt** while the agent is working and the draft is -empty. Adding text or attachments replaces it with a send button that shows your -[Follow-up behavior](#send-while-the-agent-is-working): a queue icon for Queue or a steer arrow for -Steer. Click it or press your send shortcut to use that action. Hold `Cmd` on macOS or `Ctrl` on -Windows and Linux to switch the button to the opposite action, then click, or use the opposite-action -shortcut described above. - -On web and desktop, queued messages appear at the end of the thread as dashed messages that have -not been sent yet. On mobile they appear above the composer. Each shows its text and any attached -images. **Send now** sends a message right away, into the running turn if there is one. While a -turn runs, a slash command moves to the front of the queue instead. You can also edit or -remove it. - -If you stop the agent or the server restarts, queued messages keep their order and are held. -Press **Resume** in an empty composer to continue. For stopped runs and usage limits, -this uses the provider's native continuation without sending a new prompt. If the provider -does not support it, send a message to continue instead. If the original request never reached -the provider, Resume sends that request again. - -Sending a new message also resumes the queue, unless it steers a turn that is already -running. You can edit or remove held messages without starting them. - -The pencil on a queued message opens it in the composer for editing. The original message -stays in the queue until you save, and it is highlighted while you edit. The message's -attachments appear above the text with a remove control, and new images can be added the usual way. -The checkmark saves the queued message in place; **Cancel** next to it leaves it unchanged. Whatever -you had typed in the composer before starting the edit is restored afterwards. If the queued -message starts or is removed while you are editing, the edit ends: changed content moves into the -composer when it is empty, and is discarded otherwise. +On web and desktop, press `Cmd+S` (macOS) or `Ctrl+S` (Windows/Linux) to stash the current draft and its attachments (wait for uploads to finish first). Press the same shortcut in an empty composer to restore the stash (or open the stash menu if you have multiple). -## Commands and skills +- Holds up to 100 prompts in browser storage; stashes are never auto-deleted. +- Stashes with uploaded files must be restored in their original environment. Uploads expire after 24 hours; use **Attach again** or remove expired files before sending. -Type `/` for commands or `$` to add a skill from the selected environment and -provider. On mobile, both are also available before starting a thread on -**New task**. +## Voice input -The slash menu also includes skills unless you turn off **Settings → Chat → -Show skills in slash menu**, under Advanced. Only skills enabled for the provider are listed. +Dictate into the composer with the microphone button or `mod+shift+d` (web and desktop). Audio stays on-device or goes only to an environment/provider you explicitly choose in **Settings → Voice**. See [Voice input](./voice-input.md) for setup, mobile dictation, and microphone priority. -After you add or change skills, plugins, or MCP servers, use **Restart agent -session** in the command palette on web and desktop. The conversation continues, -and your next message starts the agent again with the new setup. +## Queued messages -Provider commands must start the message to run. T3 Code commands such as -`/model` and skill mentions work on any line. +Queued messages appear at the end of the thread (web/desktop) or above the composer (mobile). From a queued message you can: -Send `/compact` in an existing conversation to reduce context usage when the -provider supports it. +- **Send now**: Injects it immediately into a running turn (or moves a slash command to the front of the queue). +- **Edit**: Opens the message and its attachments in the composer without losing your existing draft. +- **Remove**: Cancels the queued message. -Send `/clear` on its own, or pick it from the slash menu, to start a fresh session -in the same thread. Your next message goes to a new provider session that doesn't see the -earlier messages, and the thread marks where it began with **New session**. -Earlier messages and diffs stay in the thread. Dismiss the notice above the -composer to keep the current session instead. +If you stop the agent or the server restarts, queued messages pause in order. Click **Resume** in an empty composer (or send a new message) to continue. When the provider supports native continuation, **Resume** continues without sending a new prompt. -On web and desktop, turn on **Context window** in **Settings → Appearance → -Thread details** to see context usage in the thread details card. It appears -once the provider reports usage. +## Commands and skills -Claude instances can also compact idle threads for you. See -[compact long conversations](./providers-claude.md#compact-long-conversations). +Type `/` for commands or `$` for skills from the selected environment and provider. + +- Skills also appear in the `/` menu unless you disable **Settings → Chat → Show skills in slash menu** (under Advanced). +- Provider commands must start the message; T3 Code commands (like `/model`) and `$` skills work on any line. +- `/compact` reduces context usage when supported by the provider. +- `/clear` starts a fresh provider session in the same thread (earlier messages and diffs stay visible above a **New session** divider). +- After adding or changing skills, plugins, or MCP servers, run **Restart agent session** from the command palette so your next message picks up the new config. +- Turn on **Settings → Appearance → Thread details → Context window** to view reported context usage. For automatic idle compaction on Claude, see [compact long conversations](./providers-claude.md#compact-long-conversations). ## Goals -With Codex, Claude, and OpenCode 2.2.5 or later, send `/goal` followed by what "done" means, for example -`/goal all tests in packages/api pass`. The agent keeps working across turns -until it judges the goal met. The thread shows **Goal** while it works, and a -line at the end of the thread (above the composer on mobile) shows the goal and -its progress. - -- `/goal` alone shows the current goal. `/goal clear` removes it. -- Codex and OpenCode also support `/goal pause` and `/goal resume`. Stopping - their goal pauses it. Codex also pauses when its work ends without meeting the goal. -- Stopping Claude ends the current turn, but the goal stays set. Claude checks it - again at the end of your next message. -- Sending a new goal, or `/goal resume`, while the agent works stops the current - turn and starts the goal, unless you queue it. `/goal clear` and `/goal pause` - stop the turn only when it is working on the goal. Other goal commands wait for - the turn to end. +With Codex, Claude, and OpenCode 2.2.5+, send `/goal ` (for example, `/goal all tests in packages/api pass`) so the agent keeps working across turns until the goal is met. + +- `/goal` shows the current goal; `/goal clear` removes it. +- Codex and OpenCode support `/goal pause` and `/goal resume` (stopping pauses the goal). +- On Claude, stopping ends the current turn but keeps the goal active for your next message. +- Sending a new goal or `/goal resume` while working interrupts the current turn unless queued; `/goal clear` and `/goal pause` interrupt only when the agent is actively working on the goal. ## Context in your message -Context you attach lands where your cursor is, as a chip inside your text: a terminal excerpt, -a review comment from a diff or file, a preview annotation, or a file. You can type before and -after a chip, move it by cutting and pasting, and delete it like a character. Hover a chip for -its brief details. Select a terminal excerpt to open its captured output, or select a review -comment, picked element, or preview annotation to open its full details. Chips read as "Terminal -excerpt, Terminal 1 lines 3-4" and similar to screen readers. - -A pull request appears as its icon and number. Its color reflects whether it was open, draft, -merged, or closed when it was attached. Select it to inspect the captured title and branches, -then choose **Open pull request** to visit the pull request. On web and desktop, type `#` to browse the newest -pull requests in the current project's repository. Pull requests linked to the thread are included -from any repository and listed first, after any exact number match. Continue typing digits to filter the recent list -by any part of its pull request numbers. A complete number is also resolved directly, even when that -pull request is older than the recent list. Type a single word after `#` to search pull requests in -the repository by text. Choose a result to insert it as a chip. - -Another thread can be context too. Type `@` followed by part of its title to pick one from -the same server, or from a machine it links to while the Linked environments beta is on; those -show the machine's name. On web and desktop you can also drag a thread out of the sidebar and -drop it on the composer; a multi-selection drops together. On any client, **Copy thread** copies a -link to the thread that pastes into a composer as its chip. The chip shows the thread's -current title and opens it when selected. Your prompt only carries a reference: the agent reads the thread's -history on demand, so attaching a long thread costs nothing until the agent looks. Attaching a -thread does not change it, and the agent cannot send messages to it unless you ask. - -A thread from a linked machine, picked, pasted or dropped, stays a reference that the agent reads -on that machine. A pasted link to a thread on any other machine stays a link. Dropping a thread -from any other environment attaches a saved transcript file. The source -environment must be connected and up to date. The transcript includes the visible history and -saved text context at the time of the drop; later messages and the contents of attached files -are not copied. The agent can read the saved transcript after the source disconnects. Normal -file attachment limits apply. - -Type `@` and part of a model or provider name, such as `@opus`, to name that model for the -agent, for example when delegating. It does not change the thread's model. Join words with -`:`, `/` or `-`, as in `@opus:opencode`. - -Images keep their thumbnail shelf above the text and also get a chip at your cursor, so you can -say exactly which image you mean. Deleting an image chip leaves the image on the shelf; removing -the thumbnail asks first when the image is still mentioned in your text, then removes both. Files -exist only as chips: deleting a file's last chip removes the file from the message. - -Copy text that holds chips and paste it into another draft, in the same thread or another one, -and the chips come along with what they point to. Images and files are fetched again from the -environment they came from; while that happens the chip shows a dashed outline, and if it cannot -complete T3 Code tells you and leaves the chip for you to remove or replace. A chip whose -context is no longer available shows the same dashed outline; hover it for what to do. - -Copying a message with the copy button, or copying text out of it, gives other apps readable -Markdown with a link in place of each chip. Older messages that were sent before chips still -show their context. Stashing a prompt keeps its chips and what they point to; restoring brings -them back. - -On mobile, tap a chip to inspect its content. File references open the current file; attached -files show the copy that was attached to the message. +Attached context—files, terminal excerpts, diff/file review comments, preview annotations, pull requests, and threads—appears as inline chips at your cursor. Click a chip to inspect or open its source; copy/paste and [Prompt stash](#prompt-stash) preserve chips across drafts. -## Attached files +- **Pull requests (`#`)**: On web and desktop, type `#` to browse recent PRs in the current repository (linked PRs appear first), type digits to match by number, or type a word to search by text. +- **Threads (`@`)**: Type `@` and part of a thread title to reference a thread on the same server (or on a linked machine when Linked environments is enabled). You can also drag threads from the sidebar onto the composer, or paste a copied thread link. The prompt carries only a reference—the agent reads the thread on demand. Dropping a thread from an unlinked environment attaches a snapshot transcript file instead. +- **Models (`@`)**: Type `@` and part of a model or provider name (e.g. `@opus` or `@opus:opencode`) to reference a model in your prompt (such as for delegation) without changing the thread's model. +- **Images vs. files**: Images keep a thumbnail shelf above the composer plus optional inline chips; files live only as inline chips (deleting the last chip removes the file). -Select a file chip in your draft or a sent message to preview it. Code and JSON use syntax -highlighting; Markdown, HTML, CSV, and TSV offer rendered and raw views. Audio files have -playback controls. Large text files show a limited preview; save the file to read it in full. +## Attached files -On web and desktop, files open beside the conversation with the same controls as a workspace -file: a header row with the view toggle, **Copy contents** and **Save file**. On mobile, documents -open in the same file screen as workspace files; its menu holds **Copy contents**, **Save or -share** and **Open in file viewer**. Pictures, videos and PDFs keep their native viewers, and -other document formats such as Word or Pages open in the device's own viewer when it has one. -If nothing on the device can show a format, save or share it to open it elsewhere. A ZIP up to -50 MB opens as a folder list on every surface; on mobile, select a file inside it to preview, -save, or add it to chat. +Select any file chip in a draft or sent message to preview it (syntax-highlighted code/JSON, rendered/raw Markdown/HTML/CSV/TSV, audio playback, and ZIP folder browsing up to 50 MB). Large text files show a truncated preview—save the file to read it in full. ## Images and videos in messages -Select an image or video attachment or link to preview it. Playback support depends -on your browser or device; save an unsupported video to open it in another app. +Select an image or video attachment or link to preview it. -On web and desktop, right-click media to save it or copy its path or URL. On mobile, -touch and hold an image or video thumbnail and choose **Save or share**. On iOS, -return to the thumbnail to open this menu after watching a full-screen video. +- **Web and desktop**: Right-click media to save it or copy its path/URL. +- **Mobile**: Long-press a thumbnail and choose **Save or share**. -File links refer to the environment's machine, including when you connect remotely. -Previews use the original file, even outside the workspace. Moving or deleting it -can break the preview, so save a copy if you need to keep it. +File links point to the file on the environment's machine, so moving or deleting the original breaks the preview—save a copy if you need to keep it. ## Files outside the workspace -Follow an agent's file link to read a report or other file outside the workspace. -These files open read-only. An HTML file outside the workspace cannot load scripts, -styles, or images from neighboring files. +Following an agent's file link to a file outside the workspace opens it read-only. External HTML files cannot load neighboring scripts, styles, or images. ## HTML and PDF files in the file viewer -On web and desktop, HTML and PDF files open as rendered pages. Switch an HTML -file to source view to read its markup; a link to a specific line opens source -automatically. HTML previews cannot access your T3 Code session. - -The file viewer recognizes images, HTML, and PDF files by their filename extension, -including filenames or folders containing `#` or `?`. - -On mobile, select a PDF attachment or link to open it. iOS uses the native viewer; -Android opens a compatible installed file viewer. +On web and desktop, HTML and PDF files open rendered (HTML previews are sandboxed from your T3 Code session; line-specific HTML links open source view). On mobile, PDFs open in the native iOS viewer or an installed Android viewer. diff --git a/docs/user/cursor.md b/docs/user/cursor.md index f78ccf343d0cb..9a95896426836 100644 --- a/docs/user/cursor.md +++ b/docs/user/cursor.md @@ -1,105 +1,31 @@ # Cursor -Cursor V2 runs through the official [`@cursor/sdk`](https://cursor.com/docs/api/sdk/typescript) -TypeScript package. It does not use Cursor's ACP transport for V2 execution. +Run Cursor's local agent in T3 Code using your paid Cursor account or `CURSOR_API_KEY`. -## Prerequisites +## Prerequisites and sign-in -- Node.js 22.13 or newer. The repository's supported Node version satisfies this requirement. -- Sign in with Cursor in **Settings > Providers > Cursor**, or provide a Cursor API key in - `CURSOR_API_KEY`. -- A paid Cursor plan on the account used for browser sign-in or `CURSOR_API_KEY`. -- A model accepted by the Cursor SDK. `auto` is sent to the SDK as its `default` model selection. +- **Node.js 22.13+** on the environment's machine. +- A **paid Cursor plan** via browser sign-in or `CURSOR_API_KEY`. +- Open **Settings → Providers → Cursor** and choose **Sign in** (works on remote environments and configured mobile instances too). -The adapter currently uses the SDK's local-agent runtime so runs operate in the selected T3 Code -workspace. Cursor cloud agents need repository and cloud-environment configuration that T3 Code does -not expose yet. +Each Cursor instance keeps its own login separate from your Cursor editor or CLI. A configured `CURSOR_API_KEY` overrides browser sign-in. **Change account** or **Sign out** stops running threads for that instance while keeping history (to revoke a key early, delete it in your Cursor dashboard). -Custom Cursor MCP servers and plugins are not configured in T3 Code. They load from the environment -machine's Cursor config when the agent opens: project `.cursor/mcp.json`, user `~/.cursor/mcp.json`, -and installed plugins under `~/.cursor/plugins`. A project's own Cursor config, including its -`.cursor/mcp.json`, loads only in **Full access**; in the other -[permission modes](./permission-modes.md) a checkout cannot start MCP servers. Plugin tools -can appear without a login; OAuth MCP servers still need credentials. Run `agent mcp login ` -with the cwd set to the T3 project root (tokens land in -`~/.cursor/projects//mcp-auth.json`). Cursor desktop Connections auth does not write -that file, and the local SDK cannot complete interactive MCP OAuth itself—auth attempts fail with -messages such as "MCP authentication is not supported in local SDK runs" or that the auth server -does not support dynamic client registration. After you add or change skills, plugins, or MCP -servers, or after a successful CLI login, use **Restart agent session**. +## Capabilities and limits -## Sign in +- Supports streaming text, reasoning, tool activity, plans, image attachments, mid-turn text steering (steers with attachments or mode changes restart the run), and **Edit from here** / checkpoint rewind (rewinding to the first message starts a fresh session). +- **Subagents**: Cursor `task` subagents appear as read-only child threads; message the parent thread to interact. +- **Forking**: Uses a [portable handoff](./portable-handoffs.md) into a fresh Cursor session. +- **Cloud agents**: Not yet supported—runs operate locally in your T3 Code workspace. +- **Permissions**: **Full access** disables Cursor's sandbox; restricted modes enable it. On Windows, the Cursor SDK has no filesystem sandbox, so **Auto** and **Supervised** run without filesystem isolation when Cursor Auto-review is enabled, while **Auto-accept edits** cannot start on Windows. -Choose **Sign in**, then open the sign-in page and complete it in your browser. T3 Code -updates automatically when sign-in finishes. This works when connected to a remote environment too. -On mobile, use **Settings > Providers** for an already configured Cursor instance. +## MCP servers and plugins -Each provider instance keeps its own login on the environment that runs it. Your Cursor editor and -CLI login are separate. A configured `CURSOR_API_KEY` overrides browser sign-in; remove that override -to use the browser flow. +Cursor loads MCP servers and plugins from `~/.cursor/mcp.json`, `~/.cursor/plugins`, and (in **Full access** only) the project's `.cursor/mcp.json`. -Use **Change account** or **Sign out** in the same settings section. Both stop that -instance's running threads and keep their history. Sign-out forgets the saved credential; to revoke -the generated key before it expires, remove it from your Cursor dashboard's API keys. - -## V2 Capability Mapping - -The adapter supports: - -- creating and resuming local Cursor agent threads; -- changing the model and model parameters between turns; -- assistant text, reasoning, tool activity, plans, and todo streaming; -- thread-scoped T3 Code MCP tools alongside ambient Cursor MCP/plugins from disk; -- image attachments; -- interruption, queued app messages, and in-turn steering; -- provider conversation snapshots through `Agent.messages.list()`; -- Cursor `task` subagents, projected as read-only child app threads with their tool activity and - final result. - -The public SDK does not currently expose native agent fork or interactive approval callbacks. A -text-only steer reaches the current run without restarting it. -When Cursor cannot deliver the steer, the same message is queued for the next turn after -this run finishes. If you press Stop, that follow-up stays held until you resume the queue. Steers -with attachments and provider or runtime changes that must apply immediately interrupt and restart -the run. -Same-provider Cursor forks use the orchestrator's portable full-thread context handoff into a fresh -Cursor agent. **Edit from here** and checkpoint rollback rewind the same Cursor agent to just before -the selected message, as `cursor-agent`'s `/rewind` does, so it keeps its exact earlier history. -Rewinding to the thread's first message starts a fresh Cursor agent instead. -The SDK has in-process custom callback tools, but the V2 adapter intentionally uses the -authenticated, thread-scoped MCP server instead. - -Portable handoffs summarize eligible timeline items and can omit the end of long messages. Read -[Context in portable handoffs](./portable-handoffs.md) before using a fork for work whose exact -instructions must carry forward. - -Cursor task events include an `agentId`, but the local SDK does not register that identifier as a -resumable agent: `Agent.resume()` returns `AgentNotFoundError`. The adapter therefore does not attach -a provider thread to native task projections or advertise subagent thread IDs. A projected child is -read-only: send messages from the parent thread. - -Runtime modes map to the controls the local SDK exposes: full access disables its sandbox, while -restricted modes normally enable it. On Windows, Auto and Supervised run without filesystem -isolation when Cursor Auto-review is enabled, because the SDK does not support a filesystem sandbox -there. Restricted modes without Auto-review, including the default Auto-accept edits mode, still -request the sandbox and cannot start on Windows. Explicit sandbox policies remain authoritative, -including restrictive policies that the Windows SDK rejects. Explicit approval policy overrides -control Auto-review, which is not represented as an interactive T3 Code approval flow. - -The existing Cursor binary path and API endpoint settings belong to the CLI/ACP integration. Cursor -V2 execution does not launch that binary, and the SDK does not expose an API endpoint override. - -## Replay And Live Testing - -Cursor replay fixtures preserve the SDK boundary: agent open/resume, sends, ordered `onDelta` -updates, terminal results, cancellation, message snapshots, and close. The real V2 adapter, -orchestrator, event store, projections, and checkpoint logic still run in tests. - -Record a fixture against the real SDK with: +For OAuth MCP servers, authenticate via the CLI from the project root before starting a session: ```bash -pnpm --filter t3 record:cursor-replay --scenario simple +agent mcp login ``` -Use `--out ` to record a temporary probe without replacing a checked-in fixture. Supported -scenarios are listed by the recorder when an invalid scenario is supplied. +After adding or changing skills, plugins, or MCP logins, run **Restart agent session** from the command palette. diff --git a/docs/user/default-browser.md b/docs/user/default-browser.md index 1e1ef50034566..1dad12ed97393 100644 --- a/docs/user/default-browser.md +++ b/docs/user/default-browser.md @@ -1,17 +1,13 @@ # Use T3 Code as your default browser -On macOS, the desktop app can be your default web browser. Links you open from other apps then -open in T3 Code. When the thread on screen shows its browser panel, the link opens there as a new -tab. Otherwise it starts a new thread without a project, with the browser panel maximized on the -page, so you can ask an agent about it right away. +On macOS, you can set the T3 Code desktop app as your default web browser so links from other apps and local HTML files open directly in T3 Code. -Choose **T3 Code** under **System Settings → Desktop & Dock → Default web browser**. To go back, -choose another browser there. +## Enable -Pull request links for a connected project open in the pull request view when opening pull -request links in the app is enabled. Other links still open in the browser panel. +Choose **T3 Code** in **System Settings → Desktop & Dock → Default web browser** (switch back there anytime). -HTML files you open from Finder open the same way. [Prompt links](prompt-links.md) to -app.t3.codes open in the app as a draft. +## How links open -A link that launches T3 Code waits until the app has connected to its environment, then opens. +- If the active thread has its browser panel open, the link opens as a new tab there; otherwise T3 Code opens a new no-project thread with the browser panel maximized so you can ask an agent about the page right away. +- Pull request links for connected projects open in the PR view (when **Open pull requests in T3 Code** is enabled). +- [Prompt links](./prompt-links.md) to `app.t3.codes` open as a draft. diff --git a/docs/user/devices.md b/docs/user/devices.md index cc3cd935f9bbd..3c9418a4accc4 100644 --- a/docs/user/devices.md +++ b/docs/user/devices.md @@ -1,182 +1,54 @@ # Devices -The Device panel shows a live iOS Simulator or Android device next to a -thread, so you can watch an agent verify mobile work and tap the device -yourself. Agents get the same device through `device_*` tools and the -`agent-device` command line, which T3 Code sets up for them. +Stream and interact with live iOS Simulators, Android Emulators, and physical Android devices right beside a thread, and let agents inspect and drive them via `device_*` tools and the `agent-device` CLI. ## Open a device -Open the right panel in a project thread and choose **Device**. On first use, -the panel walks through three steps: starting the device hub, checking iOS and -Android support, and choosing whether agents may control devices. Opening the -panel alone does not download or start anything. If the hub is already -installed, the setup screen says so and reuses it. - -Choose a running device to watch it, or choose **Start** next to a stopped -device to boot it. The panel shows when you or an agent starts a device. -Each device opens in its own tab. Use **+ → Device** to open another, and -double-click a tab name or choose **Rename** from its context menu to rename it. -Only the visible tab streams video; switching tabs keeps both devices running. -Choose **Float device over chat** in the toolbar to keep watching and tapping the -device in a small window while the right panel shows something else; drag the -window by its handle, resize it from any edge, and use **Open in right panel** -to bring it back. -Turn off **Use devices** in **Settings → Devices** to stop the -helper processes; simulators and emulators keep running until you power them -off. - -Simulators run on the machine that hosts the environment server. iOS needs -macOS with Xcode. Android needs the SDK Platform-Tools, Android Emulator, -and Command-line Tools (latest), plus a virtual device created in Android -Studio's Device Manager. T3 Code detects standard SDK locations; set -`ANDROID_HOME` for a custom location. The panel explains missing dependencies. -After installing SDK tools, restart the environment server and refresh devices. - -Physical Android devices connected to the machine that hosts the environment -server need only SDK Platform-Tools. Turn on **USB debugging** in the phone's -Developer options, connect it over USB, and approve the prompt on the phone. For -wireless debugging, turn on **Wireless debugging** instead. Once, choose **Pair -device with pairing code** and run `adb pair
        :` on that -machine with the code it shows. Then run `adb connect
        :` with the -address and port shown on the **Wireless debugging** screen, which differ from -the pairing ones. Refresh devices afterward. - -Android emulator video also needs `ffmpeg` with the libx264 encoder on the device -host's PATH, or an executable selected by `SERVE_EMU_FFMPEG` on that host. If -opening an emulator reports an ffmpeg problem, install or fix the executable -and retry opening it. After changing PATH or `SERVE_EMU_FFMPEG`, restart the -environment server for local devices, or turn device support off and on for SSH -devices, so the running tools inherit the new environment. Physical Android -devices and iOS do not need ffmpeg. - -The screen is interactive: click and drag to touch, type while the screen is -focused, and use the toolbar for Home, Back, and Recents on Android, rotate on -iOS, and power off. Some Xiaomi phones ignore touch and keys until **USB -debugging (Security settings)** is on in Developer options. Close the tab to stop watching; the device keeps running -unless you power it off. Closed tabs stay closed after a reload. To watch the -device again, choose it from **+ → Device**. - -Choose **3D view** to inspect supported devices while the live screen stays -interactive. On iPhone Duo, use the fold and stance controls to change its -physical pose, or pinch over the device to adjust the hinge. Turning the model -to the other screen switches the live display and touch input to that screen. -**Restore 3D view** returns the device to a screen-facing position. -On supported Android foldables, use **Fold device** and **Unfold device** beside -the screen to change its posture in either view. - -## Tools - -The toolbar's **Tools** button opens a drawer for the open device. It shows the -foreground app, and lets you switch light and dark mode, change text size, -flip accessibility settings, overlay the accessibility element frames on the -screen, set a fake location, and grant or revoke app permissions. iOS also -exposes Liquid Glass, color filters, VoiceOver, and sending a test push -notification; Android adds orientation and toggling the network. The drawer -only shows what the platform can do, and every control reflects the value read -back from the device after a change. +Open the right panel in a project thread and choose **Device** (first-time setup starts the device hub, checks iOS/Android tools, and asks whether agents may control devices). + +- Start a stopped device or attach to a running one; open additional devices via **+ → Device**. +- Click, drag, and type directly on the live screen; use the toolbar for Home, Back, Recents, rotate, power off, **3D view** (and fold/unfold on foldables), **Tools**, or **Float device over chat**. +- **Tools drawer**: Inspect the foreground app, toggle dark mode, text size, accessibility overlays, mock location, app permissions, iOS VoiceOver / test push notifications, and Android orientation / network toggles. +- Closing a tab stops streaming without powering off the device. Turn off **Settings → Devices → Use devices** to stop helper processes. + +## Host prerequisites + +Devices run on the environment's server machine (or an SSH/Simlock device host): + +- **iOS Simulators**: macOS with Xcode. +- **Android Emulators**: Android SDK Platform-Tools, Android Emulator, Command-line Tools (latest), an AVD created in Android Studio, and `ffmpeg` with `libx264` on `PATH` (or `SERVE_EMU_FFMPEG`). Set `ANDROID_HOME` for custom SDK paths. +- **Physical Android devices**: SDK Platform-Tools only (no `ffmpeg`). Enable **USB debugging** (and **USB debugging (Security settings)** on Xiaomi devices), or pair wirelessly via `adb pair :` then `adb connect :`. + +Restart the environment server after installing SDK tools or changing `PATH` / `SERVE_EMU_FFMPEG`. ## Agents and devices -When an agent opens a device, it floats over the chat in web and desktop clients -connected to the thread, the same way an agent-driven browser does. Turn off -**Auto-show floating preview** in **Settings → Browser** to open a -right-panel tab instead. In the mobile app, open the agent's thread and tap the -device button above the composer to watch the live screen and control it. -On iOS layouts with an inspector, the device opens beside the thread. Maximize -it to fill the screen; closing the full-screen view returns to the inspector. -If the thread has several devices open, choose one in the viewer. Closing the -viewer stops streaming and leaves the device available to the agent. Device -activity also appears in the thread timeline. - -Agents drive the device through the `agent-device` command line. T3 -Code installs and starts it only after **Agents can use devices** is on. iOS -taps build a small test runner on first use, which takes a couple of minutes -once per server. Restart an existing agent session after granting access so it -receives the device CLI environment. - -To keep agents away from simulators, turn off **Agents can use devices** in -**Settings → Devices**. This hides the device tools from agents -started from then on; your own Device panel is unaffected. +Enable **Settings → Devices → Agents can use devices** so agents can drive devices through `agent-device` (restart existing agent sessions after enabling). First iOS tap builds a small test runner once per server (~2 minutes). + +When an agent opens a device, it floats over chat by default (disable **Settings → Browser → Auto-show floating preview** to open in the right panel instead). On mobile, tap the device button above the composer to watch and interact. ## Remote connections -The device stream goes through the environment server, so it works over the -local network, Tailscale, and T3 Connect. Live video needs a secure page -(HTTPS or localhost); on a plain-HTTP remote origin iOS falls back to a slower -still-image stream and Android cannot show video, except on Expo Simulators. +Device video streams through the environment server (works over LAN, Tailscale, and T3 Connect). Live video requires HTTPS or `localhost`—plain HTTP remote origins fall back to still images on iOS and disable video on Android (except Expo Simulators). ## SSH device hosts -In Settings → Devices, choose the environments that should use -the host and choose **Add source → Machine over SSH**. Enter an SSH alias or `user@host`, with -an optional identity file and port. These resolve on the environment server, -so use the SSH configuration and keys available there. Password prompts are -not supported. - -**Test connection**, in the host's menu, checks SSH, Node, npm, and platform tools without installing -anything, with a result for each selected environment. Targets that resolve to -the environment’s own machine are skipped, since its devices are already local. -The first device listing installs pinned device tools on the host. -SSH device hosts currently need macOS or Linux. To use devices on a Windows -machine, run T3 Code on that machine and connect to its environment. -Node 22.12 or newer and npm must be available to non-interactive SSH commands. -T3 checks common Homebrew and Android SDK locations; custom installations need -the appropriate PATH and `ANDROID_HOME` or `ANDROID_SDK_ROOT` on the host. -Android on an SSH host needs the SDK Platform-Tools, Android Emulator, and -Command-line Tools (latest), even for physical devices; adb on the PATH alone -does not enable it. Android emulator video needs -`ffmpeg` with libx264 on that host; physical Android devices use scrcpy and do -not need ffmpeg. - -The picker identifies devices by host when several hosts are configured. -Connections recover after interruptions. Removing a host closes its device -sessions and stops its T3 helpers when reachable; simulators keep running. - -T3 provides discovery, streaming, and control. Arrange app builds, -installation, and connectivity to development servers such as Metro separately. -A simulator on another machine cannot reach Metro through your environment's -localhost without forwarding or another reachable address. +Use simulators/emulators on another macOS or Linux machine (e.g., a Mac build host from Linux/Windows): + +1. Open **Settings → Devices → Add source → Machine over SSH** and enter an SSH alias or `user@host` (uses the environment server's SSH config/keys; no password prompts). +2. Run **Test connection** to verify SSH, Node.js 22.12+, npm, and SDK tools (Android on SSH hosts requires full SDK tools + `ffmpeg` for emulators). +3. First listing installs pinned device helpers on the SSH host. + +> Note: Remote simulators cannot reach `localhost` dev servers (like Metro) on your main host without port forwarding or a reachable network address. ## Simlock hosts (alpha) -[Simlock](https://incubator.callstack.com/simlock/) pools iOS simulators and -Android emulators across machines. If you run a Simlock gateway, T3 can lease -devices from it. Simlock is new and unreleased, so this integration is an -alpha: it may change or stop working with a newer Simlock. T3 does not install -or manage Simlock; set up the gateway and its workers yourself. It needs a -gateway and workers built from Simlock's `main` at -[6316e10](https://github.com/callstackincubator/simlock/commit/6316e10) or -later, the first with a lease holder's screen and input. - -Turn on **Settings → Labs → Simlock device hosts (alpha)** and **Use devices** -in Settings → Devices, then choose **Add source → Simlock pool** with an **agent token** -(`simlock --gateway token create --role agent`). Give each T3 server its own -token: Simlock counts every lease made with one token against the same -requester, and allows one at a time unless the gateway's -`lease.maxPerRequester` is raised to the host's **Devices at once**. The token -leases devices and reaches only its own leases, but commands on a leased device -run on its worker, so treat it like shell access to your workers. T3 sends it -with every request, so use an HTTPS gateway URL, or plain HTTP only over an -encrypted network such as Tailscale. The gateway -and workers need `capabilities.stream.enabled` and `capabilities.input.enabled` -for the live screen and for input. - -The picker lists the models your workers can make. Opening one takes a lease; -closing it with **Return device to the pool**, or removing the host, returns it -wiped. The panel keeps a watched device leased up to the host's lease limit. -You can tap, swipe, type, and press Home, and Back and Recents on Android. -Rotation, appearance, text size, device tools, and screenshots are not offered -for Simlock devices; agents can still do them through `device_open`. On iOS 27 -simulators, typing on your keyboard does nothing; tap the on-screen keyboard -instead. Workers must run the same agent-device -version as T3 (see Device tool updates), and agent-device accepts app installs -for a lease only from the folder it was opened from, which `device_open` -names. A device cannot reach development servers on your machine through -localhost; use an address its worker can reach. +Connect to a [Simlock](https://incubator.callstack.com/simlock/) device pool (requires Simlock `main` at commit `6316e10`+ with `capabilities.stream.enabled` and `capabilities.input.enabled`): -## Device tool updates +1. Enable **Settings → Labs → Simlock device hosts (alpha)** and **Settings → Devices → Use devices**. +2. Choose **Add source → Simlock pool** with an agent token (`simlock --gateway token create --role agent`) over HTTPS or Tailscale (give each T3 server its own token; treat it like worker shell access). +3. Closing a device with **Return device to the pool** wipes and releases the lease. Toolbar tools/rotation/screenshots are unavailable in the UI (agents can still invoke them via `device_open`). -The connected T3 server manages the device hub and agent tools on its own machine and configured SSH hosts. Required versions install automatically the next time those tools are used. In Settings → Devices, select a version and choose **Check versions** to read installed versions without installing tools or starting devices. +## Device tool updates -To receive newer tool versions on a remote environment, update that environment's T3 server. Updating only the browser or mobile app does not update the remote server. An offline host keeps its installed files, but an update needs network access before device support can start; T3 does not fall back to an older version. Reconnect the host and use Retry if installation fails. Existing device and agent-access settings are preserved. +The T3 server manages device hub and `agent-device` versions automatically on itself and SSH hosts. Check versions in **Settings → Devices → Check versions**; update the remote T3 server to receive newer device tools. diff --git a/docs/user/diagnostics.md b/docs/user/diagnostics.md new file mode 100644 index 0000000000000..5d17b9bcebc7e --- /dev/null +++ b/docs/user/diagnostics.md @@ -0,0 +1,36 @@ +# Maintenance, power, and diagnostics + +Control how aggressively T3 Code runs background checks, keep your computer awake while agents work, inspect server health, and analyze local trace files. + +## Background activity and power + +Configure under **Settings → Maintenance** (per environment): + +- **Background activity**: Choose **Balanced**, **Performance**, or **Battery saver**—or expand **Advanced** to customize pausing on host lock / low-power / battery, **Git fetch interval**, and provider health check intervals. +- **Keep awake while agents work**: Prevents the host OS from sleeping while an agent turn is running. +- **Continue threads after restarts**: Automatically resumes supported active threads after an update, crash, or reboot ([details](./updating.md#continue-threads-after-restarts)). +- **Provider update checks**: Enables checking for newer provider CLIs and updated model catalogs. +- **Artifacts and logs / Delete now**: Manage disk cleanup ([Storage cleanup](./project-settings.md#storage-cleanup)) and database compaction ([Reclaim database space](./background-service.md#reclaim-database-space)). + +## Diagnostics view + +Open **Settings → Maintenance → Diagnostics** (select an environment) to inspect: + +- Live server logs and recent failures +- Trace spans and CPU/memory resource history +- Running child processes (with controls to signal or stop them) +- **OpenTelemetry export** (OTLP HTTP endpoints; see [Export diagnostics](./telemetry.md#export-diagnostics-to-your-own-opentelemetry-receiver)) + +On mobile, startup crashes from the last 7 days are recorded under **Settings → Diagnostics** for bug reports. + +## Inspect local trace files (`t3 trace`) + +Summarize latency, rates, interrupts, and failures from the server's rotated trace files directly from the host terminal: + +```sh +t3 trace summary # Top 25 busiest spans +t3 trace summary --since 30m # Spans ended in the last 30 minutes +t3 trace summary --since 2h --limit 50 +``` + +Pass `--base-dir ` (or set `T3CODE_HOME`) for a non-default data directory. diff --git a/docs/user/diffs.md b/docs/user/diffs.md new file mode 100644 index 0000000000000..c09abcafeea4b --- /dev/null +++ b/docs/user/diffs.md @@ -0,0 +1,38 @@ +# Diffs and workspace files + +Inspect changes, browse or edit workspace files, and send line-specific feedback directly to your agent without leaving the thread. + +## Diff pane + +Open the Diff pane in the right panel (web and desktop) and choose a source from the source picker: + +- **Turn changes**: Files edited, committed, or conflict-resolved by a specific turn (excludes unrelated files brought in by `git pull`/`merge`/`rebase`). +- **Uncommitted**: Current working-tree changes. +- **Changes**: Full branch comparison against your base branch. +- **Commits**: Inspect up to the newest 100 local commits individually. + +In [multi-repo projects](./multi-repo-projects.md), use the repository picker beside the source picker to filter by repository. + +- **Find in diff**: Click into a diff and press `mod+f` to search across all loaded files (automatically unfolds matching files; `Enter` / `Shift+Enter` navigates matches). + +## Workspace files + +Open files from agent file links, the file picker, or the Diff pane to read or edit them beside the conversation (editing over a remote connection requires `filesystem:write`). + +- Supports syntax-highlighted code/JSON, rendered and raw views for Markdown, HTML, CSV, and TSV, PDF previews, and ZIP browsing up to 50 MB. +- Files outside the workspace open read-only. + +## Inline review comments + +Select lines in any diff or workspace file to leave a review comment. Comments attach to your composer as inline context chips so you can collect feedback across multiple files and send it to the agent in one message. + +## Diff settings + +Configure defaults in **Settings → Diffs & pull requests**: + +- **Diff layout**: Unified (stacked) or split (side-by-side). +- **Diff colors**: Standard or colorblind-friendly palettes. +- **Hide whitespace changes**: Ignore whitespace-only edits. +- **Default diff file state**: Expanded or collapsed by default. +- **Open pull requests and changes panels proactively**: Automatically open relevant panels when turns finish. +- **Open pull requests in T3 Code**: Open PR and local commit links inside T3 Code instead of an external browser (`Cmd/Ctrl+Click` always opens in your external browser). diff --git a/docs/user/faq.md b/docs/user/faq.md index 22af936eb8150..57f2cd4e3384c 100644 --- a/docs/user/faq.md +++ b/docs/user/faq.md @@ -2,22 +2,16 @@ ## Is T3 Code a harness? -No. A harness is what turns an LLM into an agent: it gives the model tools, a way to call them, runs them, and hands the results back. Claude Code is kind of a harness. It is an interface (the TUI, the Code tab in the desktop app) plus a harness underneath (the Anthropic Agent SDK). Codex is the same split: the app plus the Codex App Server. T3 Code uses those harnesses. It is not a harness, and it does not work without one. +No. A harness turns an LLM into an agent (tools, execution loop, and results)—like Claude Code's Agent SDK or Codex App Server. T3 Code drives those harnesses through one fast interface; it does not work without at least one installed agent. -Chef = LLM. Kitchen = harness. T3 Code = the restaurant that lets you bring whatever kitchen you want. Our MCP is a cookbook we hand the kitchen, but the chef won't open it unless you tell them to :) I wrote the long version here: [What is a harness?](https://t3.gg/blog/post/what-is-a-harness) - -Bring your own: Claude Code, Codex, Cursor, Grok Build, OpenCode, Google Antigravity, Kiro, Pi, Muse Code, or fx. [Provider setup](./install.md#providers) +Bring your own: Claude Code, Codex, Cursor, Grok Build, OpenCode, Google Antigravity, Kiro, Pi, Muse Code, fx, or any [ACP agent](./providers-acp.md). See [Provider setup](./install.md#providers). (Longer read: [What is a harness?](https://t3.gg/blog/post/what-is-a-harness)) ## Why use T3 Code instead of Claude Code or the Codex app? -We were inspired by the Codex desktop app, Conductor, Claude Desktop, and Cursor Glass, but none met our bar. What you get: - -- Bring your own sub. Claude, Codex, and whatever else you already have installed. -- Best in class remote. Run `t3 up` on any box and drive it from anywhere. -- Best in class mobile app. -- Truly 100% open source code (MIT). If we go the wrong direction, fork it under your own branding. - -Every harness feels nearly identical in here, so you can stop worrying about harnesses and focus on building :) [Install](./install.md) +- **Bring your own subscription**: Use Claude, Codex, and every other agent you already have installed in one place. +- **Remote-first**: Run `t3 up` on any box and drive it from anywhere. +- **Native mobile app**: Approve steps, review PRs, and steer threads from iOS and Android. +- **Open source (MIT)**: Fork the source code under your own branding if you ever want something different. ## Can I use T3 Code with my Claude Code subscription? @@ -25,68 +19,66 @@ Yes. ## How much does T3 Code cost? -Nothing. There's no way to pay us to use T3 Code. You bring your own sub. The source code is free and open source (MIT). You still pay your provider like you already do. T3 Connect is free too, for now. Every account can connect up to 3 machines running T3 Code. Phones and browsers that connect to them do not count. Need more? Link a paid T3 Chat account. [More machines](#can-i-connect-more-than-3-machines-with-t3-connect) We don't want to charge for this, but if the bill gets unacceptable we may have to change course. If you hit limits or have issues, you can always fork the source code (under your own branding), self host, or use Tailscale. [Install](./install.md) +Nothing. You pay your own model/agent providers. T3 Connect is free for up to 3 connected host machines per account (phones and browsers don't count). You can also self-host or use LAN/Tailscale. ## Can I fork or redistribute T3 Code? -Yes, for the source code. The [MIT License](../../LICENSE) applies only to the source code, not to the T3 Code name, wordmark, logos, or branding. If you publish a fork or custom build, you must replace T3 Code's branding with your own and make it unmistakably clear that your project is unofficial and not affiliated with T3 Tools, Inc. Using the T3 Code name, wordmark, logo, or branding without being explicitly clear that your project is unofficial, or indicating that an unofficial project is an official version of T3 Code, is unlawful and will be pursued to the full extent of the law. See [TRADEMARK.md](../../TRADEMARK.md). +Yes, for the source code. The [MIT License](../../LICENSE) covers source code only—not T3 Code's trademarks, name, wordmark, logos, or icons. Any public fork or build must use its own branding and clearly state that it is unofficial and not affiliated with T3 Tools, Inc. See [TRADEMARK.md](../../TRADEMARK.md). ## Can I connect more than 3 machines with T3 Connect? -Yes. Link your T3 Chat account and T3 Connect raises your limit: up to 10 machines with T3 Chat Pro, or 100 with Premier. Open your account menu in T3 Code, go to **T3 Chat**, and select **Link T3 Chat**. Sign in to T3 Chat and approve. The free T3 Chat plan keeps the normal limit of 3. [More machines with T3 Chat](./remote-access.md#more-machines-with-t3-chat) +Yes. Link a paid T3 Chat account from your account menu → **T3 Chat → Link T3 Chat**: T3 Chat Pro raises the limit to 10 machines, and Premier raises it to 100. See [More machines with T3 Chat](./remote-access.md#more-machines-with-t3-chat). ## Why is my Claude 5-hour limit draining so fast? -It shouldn't anymore. T3 Code drives Claude through Anthropic's Agent SDK, and Anthropic's 5h meter used to charge Agent SDK usage about 1.7x more than using Claude Code directly. Weekly limits were never affected. Since v0.1.7, Claude in T3 Code drains your 5h limit at the same rate as Claude Code. Still seeing it? [Update T3 Code](./updating.md) on the machine that runs your agents. [My post on it](https://x.com/theo/status/2114166439813017873) · [Tracking issue](https://github.com/pingdotgg/t3code/issues/24649) +Since v0.1.7, Claude in T3 Code drains your 5-hour limit at the same rate as Claude Code directly (an earlier Anthropic Agent SDK discrepancy has been resolved). If you still see it, [update T3 Code](./updating.md) on the machine running your agents. ## How do I use T3 Code remotely? -Your agents run wherever T3 Code runs: your desktop, a server, a VPS. You connect to it from anywhere. I do this constantly. Less than 5% of my prompts run on my laptop. Run `t3 up` on that machine and you get really good remote support. T3 Connect is the easy path. LAN pairing and Tailscale work too, and [app.t3.codes](https://app.t3.codes) is the web client. [Remote access](./remote-access.md) +Your agents run wherever the T3 Code server runs (desktop, server, or VPS). Run `t3 up` on that machine and connect via T3 Connect, LAN, Tailscale, or [app.t3.codes](https://app.t3.codes). See [Remote access](./remote-access.md). ## How do I use T3 Code on my phone? -Get the [iOS](https://apps.apple.com/us/app/t3-code-remote-claude-more/id6787819824) or [Android](https://play.google.com/store/apps/details?id=com.t3tools.t3code) app, then connect it to your computer with T3 Connect or a pairing link. The phone is a remote. Your computer does the work and needs to stay on. [Mobile setup](./install.md#mobile-app) · [Remote access](./remote-access.md) +Install the [iOS](https://apps.apple.com/us/app/t3-code-remote-claude-more/id6787819824) or [Android](https://play.google.com/store/apps/details?id=com.t3tools.t3code) app and connect it to your computer with T3 Connect or a pairing link. The phone is a remote control—your host computer runs the agents and must stay on. See [Mobile app](./install.md#mobile-app) and [Remote access](./remote-access.md). ## Why does T3 Connect keep disconnecting? -T3 Connect is our built-in alternative to Tailscale for remote connections. If it keeps dropping, open **Settings > Environments**, find the machine, and select **Details**. The first part marked as failed is the cause. I will not be disappointed if you set up Tailscale as a fallback (I do this personally). [T3 Connect troubleshooting](./t3-connect-troubleshooting.md) +Open **Settings → Environments**, select the machine, and choose **Details**—the first failed check identifies the cause. See [T3 Connect troubleshooting](./t3-connect-troubleshooting.md). Tailscale also works great as a direct fallback. ## Will I get banned for using my subscription? -No. We work with all of the labs and T3 Code is within the TOS of Claude Code, Codex, and Google Antigravity. We worked directly with [SpaceXAI](https://x.com/SpaceXSI/status/2070195830192320600) to collaborate on the Grok Build and Cursor integrations. Everything else uses official ACP bindings. - -If it works in T3 Code, you can trust it is safe. +No. T3 Code stays within the TOS of Claude Code, Codex, Google Antigravity, Grok Build, Cursor, and official ACP bindings. ## Can I add a bunch of accounts for one provider? -I don't think T3 Code is the right place to manage a pile of accounts. If we add an auto-switcher, we are risking TOS bans for our users. - -A separate work account is fine. Setup for two: [Codex](./providers-codex.md#use-multiple-accounts) · [Claude](./providers-claude.md#separate-accounts-or-configurations). For a bigger pool, manage them outside T3 Code with a self-hosted proxy like [CLIProxyAPI](https://github.com/router-for-me/CLIProxyAPI). I walked through how I use 6 Claude subs and 3 Codex subs in [this video](https://www.youtube.com/watch?v=D8PikZ1KhUo), and wrote up the setup in [this guide](https://gist.github.com/t3dotgg/59a521d2ee8d70aaf90e280c175072af). Hand it to your agent and it will walk you through it. Early apologies if it gets you banned 💀 After you set up a hub, T3 Code can show its pooled limits under Usage. [Connect a hub](./usage.md#connect-a-cliproxyapi-hub) +T3 Code intentionally does not include an automatic multi-account switcher to avoid risking provider TOS bans. Adding a separate work/personal account is supported ([Codex](./providers-codex.md#use-multiple-accounts), [Claude](./providers-claude.md#multiple-accounts-and-presets)). For larger pools managed externally (e.g. via [CLIProxyAPI](https://github.com/router-for-me/CLIProxyAPI)), T3 Code can display pooled limits under Usage ([Connect a hub](./usage.md#connect-a-cliproxyapi-hub)). ## Can I use an API key or OpenRouter instead of a subscription? -Yes. Add another provider instance in Settings and give it its own keys and endpoint. Claude has a full OpenRouter recipe. Your subscription setup stays untouched. [OpenRouter](./providers-claude.md#openrouter) · [Provider instances](./install.md#providers) +Yes. Add another provider instance in **Settings → Providers** with its own environment variables and endpoint (your subscription setup stays untouched). See [OpenRouter for Claude](./providers-claude.md#openrouter-and-local-routers) and [Providers](./install.md#providers). ## Does T3 Code support local models? -No. T3 Code is a serious developer tool. Locally runnable models are not capable of meaningful engineering work. +No. T3 Code focuses on frontier coding agents. ## Does my code go to T3 servers? -No. Your code and prompts go from your machine to your provider (Anthropic, OpenAI, etc.), not to us. With T3 Connect, traffic rides a Cloudflare tunnel (`cloudflared` on your machine). Our relay sets up the link. It does not proxy your HTTP or WebSocket sessions. T3 Code does send basic product usage events (provider, model, token totals, that kind of thing). No prompts, no file contents. That is the same on Tailscale, LAN, or T3 Connect. Set `T3CODE_TELEMETRY_ENABLED=false` or `DO_NOT_TRACK=1` if you want it off. [Product usage data](./telemetry.md) +No. Code and prompts go directly from your machine to your chosen provider. With T3 Connect, traffic travels over a Cloudflare tunnel (`cloudflared` on your machine); T3's relay coordinates the link without proxying your HTTP/WebSocket sessions. + +T3 Code sends basic product usage events (provider, model, token totals—no prompts or file contents). Disable with `T3CODE_TELEMETRY_ENABLED=false` or `DO_NOT_TRACK=1`. See [Product usage data](./telemetry.md). ## Worktrees are eating my disk. How do I clean them up? -Open **Settings → Worktrees → Cleanup** and turn on automatic worktree cleanup. You can also run it now from there. Worktrees add up fast. One user cleared 500 GB. [Storage cleanup](./project-settings.md#storage-cleanup) +Enable automatic cleanup or run **Delete now** in **Settings → Worktrees → Cleanup**. See [Storage cleanup](./project-settings.md#storage-cleanup). ## Is there voice input? -Yes. On iPhone and Android, dictation uses on-device speech by default, with the option to use a paired environment. On macOS 26 or later, desktop users can choose Apple Speech directly under **On this Mac** or choose an environment. Web and other desktop users can enable dictation by choosing an environment. The transcript goes into your draft for review. See [Voice input](./voice-input.md). +Yes—on-device speech on iOS, Android, and macOS 26+ desktop, or via a paired environment on web/desktop/mobile. See [Voice input](./voice-input.md). ## Does it work on Windows, Mac, and Linux? -Yes, all three. Desktop app, CLI, the works. One catch: there is no `t3` binary for Intel Macs, so use the desktop app there. Windows folks can also run agents inside WSL. [Install](./install.md) +Yes, all three (desktop app and CLI). Note: there is no standalone `t3` binary for Intel Macs (use the desktop app there), and Windows users can also run agents inside WSL. See [Install](./install.md). ## Why is my provider not showing up? -Almost always, the CLI is not installed or not on the `PATH` of the machine that runs the server. (Not your phone. The computer.) Log in on that machine first, like `codex login` or `claude auth login`. Still missing? Point **Binary path** at it in provider settings. Version managers love to cause this one. [Provider setup](./install.md#providers) +Usually the provider CLI is not installed, not signed in, or not on the `PATH` of the **server machine** (especially with version managers). Authenticate on the server machine first (e.g. `codex login` or `claude auth login`) and set **Binary path** in **Settings → Providers** if needed. diff --git a/docs/user/guest-links.md b/docs/user/guest-links.md index 30720f4fb00d9..974f603636f64 100644 --- a/docs/user/guest-links.md +++ b/docs/user/guest-links.md @@ -1,49 +1,20 @@ # Guest links -A guest link lets a teammate follow one thread in their browser and ask the agent questions, with no -account. They see your messages and the agent's replies as they stream. Each message they send waits -until you send or dismiss it. +Share a single thread with a teammate in their browser—no account required. Guests see messages and agent activity stream live, and any message they send waits for your approval before running. -## Share a thread +## Prerequisites and sharing -Guest links are a beta. Turn on **Settings → Labs → Guest links** for the machine that runs the -thread. They also need [T3 Connect](./remote-access.md): sign in and link that machine, because the -link points at its T3 Connect address. The machine must stay online while the guest uses it. -While the setting is off, every guest link on that machine stops working; links that have not -expired work again when you turn it back on. +- Enable **Settings → Labs → Guest links** on the host machine (turning it off pauses all active guest links on that machine). +- Link the host to [T3 Connect](./remote-access.md) and keep it online while the guest uses the link. -1. Right-click the thread in the sidebar and choose **Share with guest**. It is also in the thread - menu and the command palette. In the mobile app, long-press the thread in the list. -2. Copy the link and send it to one person. It works in one browser and expires after 24 hours. - Opening it again in that browser takes them back to the thread. -3. When they send a message, it appears at the end of the thread and the sidebar shows **Request**. - Choose **Send** to run it as a normal turn, or **Dismiss**. Files they attached show with the - message, and **Send** includes them. +1. Open the thread's menu (or command palette / mobile long-press) and choose **Share with guest**. +2. Send the copied link to one person (works in one browser and expires after 24 hours). +3. Guest messages appear at the end of the thread (**Request** in the sidebar). Choose **Send** to run as a normal turn (in the thread's current permission mode—review text and files first) or **Dismiss**. -Choose **Stop sharing** to end the link at once. Archiving the thread, creating a new link, or -unlinking the machine from T3 Connect also ends it. The mobile app can send, dismiss, and stop -sharing too. +Choose **Stop sharing** anytime to revoke immediately. Archiving the thread, generating a new link, or unlinking T3 Connect also ends the link. -## What the guest sees +## What guests can see and attach -The guest sees the thread's recent history and everything after, in the same timeline you see, as -it streams: messages and their files, the agent's replies with the images they show from your -machine, its reasoning, plans, questions, and its work, with command output when they expand a -command. Their composer shows the thread's model, but they cannot change it. They do not see diffs, and they cannot act on the thread: no forking, -reverting, opening files on your machine, or answering the agent for you. - -Anything the agent read or printed can show, such as a value from a file. Share only threads you -are comfortable showing. - -## Guest attachments - -Guests can attach images and other files to a message: use the paperclip, paste, or drop them on -the message box. A message holds up to 4 files and 10 MB in total. Images must be PNG, JPEG, GIF, or -WebP. While messages wait for you, their files can total 20 MB; the guest can attach more once you -send or dismiss some. - -Dismissing a message, ending the link, or archiving the thread deletes the files of messages that -still wait. A sent message keeps its files, like any message in the thread. - -The guest's text and files run with the thread's current permission mode once you send them. Check -them before you choose **Send**, as you would anything pasted from a chat. +- **Visible**: Thread messages, files, agent replies, images, reasoning, plans, questions, and command output. Anything the agent printed is visible—only share threads you're comfortable exposing. +- **Restricted**: No diffs, file browser, model switching, forking, reverting, or answering approvals/questions. +- **Attachments**: Up to 4 files (10 MB total) per message (PNG, JPEG, GIF, WebP images + other files), up to 20 MB total across pending unapproved messages. Dismissing or ending the link deletes pending files. diff --git a/docs/user/html-renders.md b/docs/user/html-renders.md index 8e3c231f49012..28f17c67182a9 100644 --- a/docs/user/html-renders.md +++ b/docs/user/html-renders.md @@ -1,19 +1,19 @@ -# Visual replies +# Visual replies and MCP apps -Agents can answer with a page instead of only text: a chart, table, diagram, image collage, or mockup. Ask for one ("show this as a chart", "make a collage of these screenshots") and the agent builds a self-contained HTML page, which appears in the thread above its written reply. It works with every provider, on web, desktop, and mobile. +Agents can render self-contained HTML visuals (charts, diagrams, tables, image collages, mockups) and interactive MCP Apps inline in a thread on web, desktop, and mobile. -Pages use your current theme, including custom themes, and follow light and dark mode as you switch. Scripts run inside the page, but it is sandboxed away from T3 Code and your session. Links you click in a page open in your browser. Use the expand button to open a page full screen. On web and desktop, use the zoom controls to see more detail. +## Visual replies (HTML renders) -Agents can place local images in a page by file path. T3 Code embeds them when the page is published, so the page keeps working after the original files move or are deleted. Deleting the thread deletes its pages. +Ask an agent for a visual (e.g. "show this as a chart" or "make a collage of these screenshots"). The rendered page appears above the agent's reply, adapts to your light/dark theme, and runs sandboxed away from your T3 Code session. -Before publishing, agents check their work with screenshots from a small headless browser that T3 Code keeps for itself; it never uses a browser you installed. The first preview on a machine downloads it once (about 120 MB) into T3 Code's data folder, so that preview can take a minute. Browser tabs on a remote environment use the same browser, so whichever comes first downloads it. Some Linux hosts need [setup](remote-access.md#browser-host-setup) before it can start. Pages publish without it. - -Previews can load public resources such as CDN scripts, but nothing on your local network. The machine running the environment looks up each name, and previews block names that resolve to private or reserved addresses. Clash or Mihomo in fake-IP DNS mode can return these addresses, so external resources can fail there. The preview's console messages can identify affected hostnames. Inline the resource, add its host to `fake-ip-filter`, or switch that machine's proxy DNS to `redir-host`. +- **Local images**: Embedded when published so they stay intact even if the original files move or are deleted. +- **Preview browser**: Before publishing, agents verify their visual with T3 Code's bundled headless Chromium (~120 MB one-time download, shared with [remote browser tabs](./remote-access.md#browser-host-setup)). +- **Network restrictions**: Previews can load public CDN assets but block private/local-network IPs. If Clash/Mihomo fake-IP DNS causes CDN loads to fail, inline the resource, add the host to `fake-ip-filter`, or switch proxy DNS to `redir-host`. ## MCP apps -Some MCP servers return an interactive app with their tool results, following the [MCP Apps](https://github.com/modelcontextprotocol/ext-apps) standard. When an agent calls one of those tools, the app appears in the thread below the tool call, on web, desktop, and mobile. The tool call keeps its input and result, so you can still read them when an app shows nothing. Codex and Claude support this today, for any MCP server you have configured for them. Claude needs Claude Code 2.1.301 or newer; older versions and other providers show these calls as ordinary tool calls. - -Apps follow your theme. An app can call tools on its own server and post a message to the thread; T3 Code asks first unless the server marks the tool as read-only, and it asks before every message. On mobile, an app also asks before opening a link, and T3 Code asks before saving a file an app offers. An app stays viewable after its agent stops, but using it needs the agent of the thread that created it running, so send a message in that thread first if the app says it is unavailable. An app that navigates away from its own page is stopped. Apps run only on an environment whose T3 Code server is current: on an older server, the thread shows a line asking you to update it in place of the app. +MCP servers supporting the [MCP Apps](https://github.com/modelcontextprotocol/ext-apps) standard render interactive UIs directly below their tool calls (supported on Codex and Claude Code 2.1.301+ on up-to-date T3 servers). -An app can open full screen right after you tap or click in it. On web and desktop, a tap in the app within five seconds of a click or key press elsewhere in T3 Code doesn't count, so tap it again after that. Use the button in its top corner, or press Escape outside the app, to return it to the thread. Anything else that needs your attention, such as an approval, also returns it to the thread. On mobile, full screen opens the app again in its own screen, so anything the app does not save itself starts over. An app can also keep the agent informed of what you did in it, such as a filter you picked; T3 Code sends the latest note from each app with your next message. +- **Safety**: T3 Code asks before an MCP app runs non-read-only server tools, posts messages to the thread, opens links (mobile), or saves files. Navigating away from its own page stops the app. +- **Session requirement**: Apps remain viewable after a turn ends, but interacting with them requires the thread's agent session to be running. +- **Full screen**: Expand an app full screen and press `Esc` (or the corner button) to return to the thread. diff --git a/docs/user/install.md b/docs/user/install.md index 60ee758a0e656..19fc9de9c81e0 100644 --- a/docs/user/install.md +++ b/docs/user/install.md @@ -1,64 +1,42 @@ # Install T3 Code -T3 Code runs coding agents on your computer and lets you control them from its -desktop, web, or mobile app. Set up the machine where the agents will work first. +T3 Code runs coding agents on your computer (or server) and lets you control them from the desktop app, web app, or mobile app. Install T3 Code on the machine where your agents will run first. ## Requirements -You need an installed, authenticated provider before starting a thread. You can -launch T3 Code and configure providers afterwards. +You need at least one installed, authenticated coding agent (provider) before starting a thread. You can launch T3 Code first and set up providers from the [Welcome page](./welcome-page.md) or **Settings → Providers**. ## Command line +Install the `t3` command to `~/.local/bin`: + ```bash +# macOS / Linux curl -fsSL https://t3.codes/install.sh | sh ``` -On Windows, in PowerShell: - ```powershell +# Windows (PowerShell) irm https://t3.codes/install.ps1 | iex ``` -This installs the `t3` command to `~/.local/bin`. If that folder is not on your -`PATH` yet, the installer says so and, for zsh, bash on Linux, and fish, prints -a command to add it. On Windows, `t3` works in the same PowerShell window right -away; add the folder to your `PATH` for new windows. If a `t3` that the -installer or the desktop app did not create is already there, it leaves that -one alone and stops. Set `T3CODE_CHANNEL=nightly` to install the nightly train, or -`T3CODE_VERSION` to pin an exact version. - -| Task | Command | -| ------------------------------------- | ----------------------------------------------------------------------- | -| Start the server and open the web app | `t3` | -| Start the server without a browser | `t3 serve` | -| Use it from your other devices | `t3 up` ([details](./remote-access.md)) | -| Keep it running in the background | `t3 service install` ([details](./background-service.md)) | -| Move to the newest release | `t3 update` | -| Reclaim database space | `t3 doctor` ([details](./background-service.md#reclaim-database-space)) | -| Remove it again | `t3 uninstall` | - -Run `t3 help` or `t3 --help` for the full reference. To start in a new working -directory, use an explicit path such as `t3 ./my-project`. A bare directory name -is accepted only if it already exists. - -If `t3` or `t3 start` reports an already running server, run the `t3 pair` -command it names and open the pairing URL to connect to that server. Stop it -before starting a replacement, or use a different `--base-dir` for an -independent server. - -To try T3 Code once without installing it, run `npx t3@latest` instead (needs -Node.js for `npx`). It offers to install the `t3` command first. If you say no, -it asks again at the next minor release, and `npx t3 install` installs it later. -`npx t3` always runs the version npm picked, even when a `t3` is installed. On -the nightly train, run your installed `t3` (for example `t3 connect`), not -`npx t3`, which runs the latest stable release. +Set `T3CODE_CHANNEL=nightly` for nightly builds or `T3CODE_VERSION=` to pin a version. To try once without installing, run `npx t3@latest` (requires Node.js; always runs the latest stable release). + +| Task | Command | +| ----------------------------- | ----------------------------------------------------------------------- | +| Start server and open web app | `t3` (or `t3 ./my-project`) | +| Start server without browser | `t3 serve` | +| Set up remote access | `t3 up` ([Remote access](./remote-access.md)) | +| Run in the background | `t3 service install` ([Background service](./background-service.md)) | +| Update | `t3 update` | +| Reclaim database space | `t3 doctor` ([Details](./background-service.md#reclaim-database-space)) | +| Uninstall | `t3 uninstall` | + +If `t3` reports a server is already running, connect with `t3 pair` or pass a separate `--base-dir`. Run `t3 --help` for all commands. ### Intel Macs -There is no `t3` executable for Intel Macs (the desktop app is available). To -run a server there, build it from source with `vp`, which provides the Node version it needs -([Install vp](../operations/00_development.md#first-checkout)): +There is no standalone `t3` binary for Intel Macs—use the desktop app, or build a server from source with `vp` ([development runbook](../operations/00_development.md#first-checkout)): ```bash git clone https://github.com/pingdotgg/t3code @@ -66,236 +44,86 @@ cd t3code && vp i && vp run build:desktop node apps/server/dist/bin.mjs ``` -`t3 update` and the background service do not apply to a server run this way; -update it with `git pull` and a rebuild. - ## Desktop app -Download a release from [GitHub Releases](https://github.com/pingdotgg/t3code/releases), -or use a package manager: - -| Platform | Install | -| ------------------ | ------------------------------------------------------------ | -| Windows | `winget install T3Tools.T3Code` | -| Windows (Scoop) | `scoop install extras/t3code` | -| macOS | `brew install --cask t3-code` | -| Debian, Ubuntu | `sudo apt install ./T3-Code-*.deb` | -| Arch Linux | `yay -S t3code-bin` | -| Arch Linux nightly | `yay -S t3code-nightly-bin` | -| Nix | `nix profile add github:NixOS/nixpkgs/nixos-unstable#t3code` | - -### Linux - -AppImage and `.deb` downloads are available for x86_64 and ARM64. Check your -architecture with `uname -m`: for `x86_64`, choose a file ending in -`x86_64.AppImage` or `amd64.deb`; for `aarch64`, choose `arm64.AppImage` or -`arm64.deb`. - -To launch an AppImage, open a terminal in its download folder. Replace -`T3-Code.AppImage` below with the exact filename you downloaded: - -```bash -chmod +x ./T3-Code.AppImage -./T3-Code.AppImage -``` - -The `.deb` updates itself like the other desktop builds. It asks for your -password to install each update. If your desktop has no password prompt, the -update fails. Download the new `.deb` and install it the same way. - -The AUR packages support x86_64 and ARM64. -Update AUR installs with your AUR helper, such as `yay -Syu`, instead of the -in-app updater. - -### Nix (nixpkgs) +Download from [GitHub Releases](https://github.com/pingdotgg/t3code/releases) or install via a package manager: -T3 Code is maintained in [nixpkgs](https://github.com/NixOS/nixpkgs/tree/nixos-unstable/pkgs/by-name/t3/t3code). -The command above installs from `nixos-unstable` and requires Nix 2.30 or later with -`nix-command` and `flakes` enabled. Launch the desktop app with `t3code-desktop`; -the package also includes the `t3` command. +| Platform | Command | +| ----------------------- | ---------------------------------------------------------------- | +| macOS | `brew install --cask t3-code` | +| Windows | `winget install T3Tools.T3Code` or `scoop install extras/t3code` | +| Debian / Ubuntu | `sudo apt install ./T3-Code-*.deb` | +| Arch Linux | `yay -S t3code-bin` (or `yay -S t3code-nightly-bin`) | +| Nix (flakes, Nix 2.30+) | `nix profile add github:NixOS/nixpkgs/nixos-unstable#t3code` | -On NixOS, you can instead add the package to your system configuration, using -a nixpkgs revision that includes `t3code`: - -```nix -environment.systemPackages = [ pkgs.t3code ]; -``` - -Apply the change with `sudo nixos-rebuild switch`. For Home Manager, add -`pkgs.t3code` to `home.packages` and run `home-manager switch`. - -Update a profile installation with `nix profile upgrade t3code`. For NixOS or -Home Manager, update your configuration's nixpkgs input or channel and rebuild. -Nix manages both the desktop app and the bundled -`t3` command; use Nix to update them instead of the in-app updater or `t3 update`. +- **Linux AppImage**: `chmod +x ./T3-Code-*.AppImage && ./T3-Code-*.AppImage` (x86_64 and ARM64). `.deb` self-updates with a password prompt; update AUR packages via your AUR helper (`yay -Syu`). +- **NixOS / Home Manager**: Add `pkgs.t3code` to `environment.systemPackages` or `home.packages` (`t3code-desktop` launches the app; `t3` is included). Update via Nix rather than the in-app updater. ### The `t3` command -The desktop app includes the `t3` command-line tool. A new install sets it up -on first launch; after an update, or any time, choose **Install** next to -**t3 command** in **Settings → About**. On macOS and Linux it adds a `t3` link -in `~/.local/bin` (or `~/bin`); on Windows it adds the app's command folder to -your `PATH`. Open a new terminal afterwards. If the folder is not on your -`PATH`, **Add to PATH** on the Welcome page or in **Settings → About** adds one -line to your shell's startup file. **Remove** takes it off, and the app does not -add it again. If you already have another `t3`, it stays as it is. - -### Windows Subsystem for Linux - -Choose a WSL distro in **Settings → Sharing & access** to run agents and projects -there. Install the provider CLIs inside that distro. T3 Code installs its own -server runtime there automatically; the first launch after an app update can -take longer. - -### Open a project from a terminal +The desktop app bundles `t3` and sets it up on first launch (manage anytime under **Settings → About → t3 command**). Use **Add to PATH** if needed, then open a new terminal. -With the desktop app already running on the same machine: +- **Open a folder in the running desktop app**: Run `t3 app` (or `t3 app ../my-project`) from a terminal, or drag folders from your file manager onto the desktop sidebar. -```bash -t3 app -``` - -This opens a new thread for the current directory, adding the project if needed. -Pass a path, such as `t3 app ../my-project`, to open another directory. It requires -the desktop app, so a standalone server or an SSH session is not enough. If the -command cannot reach the app, start or update the desktop app and try again. - -### Drop a folder on the sidebar +### Windows Subsystem for Linux -Drag one or more folders from Finder, Explorer, or your file manager onto the -sidebar. Each one opens as a project on this computer, the same as `t3 app`. -Files dropped on a thread still attach to that thread. Browsers do not share -folder paths, so in the web app use **Add project** instead. +Select a WSL distro in **Settings → Sharing & access** to run agents and projects inside WSL (install provider CLIs inside that distro). T3 Code manages its own server runtime inside WSL automatically. ## Mobile app -Install T3 Code from the -[App Store](https://apps.apple.com/us/app/t3-code-remote-claude-more/id6787819824) or -[Google Play](https://play.google.com/store/apps/details?id=com.t3tools.t3code). -The phone connects to a server on another machine. Follow -[remote access](./remote-access.md) to link it through T3 Connect or a pairing URL. - -Store links and QR codes are also available in **Settings → About → Mobile app** -on web and desktop. The store apps work with both stable and Nightly servers. Test builds are optional: - -- **iPhone and iPad:** TestFlight is invite-only. -- **Android:** download an APK from the - [Android beta releases](https://github.com/pingdotgg/t3code/releases?q=android-beta-). +Install from the [App Store](https://apps.apple.com/us/app/t3-code-remote-claude-more/id6787819824) or [Google Play](https://play.google.com/store/apps/details?id=com.t3tools.t3code) (QR codes are also in **Settings → About → Mobile app**). The mobile app connects to a server on another machine via [remote access](./remote-access.md). -If the app crashes during launch, open Settings → Diagnostics on the next launch -that succeeds. It lists startup crashes from the last 7 days with the error and -component stack that store crash reports leave out. Copy the report and paste it -into a GitHub issue. Error messages can quote values from the app, so read it over -before sharing. +- Store builds work with both Stable and Nightly servers. Optional Android beta APKs are under [Android beta releases](https://github.com/pingdotgg/t3code/releases?q=android-beta-). +- If the mobile app crashes on launch, open **Settings → Diagnostics** on the next launch to copy recent startup crash reports. ## Providers -Open **Settings → Providers** in the web or desktop app, select the environment, -and enable the provider you want. Installation, login, and configuration belong -to that environment's machine, even when you connect from a phone or another -computer. - -| Provider | Install and authenticate | -| ------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | -| Codex | [Connect with ChatGPT](./providers-codex.md#connect-with-chatgpt), or install [Codex CLI](https://developers.openai.com/codex/cli) and run `codex login`. | -| Claude | Install [Claude Code](https://claude.com/product/claude-code), then run `claude auth login`. | -| Cursor | Install [Cursor CLI](https://cursor.com/cli), then run `agent login`. | -| Grok Build | Install [Grok Build CLI](https://x.ai/cli), then run `grok login`. | -| Kiro | Install [Kiro CLI](https://kiro.dev/docs/cli/), then run `kiro-cli login`. | -| OpenCode | Install [OpenCode](https://opencode.ai), then run `opencode auth login`. | -| Antigravity | Install and sign in with Google from T3 Code's provider settings. | -| Pi | Install [Pi](./providers-pi.md#set-up-pi) with Node.js 22.19 or newer, then run `pi` and `/login`. | -| Muse Code | Install [Muse Code](https://dev.meta.ai/docs/muse-code) on the server, run `muse login`, then enable it in Settings → Providers. | -| fx | Install [fx](https://fx.sh) with `curl -fsSL https://fx.sh/setup.sh \| bash`, then run `fx login`. | -| ACP Registry agents | Add GitHub Copilot and other [ACP agents](./providers-acp.md#add-an-agent) from **Settings → Providers → Add provider → Show more**. | - -Provider CLIs must be on the server's `PATH`. If T3 Code cannot find one, set its -**Binary path** in provider settings, especially when using a version manager. -Cursor's executable is `cursor-agent`, although its login command is -`agent login`. Codex connected through ChatGPT and Antigravity can use their -managed runtimes without a `PATH` entry. - -T3 Code warns when a provider version has known compatibility problems with your -release. Check **Settings → Providers** on that environment for the recommended -version or range. When its package manager supports installing a specific version, -you can install the recommendation there. Otherwise use the provider's installer -on the environment's machine. An unlisted version is unverified. - -When a provider CLI is behind its latest release, its provider card shows the -available version. **Update now** runs the installer that owns the CLI -(Homebrew, mise, or a global npm, pnpm, Yarn, Bun, Volta, or Vite+ install), or -the CLI's own update command when T3 Code cannot tell. Claude, Codex, and -OpenCode installs T3 Code cannot identify stay manual: update them through the -installer you used. T3 Code runs `mise upgrade` -only for a tool your mise config requests as `latest` when the provider's binary -path is a mise shim or under the tool's `installs//latest` link; update a -pinned version, or a path into one version's directory, through mise yourself. -Update a CLI installed with Nix through Nix. -Cursor and Antigravity update with T3 Code. Homebrew and Chocolatey installs -compare against the version their package manager offers, which can trail the -npm release; update Claude installed with Chocolatey through Chocolatey. - -The managed runtimes for Antigravity and for Codex connected through ChatGPT -first install the release T3 Code tested. When T3 Code finds a newer compatible -release, their setup in **Settings → Providers** offers an update. - -Add another provider instance for a separate account or configuration. Each -instance can have its own environment variables, such as API keys or a custom -base URL. Mark secret values as sensitive; after saving, T3 Code does not display -their original values. - -For provider-specific setup and accounts, see [Codex](./providers-codex.md), -[Claude](./providers-claude.md), [OpenCode](./providers-opencode.md), -[Antigravity](./providers-antigravity.md), [Kiro](./providers-kiro.md), -[Pi](./providers-pi.md), [Muse Code](./providers-muse.md), [fx](./providers-fx.md), and -[ACP Registry agents](./providers-acp.md). +Open **Settings → Providers** (web or desktop), select the environment, and enable the providers you use. Installation and sign-in always happen on the **environment's machine**. + +| Provider | Install and authenticate | Guide | +| ---------------- | ------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------- | +| **Codex** | Connect with ChatGPT in Settings, or install [Codex CLI](https://developers.openai.com/codex/cli) and run `codex login`. | [Codex](./providers-codex.md) | +| **Claude** | Install [Claude Code](https://claude.com/product/claude-code) and run `claude auth login`. | [Claude](./providers-claude.md) | +| **Cursor** | Sign in in Settings or install [Cursor CLI](https://cursor.com/cli) and run `agent login`. | [Cursor](./cursor.md) | +| **Grok Build** | Install [Grok Build CLI](https://x.ai/cli) and run `grok login`. | [Grok](./providers-grok.md) | +| **Antigravity** | Install managed runtime and sign in with Google in Settings. | [Antigravity](./providers-antigravity.md) | +| **OpenCode** | Install [OpenCode](https://opencode.ai) and run `opencode auth login`. | [OpenCode](./providers-opencode.md) | +| **Kiro** | Install [Kiro CLI](https://kiro.dev/docs/cli/) and run `kiro-cli login`. | [Kiro](./providers-kiro.md) | +| **Pi** | Install [Pi](./providers-pi.md) (Node.js 22.19+) and run `pi` → `/login`. | [Pi](./providers-pi.md) | +| **Muse Code** | Install [Muse Code](https://dev.meta.ai/docs/muse-code) and run `muse login`. | [Muse Code](./providers-muse.md) | +| **fx** | Install [fx](https://fx.sh) and run `fx login`. | [fx](./providers-fx.md) | +| **ACP Registry** | Add GitHub Copilot and other agents in **Settings → Providers → Add provider → Show more**. | [ACP](./providers-acp.md) | + +- **Binary path**: If a CLI isn't on the server's `PATH` (common with version managers), set **Binary path** in the provider's settings. +- **Updates**: Click **Update now** on outdated provider cards (supports Homebrew, mise `latest`, npm/pnpm/Yarn/Bun/Volta/Vite+, or the CLI's own updater; update Nix, Chocolatey, or pinned mise installs manually). +- **Multiple instances**: Add extra provider instances for separate accounts, API keys, or custom endpoints (mark secret env vars as sensitive). ### Provider check timeouts -If a provider works in its CLI but T3 Code reports a timeout while checking it, -allow more time in the T3 server's environment. For example, give Codex and -Claude readiness checks 60 seconds: +If a working CLI times out during T3 Code's readiness check, increase its probe deadline (in milliseconds) in the server's environment (or systemd override / `service.env`) and restart: ```bash T3CODE_CODEX_PROBE_TIMEOUT_MS=60000 T3CODE_CLAUDE_PROBE_TIMEOUT_MS=60000 t3 serve ``` -For a remote environment, set these on the machine running the T3 server. -Keep them in your launcher or service configuration to retain them across -updates, then restart the server. For systemd, add -`Environment=T3CODE_CODEX_PROBE_TIMEOUT_MS=60000` under `[Service]` in a service -override, reload systemd, and restart the service. Provider instances can also -set their own overrides in Settings → Providers. - -Each variable extends that provider's readiness-probe deadlines; a phase whose -default is already longer keeps its default. Providers with several phases can -take longer than one deadline in total. Values must be whole milliseconds no -greater than 2147483647; unset or invalid values keep the defaults. - -| Provider | Environment variable | -| ------------------- | -------------------------------------- | -| Codex | `T3CODE_CODEX_PROBE_TIMEOUT_MS` | -| Claude | `T3CODE_CLAUDE_PROBE_TIMEOUT_MS` | -| Cursor | `T3CODE_CURSOR_PROBE_TIMEOUT_MS` | -| Antigravity | `T3CODE_ANTIGRAVITY_PROBE_TIMEOUT_MS` | -| Grok | `T3CODE_GROK_PROBE_TIMEOUT_MS` | -| Kiro | `T3CODE_KIRO_PROBE_TIMEOUT_MS` | -| fx | `T3CODE_FX_PROBE_TIMEOUT_MS` | -| Pi | `T3CODE_PI_PROBE_TIMEOUT_MS` | -| Muse Code | `T3CODE_MUSE_PROBE_TIMEOUT_MS` | -| OpenCode | `T3CODE_OPENCODE_PROBE_TIMEOUT_MS` | -| ACP Registry agents | `T3CODE_ACP_REGISTRY_PROBE_TIMEOUT_MS` | - -Longer deadlines also take longer to report a stalled check. These overrides -cover readiness and discovery, including OpenCode server startup. Usage and -config enrichment retain their own shorter limits. Turn execution, package -installation, update checks, and shutdown limits keep their existing behavior. +| Provider | Environment variable | +| ------------ | -------------------------------------- | +| Codex | `T3CODE_CODEX_PROBE_TIMEOUT_MS` | +| Claude | `T3CODE_CLAUDE_PROBE_TIMEOUT_MS` | +| Cursor | `T3CODE_CURSOR_PROBE_TIMEOUT_MS` | +| Antigravity | `T3CODE_ANTIGRAVITY_PROBE_TIMEOUT_MS` | +| Grok | `T3CODE_GROK_PROBE_TIMEOUT_MS` | +| Kiro | `T3CODE_KIRO_PROBE_TIMEOUT_MS` | +| fx | `T3CODE_FX_PROBE_TIMEOUT_MS` | +| Pi | `T3CODE_PI_PROBE_TIMEOUT_MS` | +| Muse Code | `T3CODE_MUSE_PROBE_TIMEOUT_MS` | +| OpenCode | `T3CODE_OPENCODE_PROBE_TIMEOUT_MS` | +| ACP Registry | `T3CODE_ACP_REGISTRY_PROBE_TIMEOUT_MS` | ## Next steps +- [User guide index](./README.md): overview of how T3 Code works. - [Working with threads](./thread-sidebar.md): start tasks and organize parallel work. -- [Permission modes](./permission-modes.md): choose when agents ask before acting. +- [Permission modes](./permission-modes.md): control when agents ask before acting. - [Remote access](./remote-access.md): connect from another device. -- [Running in the background](./background-service.md): keep a host available. -- [Updating T3 Code](./updating.md): update the app and connected servers. -- [Managed policy](./managed-policy.md): configure T3 Code for everyone on a machine. +- [Updating T3 Code](./updating.md): keep apps, servers, and providers up to date. diff --git a/docs/user/keybindings.md b/docs/user/keybindings.md index eab9e88ec98f0..fc2f5f0450924 100644 --- a/docs/user/keybindings.md +++ b/docs/user/keybindings.md @@ -1,225 +1,97 @@ # Keybindings -Customize shortcuts in **Settings → Keybindings** on web and desktop. That page -also lists the command IDs and defaults available in your version. - -To free a default shortcut for another command, choose **Unassign** from its row's -actions menu. **Reset to default** brings it back. - -## Composer controls - -`mod+shift+d` starts dictation in the focused editor, or the composer, and finishes it on the next press; -`Esc` discards the recording. Change the chord under **Composer: Start or Finish -Dictation**, and the hold or toggle behavior in **Settings → Voice**. See -[Voice input](./voice-input.md). - -In **Settings → Chat → Send shortcut**, choose whether Enter sends, requires -`mod+Enter` for multiline prompts, or always requires `mod+Enter`. `Shift+Enter` -inserts a new line. This applies to the web and desktop composer at desktop widths. - -**Follow-up behavior** chooses Queue or Steer while the agent runs. Use -`mod+Enter` to do the opposite for one message, even when the send shortcut -requires a modifier. `mod+Alt+Enter` sends, keeps that thread running in the -background, and opens a fresh new-thread composer. In a new thread, `mod+Enter` -does the same. Change these shortcuts in **Settings → Keybindings** under -**Composer: Opposite Queue or Steer Action**, **Composer: Start in Background**, -or **Composer: Send and Start New Thread**. These bindings take priority over the -send shortcut. Click the send button to use the configured follow-up behavior. - -When a thread has queued messages, `mod+Shift+Enter` sends the first one as a steer -while a turn is running, or as a new turn when the thread is stopped. Change it under -**Queue: Send First Queued Message** in Keybindings. - -Use `mod+shift+m` to choose a model and `mod+shift+h` to choose a host. -To step a new thread to the next machine instead of opening the menu, bind -**Composer: Cycle Host** in Keybindings. It has no default shortcut. -Use `mod+shift+e` for effort, `mod+shift+a` for permissions, `mod+shift+x` for the -workspace, and `mod+shift+g` for the Git branch. The workspace menu includes the -current checkout, a new worktree, and the previous worktree when available. -Use `mod+shift+l` to reuse the previous worktree directly. - -To change effort one step without opening the picker, bind -**Composer: Increase Effort** and **Composer: Decrease Effort** in Keybindings. -Both are unbound by default. Increase wraps from the highest level to the -lowest, and decrease wraps from the lowest level to the highest. - -In the model picker, press Left in an empty search field or Shift+Tab to reach -the provider list. Use Up/Down to move and Enter to choose. Right returns to -model search. Right at the end of the search moves to the highlighted model's effort -levels, and Left comes back. Choosing a model keeps the picker open on its effort. `mod+shift+up` and `mod+shift+down` switch providers directly and clear the -search. These provider shortcuts can also be changed in Settings. - -These shortcuts run inside the focused web or desktop client. `mod` uses Command -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. - -## Copy pull request references - -With a PR open in the right panel or on the Pull requests page, use `mod+shift+c` -to copy its URL and `mod+shift+k` to copy its number with a `#` prefix. -Both shortcuts can be changed in Settings. Search for “Copy Link or Thread” -or “Copy Number”. They copy the selected PR and leave terminal input alone. -Without a PR, `mod+shift+c` copies the thread itself, which pastes into a -composer as a thread chip. - -## Find in a diff - -Click into a diff in the Diff panel or a pull request's Code tab, then press -`mod+f` to search every file in it, including folded files and unchanged lines -hidden between changes. Enter and `Shift+Enter` move between matches, and a -match in a folded file opens it. Escape closes the search. This shortcut is not -configurable. A very large uncommitted diff loads its files as you scroll, and -find only searches the files loaded so far. - -## iPad - -With a hardware keyboard, use `Cmd+1` through `Cmd+9` to open the first nine -displayed threads. The shortcuts follow the current list filters and order. -`Cmd+K` opens the command palette to search commands, projects, and threads. -Use the arrow keys and Return to choose a result, or `Cmd+1` through `Cmd+9` to -choose directly. Escape or `Cmd+K` closes the palette. Start a search with `>` -to show only actions. - -In a new thread, `Cmd+Shift+H` moves the draft to the next machine. - -In the composer, Return sends and `Shift+Return` inserts a new line. While a -turn is running, `Cmd+Return` sends with the other follow-up action. To make -Return insert a new line instead, change the Return key behavior in Settings → -Keyboard; `Cmd+Return` then sends. - -## Android - -With a hardware keyboard, the composer handles Return as on iPad, with `Ctrl` in -place of `Cmd`. The on-screen keyboard's Return always inserts a new line. +Customize keyboard shortcuts in **Settings → Keybindings** on web and desktop. That page lists every available command ID and default binding. -## Edit the configuration file +To free a default shortcut, choose **Unassign** from its row menu (**Reset to default** restores it). -Keybindings live on the environment's machine, in -`~/.t3/userdata/keybindings.json` by default. You can edit this file directly. -It is a JSON array of rules: +> Note: `mod` means `Cmd` on macOS and `Ctrl` on Windows and Linux. -```json -[ - { "key": "mod+g", "command": "terminal.toggle" }, - { "key": "mod+shift+g", "command": "terminal.new", "when": "terminalFocus" } -] -``` +## Common composer shortcuts + +| Action | Default | Notes | +| --------------------------- | ----------------- | ------------------------------------------------------------------ | +| Start / finish dictation | `mod+shift+d` | `Esc` discards. See [Voice input](./voice-input.md). | +| Opposite queue/steer action | `mod+Enter` | Uses the non-default follow-up behavior while a turn runs. | +| Start thread in background | `mod+Alt+Enter` | Also `mod+Enter` in a new thread; opens a fresh draft immediately. | +| Send first queued message | `mod+Shift+Enter` | Steers if running, or starts a turn if stopped. | +| Pick model | `mod+shift+m` | `mod+shift+up/down` switches providers inside the picker. | +| Pick host / environment | `mod+shift+h` | Bind **Composer: Cycle Host** to step without a menu. | +| Pick effort | `mod+shift+e` | Bind **Increase/Decrease Effort** to step without a menu. | +| Pick permissions | `mod+shift+a` | | +| Pick workspace mode | `mod+shift+x` | `mod+shift+l` reuses the previous worktree directly. | +| Pick Git branch | `mod+shift+g` | | + +Configure whether `Enter` sends or requires `mod+Enter` in **Settings → Chat → Send shortcut** (`Shift+Enter` always inserts a newline). -T3 Code creates the file with its defaults and adds new defaults on later startups. -New defaults do not replace commands you customized. If a new default overlaps one -of your shortcuts, [rule order](#precedence) decides which runs. -Invalid rules are ignored; if the file cannot be parsed, T3 Code uses defaults. +In the model picker, use `Left`/`Shift+Tab` to move to the provider list, `Right` to return to search or move into effort levels, and `Up`/`Down`/`Enter` to select. -## Rule shape +## Copy pull request and thread references -Each rule requires a `key` shortcut and a `command` ID. An optional `when` -expression restricts when it runs. +- `mod+shift+c`: Copies the open PR's URL (or copies a thread chip link when no PR is open). +- `mod+shift+k`: Copies the open PR's `#number`. -Project scripts use `script.{id}.run`, such as `script.test.run`. +Remap under **Copy Link or Thread** and **Copy Number** in **Settings → Keybindings**. -## Key syntax +## Find -Join modifiers and a key with `+`, such as `mod+shift+d` or `ctrl+l`. -`mod` means Command on macOS and Control elsewhere. Other modifiers are -`cmd` / `meta`, `ctrl` / `control`, `alt` / `option`, and `shift`. +- **Current thread** (`chat.find`, default `mod+f` outside terminals/previews): Searches all messages and plans in the thread (requires an up-to-date server). Use `Enter` / `Shift+Enter` to step through matches and `Esc` to close. +- **Diffs** (`mod+f` inside a diff or PR Code tab): Searches all loaded files in the diff, unfolding matching files. Not configurable. Very large uncommitted diffs only search files loaded so far. +- **Browser page** (`preview.find`, default `mod+f` in a desktop browser tab): Searches the open page. If a page handles `mod+f` itself, use the browser's **⋮** menu. Not supported in web clients or streamed browser tabs. -## When conditions +## Hardware keyboards on iPad and Android -Available context keys are `terminalFocus`, `terminalOpen`, `previewFocus`, -`previewOpen`, `rightPanelOpen`, `modelPickerOpen`, `usagePageOpen`, `composerFocus`, -`draftThreadRoute`, `turnRunning`, `composerEmpty`, `editableFocus`, `isWeb`, and `isDesktop`. -In a thread, `rightPanelOpen` is true while its right panel is open; the default -`mod+t` uses it to open the panel's new-tab menu. -`draftThreadRoute` is true on a draft thread, including a restored draft, until it is first sent. -`composerEmpty` is true while the composer has no text, attachments, or context, and is not -editing a queued message or answering a question. -`editableFocus` is true while a text field, the composer, or another editor has -the keyboard. `isWeb` is true in a browser tab. `isDesktop` is true in the -desktop app. Unknown keys evaluate to `false`. +- **iPad**: `Cmd+1`–`Cmd+9` open the first nine visible threads; `Cmd+K` opens the command palette (prefix with `>` for actions only); `Cmd+Shift+H` cycles host on a new thread. `Return` sends (`Shift+Return` for newline; `Cmd+Return` for opposite follow-up). Change Return behavior in **Settings → Keyboard**. +- **Android**: Same composer Return behavior using `Ctrl` instead of `Cmd`. The on-screen keyboard's Return always inserts a newline. -`mod+1` through `mod+9` jump to the first nine threads, and to models while the -model picker is open. The thread jumps do not run while the model picker is open. -Those defaults use `isDesktop` so they do not steal the -browser's tab-switch shortcuts. Remove that condition in Settings if you want -the same jumps in a browser. +## Edit the configuration file -Combine keys with `!` for not, `&&` for and, `||` for or, and parentheses: +Keybindings are stored on the environment's machine at `~/.t3/userdata/keybindings.json` as a JSON array: ```json -{ "key": "mod+j", "command": "terminal.toggle", "when": "terminalOpen && !terminalFocus" } +[ + { "key": "mod+g", "command": "terminal.toggle" }, + { "key": "mod+shift+g", "command": "terminal.new", "when": "terminalFocus" } +] ``` -## Find in the current thread +New default bindings are added on startup without overwriting customized commands. Invalid rules are ignored; an unparseable file falls back to defaults. -`chat.find` searches conversation messages and proposed plans in the active thread. Entering a -query searches the entire thread, including older messages. Thread search requires server support; -update an older server to enable it. Select **Retry** if a search fails. It defaults to -`mod+f` outside terminals and previews. Press **Enter** or **Shift+Enter** to move between matches, -and **Escape** to close find. +### Rule shape and key syntax -## Find on a browser page +Each rule requires `key` and `command`, plus an optional `when` condition. Project scripts use `script.{id}.run` (e.g. `script.test.run`). -`preview.find` (`mod+f` while a browser has focus) searches the open page in the desktop app. It -is also in the browser's **⋮** menu and the command palette. A page that handles `mod+f` itself, -such as a code editor, keeps its own find. Use the **⋮** menu to reach the browser's find there. -Streamed browser tabs and T3 Code in a web browser do not support it. +Join modifiers and keys with `+` (`mod`, `cmd`/`meta`, `ctrl`/`control`, `alt`/`option`, `shift`). -## Precedence - -The last rule whose key and condition both match wins, even if it belongs to a -different command. Put a more specific rule after a general one when they share -a shortcut. +### When conditions -## Commands with special behavior +Available context keys: `terminalFocus`, `terminalOpen`, `previewFocus`, `previewOpen`, `rightPanelOpen`, `modelPickerOpen`, `usagePageOpen`, `composerFocus`, `draftThreadRoute`, `turnRunning`, `composerEmpty`, `editableFocus`, `isWeb`, `isDesktop`. Unknown keys evaluate to `false`. -`thread.stop` interrupts the running turn in the focused thread. It has no default -shortcut; assign one in **Settings → Keybindings**. +Combine with `!`, `&&`, `||`, and parentheses: -`thread.regenerateTitle` generates a new title for the focused thread, like -**Regenerate title** in the thread menu. It has no default shortcut. +```json +{ "key": "mod+j", "command": "terminal.toggle", "when": "terminalOpen && !terminalFocus" } +``` -`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 -actions of the same kind undo together. The notice remains available for five -seconds after the latest action. Right after an action, the shortcut works even -in a text field such as the composer. Once you type or press another key, the -field gets its own undo back. Terminals always keep their native shortcut. +> Tip: `mod+1`–`mod+9` default to `isDesktop` so they don't hijack browser tabs. Remove that condition in Settings if you want thread jumps on web. -`navigation.back` (`mod+[` by default) and `navigation.forward` (`mod+]`) move -through the pages you have visited, like a browser's back and forward buttons. +## Precedence -`chat.new` may ask you to choose a project when there is more than one. -`chat.newLocal` skips that chooser. Both use your -[new-thread defaults](./thread-sidebar.md#start-a-thread). `chat.newWithoutProject` -(`mod+alt+n`) starts a thread [without a project](./thread-sidebar.md#start-without-a-project). +The last matching rule in `keybindings.json` wins, even across different commands. Place more specific rules after general ones. -## Reserved shortcuts +## Commands with special behavior -In the desktop app, `mod+w` closes the focused terminal or the active right-panel -tab. When nothing remains to close, it does nothing; it never closes the window. In a browser, `mod+w` -closes the browser tab; rebind `rightPanel.close` and `terminal.close` to an available -shortcut such as `alt+w`. +- `thread.stop`: Interrupts the running turn (unbound by default). +- `thread.regenerateTitle`: Regenerates the focused thread's title (unbound by default). +- `thread.undo` (`mod+z`): Undoes recent sidebar actions (unpin, settle, snooze, archive, discard draft) within 5 seconds, including consecutive actions of the same kind. +- `navigation.back` (`mod+[`) / `navigation.forward` (`mod+]`): Moves through visited pages. +- `chat.new` / `chat.newLocal` / `chat.newWithoutProject` (`mod+alt+n`): Start new threads using your [new-thread defaults](./thread-sidebar.md#start-a-thread) or [without a project](./thread-sidebar.md#start-without-a-project). -`mod+shift+t` reopens the last closed tab across the app, including files, -diffs, pull requests, browsers, and devices, in the order you closed them. -A browser opens in a fresh session without its old page history. Incognito tabs -can reopen until you reload or quit the app. This shortcut does not undo deleted work. -Browsers also use it to reopen browser tabs; choose another binding in Settings -if the browser takes it first. +## Reserved and platform shortcuts -Many defaults include `!terminalFocus` so they do not intercept terminal input. -Keep that condition when remapping them if you want the same behavior. -`sidebar.toggle` never takes a Ctrl chord from a focused terminal, so tmux's `Ctrl+B` -prefix reaches it. On macOS, `Cmd+B` still toggles the sidebar there. +- `mod+w` (desktop): Closes the focused terminal or active right-panel tab without closing the window. On web, browsers intercept `mod+w`—rebind `rightPanel.close` and `terminal.close` (e.g. `alt+w`). +- `mod+shift+t`: Reopens the last closed panel tab (files, diffs, PRs, browsers, devices) in order. Browser tabs reopen as fresh sessions. Rebind on web if your browser intercepts it. +- Keep `!terminalFocus` when remapping shortcuts that shouldn't intercept terminal input. `sidebar.toggle` ignores `Ctrl+B` inside terminals so `tmux` keeps its prefix (`Cmd+B` still works on macOS). ## Desktop quit shortcut -Use `Cmd+Q` on macOS or `Ctrl+Q` on Windows and Linux. In the default **Hold** mode, -hold for 1.2 seconds or press twice within 500 milliseconds. Holding requires -keyboard repeat; if repeat is disabled, use two presses or the application menu. - -Change **Settings → General → Confirmations → Quit shortcut** to **Direct** for a -single press or **Double press** for two presses only. Choosing **Quit** from the -application menu always quits immediately. +`Cmd+Q` (macOS) or `Ctrl+Q` (Windows/Linux) defaults to **Hold** mode: hold for 1.2 seconds or press twice within 500 ms. Change this in **Settings → General → Confirmations → Quit shortcut** to **Direct** or **Double press**. Quitting from the application menu always exits immediately. diff --git a/docs/user/keyboard-focus.md b/docs/user/keyboard-focus.md index 2a8edd62b2fa1..9ed9587c7f8e4 100644 --- a/docs/user/keyboard-focus.md +++ b/docs/user/keyboard-focus.md @@ -1,37 +1,24 @@ # Keyboard focus -The command palette keeps focus while open. Closing it returns focus to the composer in chat, -or to the previous control on other pages. Choosing a workspace focus command moves to that -area instead. Opening Pull requests moves focus into that page. -While the palette or model picker is open, number shortcuts select its entries instead of -switching threads. Model shortcuts work in Settings as well as the composer. -See [Keybindings](./keybindings.md) to customize these shortcuts. - -If you return to typing while a terminal is starting, the composer keeps focus when the terminal -becomes ready. Opening or switching to a terminal explicitly still focuses it. +Navigate T3 Code's workspace, sidebar, and settings entirely from the keyboard on web and desktop. See [Keybindings](./keybindings.md) to customize shortcuts. ## Move between workspace areas -On web and desktop, press `F6` or `Shift+F6` to move between the Threads sidebar, -conversation, message input, and visible panels. Navigation wraps around and restores -the last focused control in each area. Pull requests has a page content area. In Settings, -`F6` moves between the section list and the open section. Hidden areas are skipped. Other -dialogs and form popups retain focus; a thread context menu closes when an area command -moves focus away. +Press `F6` or `Shift+F6` to cycle between visible workspace areas—the Threads sidebar, conversation, composer, and open panels (or the section list and content pane in Settings). Each area remembers its last focused control, and hidden areas are skipped. -In a browser, plain `F6` may move to the browser's own toolbar. Use `mod+F6` and -`mod+Shift+F6` instead (`mod` is Command on macOS and Ctrl elsewhere). **Focus Next -Workspace Area** and **Focus Previous Workspace Area** are also in the command palette and -can be remapped in Settings > Keybindings. +In a web browser, plain `F6` may focus the browser toolbar. Use `mod+F6` and `mod+Shift+F6` instead (`Cmd` on macOS, `Ctrl` elsewhere), or run **Focus Next / Previous Workspace Area** from the command palette. -## Browse threads +## Browse threads and settings -Tab moves through each thread and its buttons. Up and Down also move between threads -without opening them; Enter opens the focused thread or toggles a group. Right and Left -expand and collapse groups. `F2` renames the focused thread. +- `Tab`: Moves through each thread row and its actions. +- `Up` / `Down`: Moves between threads (or Settings sections) without opening them. +- `Enter`: Opens the focused thread or toggles a group. +- `Right` / `Left`: Expands and collapses groups. +- `F2`: Renames the focused thread. +- `Shift+F10` (or Context Menu key): Opens the focused thread's menu (`Esc` closes it). -Press `Shift+F10` or the Context Menu key to open the focused thread's menu. Use the arrow -keys to move through it, Enter to choose, and Escape to close it. +## Focus behavior -The Settings section list works the same way: Tab moves through each section, Up and Down -also move between sections without opening them, and Enter opens one. +- Closing the command palette returns focus to the composer in chat (or the previous control elsewhere). +- While the command palette or model picker is open, number shortcuts select its entries instead of switching threads. +- If you resume typing in the composer while a terminal is starting, the composer keeps focus when the terminal finishes loading. diff --git a/docs/user/managed-policy.md b/docs/user/managed-policy.md index 05a942291d67b..8404798e4b259 100644 --- a/docs/user/managed-policy.md +++ b/docs/user/managed-policy.md @@ -1,21 +1,14 @@ # Managed policy -A managed policy lets an administrator configure T3 Code for every user on a machine. It sets -defaults and locks for settings, and limits such as the broadest permission mode or which -providers may run. The T3 Code server on the machine enforces it for every app that connects: -the desktop app, a browser, or the mobile app. +A managed policy lets an administrator set defaults, lock settings, and restrict capabilities (such as maximum permission mode, allowed providers, or remote access) for every user on a machine. The T3 Code server enforces the policy for all connected clients (desktop, web, and mobile). ## Roll out a policy -1. Write the policy as JSON, starting from the [example](#write-a-policy). -2. Run `t3 policy check policy.json`. It prints what the policy will do, or what is wrong with it. -3. Deploy the policy to each machine with your device management tool, in - [one of the supported places](#where-the-policy-goes). -4. Restart T3 Code on the machine. The server reads the policy only when it starts. -5. Run `t3 policy show` on the machine to - [check what the server loaded](#check-what-the-server-loaded). - -The desktop app includes the `t3` command; see [The `t3` command](./install.md#the-t3-command). +1. Author a JSON policy (see [Write a policy](#write-a-policy)). Do **not** include secrets—all local users can read the policy. +2. Validate it: `t3 policy check policy.json`. +3. Deploy via MDM/GPO or a file to [one supported location](#where-the-policy-goes). +4. Restart T3 Code on the machine (policies load at startup only). +5. Verify with `t3 policy show`. ## Write a policy @@ -36,129 +29,44 @@ The desktop app includes the `t3` command; see [The `t3` command](./install.md#t } ``` -`schemaVersion` and `organization` are required. Users see the organization's name in Settings -and beside each control the policy locks, with a link to `supportUrl` if you set one. [`settings`](#settings) -sets defaults and locks, and [`limits`](#limits) restricts what T3 Code may do. - -Every user on the machine can read the policy, so do not put credentials in it. +`schemaVersion` and `organization` are required. Locked controls display your organization name and optional `supportUrl` in Settings. ## Where the policy goes -Use one of these per machine: - -| OS | Native policy | Policy file | -| ------- | ---------------------------------------------------------------------------------------------------- | ------------------------------------------------- | -| macOS | Configuration profile for `com.t3tools.t3code` | `/Library/Application Support/T3Code/policy.json` | -| Windows | Group Policy template, or a `Policy` JSON value (both under `HKLM\SOFTWARE\Policies\T3Tools\T3Code`) | `C:\Program Files\T3Code\policy.json` | -| Linux | | `/etc/t3code/policy.json` | - -T3 Code does not merge sources. If a machine has both a native policy and a policy file, T3 Code -refuses to start until you remove one. - -**Policy file.** Copy the JSON to the path for the OS. Make it and its folder writable only by -administrators. - -**macOS configuration profile.** Add a custom settings payload for the preference domain -`com.t3tools.t3code`. The payload's keys are the policy's top-level keys (`schemaVersion`, -`organization`, `supportUrl`, `settings`, `limits`); JSON objects become dictionaries and lists -become arrays. To make the payload from a policy file you checked, run -`plutil -convert xml1 -o com.t3tools.t3code.plist policy.json` and upload the result, or run -`t3 policy templates --policy policy.json` to write a complete -`macos/t3code.mobileconfig`. Install it as -a device profile, since T3 Code ignores user profiles, and deploy only one profile for this domain. -A profile cannot hold `null`, so use a policy file if a setting's value must be `null`. - -**Windows Group Policy.** Run `t3 policy templates ` and copy -`windows/t3code.admx` and `windows/en-US/t3code.adml` into your `PolicyDefinitions` folder or -central store, or import them into Intune. The policies appear under Computer Configuration > -Administrative Templates > T3 Code. Set **Organization** whenever you set any other T3 Code policy. -Locks and provider fields go in the two JSON policies, as the same objects a policy file would hold. -Machines pick up a change at the next Group Policy refresh; run `gpupdate /target:computer /force` -to apply it now, then restart T3 Code. -Setting **Allow T3 Connect**, **Allow webhook tasks**, **Allow importing browser cookies**, or -**Allow usage data** to **Disabled** turns that feature off. Setting any other T3 Code policy to -**Disabled** restricts nothing, the same as **Not Configured**. - -**Windows registry value.** Instead of the template, set the `Policy` value (`REG_SZ`) to the whole policy as one line of JSON, -from Group Policy Preferences or an Intune script. T3 Code reads it through the Windows registry -API, so it works where registry tools such as `reg.exe` are blocked for users. Use one or the other: -T3 Code refuses to start when the key holds both a `Policy` value and the template's settings. In -PowerShell, as an administrator: - -```powershell -$json = (Get-Content -Raw -Encoding UTF8 policy.json) -replace '\r?\n\s*', '' -New-Item -Path HKLM:\SOFTWARE\Policies\T3Tools\T3Code -Force | Out-Null -Set-ItemProperty -Path HKLM:\SOFTWARE\Policies\T3Tools\T3Code -Name Policy -Value $json -Type String -``` +Use **one** source per machine (having both a native policy and a policy file prevents T3 Code from starting): -## Check what the server loaded +| OS | Native policy | Policy file (admin-writable only) | +| ----------- | --------------------------------------------------------------------------------- | ------------------------------------------------- | +| **macOS** | Device configuration profile for `com.t3tools.t3code` | `/Library/Application Support/T3Code/policy.json` | +| **Windows** | GPO template or `Policy` (`REG_SZ`) under `HKLM\SOFTWARE\Policies\T3Tools\T3Code` | `C:\Program Files\T3Code\policy.json` | +| **Linux** | — | `/etc/t3code/policy.json` | -Run `t3 policy show` as the user who runs T3 Code. It prints the installed policy and its -fingerprint, then says whether the running server loaded that policy or an older one. The server -reads the policy only when it starts, so "Restart T3 Code to apply the installed policy" means it -still enforces the old one. In Settings, users see that your organization manages the environment, -and each locked control shows **Managed by**. +- **macOS profile**: Generate `macos/t3code.mobileconfig` with `t3 policy templates --policy policy.json` (or `plutil -convert xml1 -o com.t3tools.t3code.plist policy.json`). Deploy as a single device profile (profiles cannot represent `null`; use a policy file if needed). +- **Windows GPO**: Generate `windows/t3code.admx` and `windows/en-US/t3code.adml` with `t3 policy templates `, import into `PolicyDefinitions`/Intune under **Computer Configuration → Administrative Templates → T3 Code**, set **Organization**, run `gpupdate /target:computer /force`, and restart T3 Code. +- **Windows registry**: Set `Policy` (`REG_SZ`) to single-line JSON (do not mix with GPO template values). -## Change or remove a policy +## Check what the server loaded -After you deploy, change, or remove a policy, restart the T3 Code server on the machine: quit and -reopen the desktop app, or run `t3 service restart` for the -[background service](./background-service.md). Reconnecting a phone or browser does not reload the -policy. +Run `t3 policy show` as the user running T3 Code to inspect the installed policy, fingerprint, and whether the running server has loaded it. After any policy change or removal, restart the desktop app or run `t3 service restart`. Removing a policy restores the user's own saved settings. -To remove a policy, delete the file, remove the profile, set the Group Policy settings to -**Not Configured**, or delete the registry value, then restart -the server. Users get back the settings they had chosen, since T3 Code never writes policy values -into them. +> Note: T3 Code **refuses to start** if a policy is unreadable, invalid, uses unknown keys from a newer version, or conflicts with another policy source. Always validate with `t3 policy check` and upgrade T3 Code before deploying newer keys. -## When T3 Code refuses to start +## Settings -T3 Code refuses to start rather than run with a policy it cannot fully enforce. That includes a -policy it cannot read or parse, a setting it does not know, a value of the wrong type, a key this -version does not support, or a machine with both a native policy and a file. The error names where -the policy came from and what is wrong. +Run `t3 policy settings` to list every manageable path from `settings.json` and its default. -`t3 policy check` catches the same problems in a JSON file. For a profile or registry value, check -the JSON before you convert it. For the Group Policy template, check a complete policy file that -holds the same settings, then paste its `settings` and `limits.providers.instances` objects into the -two JSON policies. A policy written for a newer version can use keys an older one -cannot enforce, so upgrade T3 Code before you deploy a policy that uses them. +- `"locked": false` sets a default (users can override). +- `"locked": true` enforces the value across Settings and project overrides. -## Settings +Key constraints: -Each key under `settings` is a setting's path in the server's `settings.json`, such as -`storageCleanup.logsAfterDays`. Run `t3 policy settings` to list every path a policy can manage, -with its default. - -- `"locked": false` sets a default. It applies wherever the user has not chosen a value of their - own, and users can change it. -- `"locked": true` sets the value. Users and agents cannot change it, in Settings or in a project's - settings, and Settings shows the control as managed by your organization. Removing the policy - brings back the user's own value. - -A few settings need care: - -- A default cannot add an entry, such as a provider instance, because users could never remove it. - Lock the entry instead, or set provider fields with [`providers.instances`](#providers). -- A setting that can be empty, such as `defaultModelSelection`, is managed as a whole. You cannot - manage one field inside it. -- `defaultRuntimeMode` cannot be broader than [`maxRuntimeMode`](#permission-modes). -- `worktreeCleanup`, which projects can also set, overrides the `worktree` rules in - `storageCleanup`. Lock it along with those rules; T3 Code refuses a policy that locks only the - rules. -- `observability` cannot be managed. Its OTLP endpoints come from each user's environment - variables, settings file and desktop startup input, which a policy cannot override. -- Manage `idleCompaction`, not the older `compactIdleThreads`. A Claude instance's own idle - compaction choice still wins over `idleCompaction`. -- A provider instance's fields override each other, so lock `providerInstances.` as a whole, - or pin single fields with [`providers.instances`](#providers). T3 Code refuses a lock on one - field inside an instance. A whole-instance lock covers only that instance; to cover every - instance of a provider, use `providers.instances`. +- Lock `worktreeCleanup` together with `storageCleanup` worktree rules. +- `observability` (OTLP endpoints) cannot be managed by policy. +- Manage `idleCompaction` (not legacy `compactIdleThreads`). +- Lock `providerInstances.` as a whole, or pin per-driver fields under [`limits.providers.instances`](#providers). ## Limits -`limits` restricts what T3 Code may do. Leave a key out to keep T3 Code's normal behavior. - ```json { "schemaVersion": 1, @@ -188,130 +96,38 @@ A few settings need care: ### Permission modes -`maxRuntimeMode` is the broadest [permission mode](./permission-modes.md) any thread may use: -`approval-required` (Supervised), `auto-accept-edits`, `auto`, or `full-access`. It covers threads -that users start, agents start, and scheduled tasks start. A thread already above the limit cannot -run another turn until someone lowers its mode; its queued messages send once that happens. New -threads start at the limit when the user's default is above it. +`maxRuntimeMode` caps all threads (`approval-required`, `auto-accept-edits`, `auto`, or `full-access`). Threads above the cap cannot run until lowered. -With `maxRuntimeMode` set, you own each provider's launch settings: binary path, launch arguments, -config home, and the environment variables set on each provider. They come from -[`providers.instances`](#providers) or T3 Code's defaults, and users cannot change them, because a -wrapper script, a launch flag, or a variable such as `NODE_OPTIONS` could otherwise turn off the -provider's approvals. Pin the variables your users need, such as a gateway URL, in -`providers.instances`. - -Variables in the environment that starts T3 Code itself still reach providers, and a default -binary path such as `claude` is looked up on that environment's `PATH`. The desktop app builds that -environment from settings the user controls, such as their shell profile, so a user could put their -own `claude` earlier on their `PATH`. Pin an absolute `binaryPath` in `providers.instances` for each -provider you allow. - -ACP agents' own mode menus have no effect under `maxRuntimeMode`, except Antigravity's, whose modes -T3 Code can place under the limit. Users still choose which ACP Registry agent runs; leave -`acpRegistry` out of `allowedDrivers` to stop that. - -The limit decides which modes T3 Code asks the provider for. It is not a sandbox; see -[What a policy does not cover](#what-a-policy-does-not-cover). +When `maxRuntimeMode` is set, users cannot modify provider launch settings (`binaryPath`, `launchArgs`, config home, or env vars)—pin required values (including absolute `binaryPath`s so user `PATH` entries can't shadow them) in `providers.instances`. Leave `acpRegistry` out of `allowedDrivers` if you don't want users adding arbitrary ACP Registry agents. ### Clients and T3 Connect -`clients` lists how the server may run: - -- `desktop`: as the desktop app's own server. -- `local-browser`: as a server only browsers on this machine reach, such as `npx t3`. -- `remote`: reachable from phones, other computers, and app.t3.codes over the network. - -`remote` is the line that matters. A server reachable from the network also accepts browsers on -this machine, and the two local kinds differ only in how T3 Code was started. On machines with the -desktop app, keep `desktop` in the list, or the app cannot start. - -Without `remote`, the server listens only on a loopback address, creates no pairing links, and -signs out devices that paired earlier. It does not start with a host other than a loopback -address or `localhost`. A [background service](./background-service.md) installed before -`T3CODE_LAN` existed keeps private-network access, so without `remote` it refuses to start. -Run `t3 up --no-lan` when its `service.env` sets no `T3CODE_HOST`, or set -`T3CODE_HOST=127.0.0.1` in `service.env`, then run `t3 service restart`. The desktop app starts -with network access and Tailscale Serve off, whatever the user chose. That also turns off -T3 Connect. To keep other remote access but turn off T3 Connect alone, set `"connect": false`. - -When it starts, the server also turns off each Tailscale Serve route, HTTPS or TCP, that forwards -to it, such as one `t3 pair --tailscale` set up, and leaves other routes alone. It does not start -while such a route stays on, or while Tailscale's answer cannot be read; the error names the -command that turns the route off. A route whose target is a name, such as `localhost` or another -machine on the same port, also stops it, since a name can resolve to this server; change the route -or T3 Code's port. If Tailscale is installed but does not answer, as on a Mac where it was never set up, the -server does not start until Tailscale is set up or removed. It does start when Tailscale is not -installed, not running, or -logged out, since nothing forwards then; a route Tailscale kept returns when Tailscale runs again, -so restart T3 Code after that. +`clients` allows any subset of `desktop`, `local-browser`, and `remote` (keep `desktop` on desktop machines). + +- Omitting `remote` restricts the server to loopback, revokes paired devices, disables LAN/Tailscale Serve/T3 Connect, and refuses startup if a Tailscale Serve route still forwards to T3 Code (or if a legacy service has LAN enabled—run `t3 up --no-lan`). +- Set `"connect": false` to disable T3 Connect while allowing LAN/Tailscale remote access. ### Other capabilities -- `webhookTasks: false`: scheduled tasks cannot use webhook triggers. Existing webhook tasks stay - but do not run, and cannot be turned back on. Users can still edit or delete them. - Workflow webhooks are refused too. -- `browserCookieImport: false`: users cannot import cookies from another browser into T3 Code's - browser. -- `previewTunnel: false`: other devices cannot load this machine's `localhost` pages themselves. - Browser tabs stream from it instead, and port forwarding and **Open on this device** are - unavailable. This wins over the user's - [Preview tunnel setting](./remote-access.md#browser-on-a-remote-environment). -- `worktreeLayoutCommands: false`: T3 Code does not run the - [worktree layout commands](./multi-repo-projects.md#lay-the-folder-out-yourself) a project's - `t3.json` declares, whether or not a user approved them. Such a project gets no new worktree - threads; existing thread folders are restored as plain checkouts and removed without the - project's `remove` command. -- `telemetry: false`: the server and desktop app send no [product usage data](./telemetry.md) or - relay connection traces, and neither does a browser opened from the server. A policy cannot turn - them on. The hosted web app at app.t3.codes and the mobile app still send their own relay traces. +- `webhookTasks: false`: Disables scheduled-task and workflow webhooks. +- `browserCookieImport: false`: Disables importing cookies from other browsers. +- `previewTunnel: false`: Disables remote `localhost` tunneling and port forwarding (streams tabs instead). +- `worktreeLayoutCommands: false`: Disables `t3.json` `worktreeLayout` `create`/`remove` commands. +- `telemetry: false`: Disables product usage data and relay tracing for the server, desktop app, and server-opened browsers (does not control `app.t3.codes` or mobile). ### Providers -`providers.allowedDrivers` lists the providers that may run, by ID: `codex` (Codex), -`claudeAgent` (Claude), `cursor` (Cursor), `grok` (Grok), `opencode` (OpenCode), `antigravity` -(Antigravity), `fx` (fx), `kiro` (Kiro), `pi` (Pi), `muse` (Muse Code), and `acpRegistry` (ACP -Registry). -`t3 policy check` rejects an ID this version does not know. Threads on other providers stay, -marked unavailable, and users can still turn those providers off. - -`providers.instances` sets fields on every instance of a provider, such as an environment variable -that routes Claude through Amazon Bedrock or a base URL for a company gateway. `binaryPath` and -`launchArgs` work only for providers that have those settings. With `"locked": true`, users cannot -change the fields you set. With `"locked": false`, the fields fill in only what the user left -empty. A `codex` entry that is locked, or any `codex` entry under `maxRuntimeMode`, also rules out -[Connect with ChatGPT](./providers-codex.md#connect-with-chatgpt), since that runtime would skip -your fields. In the same way, an `opencode` entry like that rules out a server URL, so OpenCode -starts the binary you set. +- `providers.allowedDrivers`: Whitelist of driver IDs (`codex`, `claudeAgent`, `cursor`, `grok`, `opencode`, `antigravity`, `fx`, `kiro`, `pi`, `muse`, `acpRegistry`). +- `providers.instances`: Sets or locks (`"locked": true`) fields across all instances of a driver (e.g., Bedrock/gateway env vars, `binaryPath`, `launchArgs`). Locking `codex` (or using `maxRuntimeMode`) disables ChatGPT-managed Codex; locking `opencode` disables external `serverUrl`. ### Updates -- `mode`: `auto` keeps the normal update flow. `off` stops T3 Code from checking for updates, for - machines that get T3 Code through device management. -- `feedUrl`: T3 Code updates from your own mirror instead of GitHub: the desktop app, `t3 update`, - and updates started from another device. Publish only the versions you have approved, laid out - as on a GitHub release. The release's update files (`latest.yml`, `latest-mac.yml`, - `latest-linux.yml`, `latest-linux-arm64.yml`, and their `nightly` versions if you allow nightly) - and the desktop installers they list go at the URL's root. The release's `t3-*` archives and - `SHA256SUMS` go under `v/`. A `t3` run through `npx` comes from npm, so pin it with your - package tooling. -- `allowNightly: false`: the nightly channel is unavailable. +- `mode`: `"auto"` or `"off"` (when updates are managed externally). +- `feedUrl`: Custom update mirror matching GitHub Release layout (`latest*.yml` and installers at root; `t3-*` archives and `SHA256SUMS` under `v/`). +- `allowNightly: false`: Disables the nightly channel. ## What a policy does not cover -The policy controls what T3 Code does. Agents run through each provider's own CLI, which reads its -own configuration, such as `~/.claude`, and which a user can also run outside T3 Code. To restrict -those CLIs, use their own managed configuration, such as Claude Code's managed settings. - -On a managed Windows machine, the desktop app does not run a WSL environment. A T3 Code server a -user starts inside WSL reads `/etc/t3code/policy.json` in that distro, not the Windows policy. -Deploy the policy file there too if your users run T3 Code in WSL. - -Without `remote`, T3 Code does not expose the server, but a user can still forward its local port -with other tools. - -A user with administrator rights on the machine can edit or remove the policy. T3 Code enforces -the policy in its own processes, which run as the user, so it stops users from changing managed -settings in T3 Code but does not stop a user who modifies or replaces T3 Code itself. A version -from before managed policy ignores it too. To control which builds can run, use your device -management tool's application controls. +- **Provider CLIs**: Restrict underlying CLIs with their own managed settings (e.g., Claude Code managed settings). +- **WSL**: Managed Windows desktop disables its WSL environment; a server started manually inside WSL reads `/etc/t3code/policy.json` in that distro. +- **Local admins / port forwarding**: Administrators can modify policies or T3 Code binaries, and users can still port-forward loopback sockets with external tools. Use OS/MDM controls for binary integrity and network isolation. diff --git a/docs/user/mobile-notifications.md b/docs/user/mobile-notifications.md index 992efd5b7b29a..10cc5657b15c1 100644 --- a/docs/user/mobile-notifications.md +++ b/docs/user/mobile-notifications.md @@ -1,15 +1,20 @@ # Mobile notifications -Sign in to T3 Connect, link your environments, and enable **Device Notifications** in **Settings → Notifications** to receive alerts when an agent finishes, fails, needs approval, or asks for input. Tap a notification to open its thread. Your environment must have agent activity publishing enabled. +Get push alerts, Live Activities, and home-screen widgets on iOS and Android when agents finish, fail, or need your approval or input. -Enable **Live Activity Updates** on iOS, **Agent Live Updates** on Android 16 and newer, or **Ongoing Agent Activity** on older Android versions to follow work without opening the app. Finished results remain visible for up to 15 minutes. You can dismiss an Android activity card without disabling alerts; turn off the same switch to stop future cards. +## Prerequisites -For activity without ordinary alerts on Android 8 or newer, leave **Ongoing agent activity** enabled and turn off **Agent alerts** in Android's notification settings for T3 Code. Activity updates continue, and the same card shows the finished result without a separate alert. On Android 16 and newer, the finished result remains a Live Update until dismissed or expired. Keep app-wide notification permission and **Live updates** enabled so Android can display it. +- Sign in to **T3 Connect** on both your phone and host machine (direct/Tailscale connections alone do not deliver background push notifications). +- Enable **Publish agent activity** in **Settings → Sharing & access** on the host. +- Enable **Device Notifications** in **Settings → Notifications** on mobile (Android requires Android 7.0+ and Google Play services). -On iOS you can also add the **Agent Activity** widget to your Home Screen or Lock Screen. It shows the same agents as the Live Activity, using your T3 Connect sign-in. The widget refreshes when you open T3 and shows unfinished work as out of date after 10 minutes. +## Live updates and widgets -Ordinary alerts stay quiet while the mobile app is in the foreground. Ongoing activity continues to update. Viewing a thread on another device does not silence your phone's alerts. +- **Live progress**: Enable **Live Activity Updates** (iOS), **Agent Live Updates** (Android 16+, check **Live Update Settings** if missing), or **Ongoing Agent Activity** (older Android). Finished results stay visible for up to 15 minutes. +- **Silent live updates (Android 8+)**: Keep **Ongoing agent activity** on and disable **Agent alerts** in Android system notification settings. +- **iOS widget**: Add the **Agent Activity** widget to your Home Screen or Lock Screen (refreshes when you open T3; marks unfinished work stale after 10 minutes). -Android notifications require Android 7.0 or newer and Google Play services. Android 16 and newer can promote ongoing activity to a Live Update, subject to system settings and device support. Other devices show a regular ongoing notification. If Live Updates don't appear on Android 16 or newer, check **Live Update Settings** in T3 Code's **Settings → Notifications**. Android 7's battery-saving modes can delay removal of expired cards. +## Notes -Notification permission and Android notification channels are controlled in system Settings. Background delivery requires T3 Connect; a direct or Tailscale connection alone does not enable push notifications. The mobile app does not need to maintain a connection to your environment. Force-stopping the Android app in system Settings prevents push delivery until you open it again. +- Ordinary alerts are muted while the mobile app is in the foreground, though viewing a thread on another device does not silence your phone. +- Force-stopping T3 Code in Android system Settings pauses push delivery until you reopen the app. diff --git a/docs/user/multi-repo-projects.md b/docs/user/multi-repo-projects.md index d58ab4ad3b423..4b8d13ba34a3c 100644 --- a/docs/user/multi-repo-projects.md +++ b/docs/user/multi-repo-projects.md @@ -1,42 +1,19 @@ # Projects with several repositories -A project can cover more than one repository, so one thread can read and change all of them. This -fits three common setups: +A single T3 Code project can span multiple Git repositories so one thread can read and edit all of them. This supports: -- A plain folder that holds several repositories, such as `shop/api` and `shop/web`. -- A repository that works alongside others it depends on, anywhere on the machine. -- A repository with submodules. +- A plain folder containing multiple repositories (e.g. `shop/api` and `shop/web`) +- A repository paired with external sibling repositories anywhere on disk +- A repository with Git submodules -The project folder does not have to be a Git repository itself. +The project folder itself does not need to be a Git repository. -## Which repositories a project covers +## Discovery and configuration -There is no list to keep. A project covers every repository inside its folder: T3 Code looks one -level down, and one level further inside folders that are not repositories themselves, such as -`src` or `packages`. It reads the disk each time, so a repository you clone there is part of the -project straight away, and one you delete is gone from it. Worktrees of another repository are left -out. +T3 Code automatically discovers every Git repository inside the project folder—one level down, plus one level deeper inside non-repo folders (such as `src/` or `packages/`). Cloned or deleted repos update automatically; worktrees of other repos are ignored. View covered repos in **Settings → Projects → Repositories**. -**Settings → Projects → Repositories** shows what the project covers on each machine. - -### Folders outside the project - -A repository somewhere else on the machine has to be added, because adding it lets agents work in a -place they could not reach before. - -- On web and desktop, use **Add folder** under **Repositories**. -- If the project folder has a `.code-workspace` file, the folders it lists outside the project are - offered there with an **Add** button, on mobile too. -- From a script, `t3 project add --track ` adds one. - -**Remove** takes an added folder out of the project. It never deletes files. Added folders are -paths on one machine, so the same project on another machine has its own. A project can cover up to -128 folders. - -### Leave a repository out - -To keep a repository inside the project folder out of the project, name it in the `t3.json` in the -project folder, relative to that folder: +- **Add external folders**: Use **Add folder** in **Settings → Projects → Repositories** (web/desktop), import entries from a `.code-workspace` file (web/desktop/mobile), or run `t3 project add --track `. Added folders are per machine (up to 128 folders per project); removing one never deletes files. +- **Ignore a repository**: Add relative paths to `t3.json` in the project folder (applies on every machine): ```json { @@ -44,64 +21,25 @@ project folder, relative to that folder: } ``` -It is then not reviewed on its own and gets no worktree. Because the file is checked in, the choice -applies on every machine. - -### Submodules - -Submodules are checked out when a worktree is created. If that fails, a submodule stays -uninitialized and the thread does not list it until you run `git submodule update --init` in the -thread's folder. A thread that changes one shows it as its own repository, with its own diff and -Git actions, while the repository that holds it shows the changed pin. A submodule never -gets a worktree of its own, because its parent repository decides where it is checked out. - -## Review changes - -Each turn lists the files it changed, grouped by repository, and its diff covers all of them. See -[Review turn changes](source-control.md#review-turn-changes). +- **Submodules**: Checked out automatically when creating a worktree. If checkout fails, run `git submodule update --init` in the thread folder. Modified submodules appear as their own repository for diffs and Git actions, while the parent shows the updated pin. -On web and desktop, the Diff pane's **Uncommitted**, **Changes**, and **Commits** sources read one -repository at a time. Pick it from the repository picker next to the source picker. The picker -lists every repository the thread reaches, including ones no turn has touched, so edits you made by -hand show up too. +## Review, commit, and open pull requests -## Commit, push, and open pull requests - -Git actions run in one repository at a time. - -- **Web and desktop:** the thread details panel lists the repositories the thread changed, most - recent first, each with its branch and uncommitted changes. Expand one to commit, push, or open a - pull request there. **Other repositories...** adds any other repository of the project. -- **Mobile:** open **Git controls** in the thread. The sheet lists the repositories under - **Repositories**; tap one for its own commit, push, and pull request actions. - -A pull request opened in a repository is linked to the thread under that repository, not under the -project's. +- **Turn diffs**: Each turn groups changed files by repository. In the Diff pane (web/desktop), **Uncommitted**, **Changes**, and **Commits** read one repository at a time via the repository picker. See [Review turn changes](./source-control.md#review-turn-changes). +- **Git actions**: Commit, push, and PR actions run per repository—expand a repository in the thread details panel (web/desktop) or open **Git controls** (mobile). Use **Other repositories…** to include untouched repos. PRs link under their own repository. ## Worktree threads -**New worktree** works for these projects too. The thread gets its own folder laid out like the -project, and each repository you choose gets a worktree there, all on the thread's branch. - -Choose the repositories with the repositories control next to the workspace picker before you send. -Every repository is included when the project covers eight or fewer; with more, none is -included until you choose. A repository with no commit yet is left out, since it has nothing to -branch from. On web and desktop, your last choice is remembered for the project in -that browser. To bring another repository into a running thread, pick it under **Other -repositories** in the thread details panel or the mobile Git sheet. - -Each repository starts from the thread's base branch where it has a branch of that name, and from -its own default branch otherwise. A plain folder has no branch picker, so on web and desktop you -name the base branch at the bottom of the repositories control. +**New worktree** creates a thread folder matching the project layout, giving each selected repository its own worktree on the thread's branch. -In a plain folder, the files outside your repositories are shared links to the originals, not -copies. Editing one changes it for every thread. +- Choose repositories from the repositories control next to the workspace picker before sending (all repos are selected by default when there are 8 or fewer; none when more; repos with no commits are excluded). +- Add more repositories to a running thread from **Other repositories…** (web/desktop) or the mobile Git sheet. +- Each repository branches from the thread's base branch if it has one, otherwise its own default branch. +- In a plain project folder, files outside repositories are linked (shared) rather than copied—editing them affects all threads. -### Lay the folder out yourself +### Custom worktree layout -If the default layout does not suit your project, for example because build output must be per -thread, workspace metadata has to be generated, or submodules need preparing, the project can -create the folder with its own command. Add this to the `t3.json` in the project folder: +For custom workspace generation (e.g., per-thread build dirs or submodule setup), declare `worktreeLayout` in the project folder's `t3.json`: ```json { @@ -112,78 +50,24 @@ create the folder with its own command. Add this to the `t3.json` in the project } ``` -`create` runs in the project folder and must leave the thread's copy of the project folder in -place. It receives these environment variables: - -| Variable | Value | -| -------------------------- | ---------------------------------------------------------- | -| `T3_PROJECT_ROOT` | The project folder. | -| `T3_WORKTREE_ROOT` | The empty folder to fill for this thread. | -| `T3_WORKTREE_PROJECT_PATH` | Where the project folder goes inside it. | -| `T3_WORKTREE_BRANCH` | The thread's branch name. | -| `T3_WORKTREE_BASE` | The base branch, or empty when the thread has none. | -| `T3_WORKTREE_REPOSITORIES` | The repositories chosen for the thread, one path per line. | - -Every repository of the project that the command checks out at the same relative place becomes the -thread's checkout of it. `remove` is optional and runs before T3 Code removes whatever is left. - -What the commands can rely on, and what they must do: - -- **Checkouts are linked worktrees on the thread's branch.** Make each one with - `git worktree add` from the repository it belongs to, on `T3_WORKTREE_BRANCH`. T3 Code later - removes, restores, and renames these through Git, so it refuses a clone or a checkout on another - branch and the thread does not start. -- **`create` can run more than once.** It runs again when a thread's folder has gone missing, by - which time the branch already exists. Check the branch out when it is there and create it - otherwise. -- **`remove` can run on a folder that is partly gone**, such as after a failed `create` or an - earlier cleanup. Storage cleanup never deletes files that exist only in the thread's folder, so - `remove` should delete what `create` generated. -- **A failed `create` is rolled back.** Checkouts it already made are removed. -- **One command runs at a time per project**, so a command can update a shared file in the project - folder without its own locking. -- **Each command has ten minutes.** -- **The commands run only for requests that may run commands on the host.** A client paired - without `orchestration:operate` and `terminal:operate`, and a thread started through a - [linked environment](remote-access.md#link-another-environment) paired below full access, get no worktree in a project - that declares a layout, and their cleanup leaves `remove` out. - -#### Approve the commands - -T3 Code runs `create` and `remove` only after you have approved them. The first time you start a -worktree thread in the project from the web or desktop app, it shows both commands in full and asks. -**Approve and continue** records the approval and starts the thread; **Cancel** leaves your draft as -it was. You can also review, approve, and revoke each command under **Worktree layout** in the -project's settings. Approving needs a client that can use the terminal (`terminal:operate`). - -An approval is kept on the environment, not in the repository, and covers the exact text of one -command for one project. When the text in `t3.json` changes, for example after a pull, the command -stops running until you approve the new text. An approval covers the command text only: when the -command runs a script file, later changes to that file do not ask again. - -While a command is not approved: - -- **Nothing that needs `create` gets a worktree.** A worktree thread started from the mobile app, - by a scheduled task, or by an agent fails with a message that says so. Approve the command in the - web or desktop app, then start it again. -- **A thread folder that went missing comes back as plain checkouts**, without the project's - `create`. -- **Removing a thread's worktree skips `remove`** and removes the checkouts. - -Agents never approve a command, and an approval is not enough for one that works below Full access. -When an agent hands its thread off to a worktree or starts a worktree thread, the commands run -only if the thread that asked is in Full access when they are about to run. Below that, or where an -administrator's [policy](managed-policy.md) does not allow Full access, a project that declares a -layout gets no worktree from the agent. In any project, an action set to **Run automatically on worktree -creation** does not run for a worktree an agent asked for below Full access. Start the worktree -thread yourself, or switch the thread to Full access. - -An administrator can turn these commands off for a machine with -[`worktreeLayoutCommands`](managed-policy.md#other-capabilities). - -A project with no other repository can declare a layout too. This example gives each thread -a worktree with its submodules checked out. The command runs in `sh`, and in `cmd.exe` on Windows, -so write it for the shell of the machine the project is on; this one is for `sh`: +`create` runs in the project folder (10-minute timeout, serialized per project) with these environment variables: + +| Variable | Value | +| -------------------------- | --------------------------------------------- | +| `T3_PROJECT_ROOT` | The project folder. | +| `T3_WORKTREE_ROOT` | Empty folder to populate for this thread. | +| `T3_WORKTREE_PROJECT_PATH` | Target path for the project folder inside it. | +| `T3_WORKTREE_BRANCH` | The thread's branch name. | +| `T3_WORKTREE_BASE` | Base branch, or empty if none. | +| `T3_WORKTREE_REPOSITORIES` | Selected repositories, one path per line. | + +Requirements for layout scripts: + +- Create linked worktrees on `T3_WORKTREE_BRANCH` via `git worktree add` (clones or other branches are rejected). +- `create` must be idempotent (if re-run when a folder is missing, check out the existing branch). Failed `create` runs roll back created checkouts. +- `remove` (optional) runs before T3 Code cleans up and should handle partially missing folders and delete generated files. + +Example (`sh`) for a single repo that also initializes submodules: ```json { @@ -193,21 +77,15 @@ so write it for the shell of the machine the project is on; this one is for `sh` } ``` -## Rewind +#### Command approval and security -Rewinding a thread restores its project folder and each repository it works in. Two cases are not -restored: +T3 Code prompts you to approve the exact `create` and `remove` command strings on web/desktop before running them (manage approvals in **Settings → Projects → Worktree layout**; requires `terminal:operate`). Approvals are stored per environment and invalidated if the command string in `t3.json` changes. -- **A plain project folder.** Only repositories have snapshots, so files that sit outside every - repository keep their current contents. -- **A repository with no earlier snapshot.** If nothing was recorded for a repository before the - turns you discard, it keeps their changes. The rewind still completes and names the repositories - it left, so check their uncommitted changes afterwards. +- Unapproved commands block worktree creation from mobile, scheduled tasks, and agents. +- Agents can never approve commands and must be in **Full access** to trigger `worktreeLayout` or worktree-creation setup scripts. +- Administrators can disable layout commands with [`worktreeLayoutCommands`](./managed-policy.md#other-capabilities). -## Limits +## Rewind and limits -- One Git action runs in one repository. There is no commit or push across several at once. -- Only the project folder's `t3.json` is read. Setup scripts and actions inside one of its - repositories are not picked up. -- The Diff pane's repository picker and the base branch field for a plain folder are on web and - desktop only. +- **Rewind**: Restores every repository with an earlier snapshot. Plain-folder files outside repositories and repositories with no earlier snapshot keep their current contents (the rewind reports any skipped repos). +- **Limits**: Git actions run one repository at a time; only the project folder's `t3.json` is read; the Diff pane repository picker and plain-folder base branch field are web/desktop only. diff --git a/docs/user/open-source-licenses.md b/docs/user/open-source-licenses.md index 1324d552c233d..827c9df7749fd 100644 --- a/docs/user/open-source-licenses.md +++ b/docs/user/open-source-licenses.md @@ -1,13 +1,8 @@ # Open source licenses -T3 Code includes third-party software and adapted assets. To read their license and attribution -notices: +View third-party license and attribution notices (including optional on-demand device tools) inside T3 Code: -- On web and desktop, open **Settings → About**, find **Open source licenses** under **Legal**, - and select **View licenses**. -- On mobile, open **Settings → About T3 Code → Open source licenses**. +- **Web and desktop**: **Settings → About → Legal → Open source licenses → View licenses**. +- **Mobile**: **Settings → About T3 Code → Open source licenses**. -The page lists the version when available, license identifier, and the parts of T3 Code that include -or use the item. This also covers optional device tools that T3 Code installs on demand instead of -bundling. Select a row to read the complete notice text. Use the search field to find a package, -version, license, or app component. +Search by package name, version, license, or component, and select any entry to read its full notice. diff --git a/docs/user/outside-agents.md b/docs/user/outside-agents.md index be86ef8b487df..4080792517196 100644 --- a/docs/user/outside-agents.md +++ b/docs/user/outside-agents.md @@ -1,166 +1,48 @@ # Outside agents -Agents that T3 Code did not start can work with an environment through its MCP -server. They can read projects and threads, start and message threads, and -check which providers and models are available. This covers Claude Code or -Codex in your own terminal, ChatGPT, and bots that support MCP. Each agent signs -in once, and you choose what it may do. - -## Add T3 Code to an assistant app - -Open the command palette (`Cmd/Ctrl+K`) and choose **Use T3 Code in another -app (MCP)**, or use the button in **Settings → Sharing & access**. Pick the -app and follow the step for that app. Assistants like -Poke and Claude run in the cloud, so the wizard first asks you to sign in to T3 -Connect and turn it on for the environment. To reach your other machines through -the same connection, turn on **Linked environments** in Labs and -[link them](./remote-access.md#link-another-environment). - -When the app opens the sign-in page, choose what it may do and approve with your -T3 Connect account. On an older environment, the wizard asks for the level and -gives you a code to paste instead. A code works once, for 5 minutes, and -approves only that level. - -For an app that is not listed, choose **Something else…**, add a remote MCP -server with OAuth in that app, and paste the URL. Apps that require their own -client ID cannot connect. - -## Get the MCP URL - -In **Settings → Environments**, open a saved environment's menu and choose -**Copy MCP URL**. The URL is the environment's address followed by `/mcp`, for -example: - -```text -https:///mcp -``` - -When T3 Connect serves the environment, the copied URL is its T3 Connect -address, which agents can reach from anywhere. Otherwise it uses the route this -device is connected over, so an agent on the same device can reach it. - -- **An agent on your own computers** can use `localhost` on the host, T3 - Connect, or any `https` address, such as - [Tailscale HTTPS](./remote-access.md#tailscale-https). Signing in sends the - agent's credentials to the environment, and agents only do that over `https` - or to `localhost`. A plain-`http` LAN or Tailscale address, like - `http://100.x.y.z:3773`, lets an agent find the environment but not finish - signing in. -- **A hosted agent**, such as ChatGPT or a bot running in the cloud, must reach - the environment from the internet. Use the T3 Connect address. A Tailscale - address only works from your own tailnet. - -## Approve a sign-in - -The first time an agent connects, it opens a sign-in page. When the agent -reaches the environment through T3 Connect, the page opens on the T3 Code web -app: sign in with the T3 Connect account the environment is linked to and -approve there, without a code. Otherwise the page opens on the environment. -Either page names the agent and where its access goes: - -- For an agent on your computer, approval returns to a `localhost` address on - the computer that opened the page. -- For a hosted agent, approval goes to that service, such as `chatgpt.com`. - Anyone who runs that service gets the access. - -Only approve a sign-in you just started. On the environment's own page, enter a -code from **Use T3 Code in another app (MCP)**, **Settings → Sharing & access**, -or `t3 auth pairing create` on the host. A browser already signed in to the -environment with permission to manage access can approve without a code. On the -web app, **Use a sign-in code instead** opens the environment's own page. - -A code from **Use T3 Code in another app (MCP)** already carries the level you -picked there. With another code, choose what the agent may do here: **Auto** is -selected by default, or the closest lower mode allowed by your organization’s -policy. Approving without a code starts at **Read only**: - -- **Read only** lets the agent read projects and threads and see - the available providers and models. It cannot change anything. -- **Supervised** through **Full access** also let it start, message and stop - threads in every project. A thread it starts or steers cannot run with more - permissions than the mode you chose. [Workflow runs](workflows.md) choose - their own modes, so only **Full access** (or the highest mode your - organization's policy allows) can start, answer, resume or cancel them, - change what workflows store, or read webhook paths. Lower modes can still - read runs. Some agents have modes of their own that skip approvals; only an - agent with **Full access** can pick one. - -## What outside agents can call - -Some tools only work for an agent running inside a T3 thread, because they act -as that thread: subagents, secret requests, rendered HTML, the browser preview, -devices, and worktree handoff. They still appear in an outside agent's tool -list, but calling one returns an error saying it needs an agent running inside -T3 Code. - -- To hand off work, start a thread with `t3_thread_launch`, then follow it with - `t3_thread_wait` or `t3_thread_read`, instead of `create_threads` or - `delegate_task`. -- Tools that default to the caller's own project or thread need an explicit - `projectId` or `threadId`. -- To list threads across projects, call `t3_thread_list` with - `allProjects: true`, or use `t3_thread_search`. - -## Claude Code +Connect external agents (Claude Code or Codex in your terminal, ChatGPT, or any OAuth-capable MCP client) to your T3 Code environment over MCP to read projects/threads, launch and message threads, and monitor events. -```sh -claude mcp add --transport http t3 https:///mcp -claude mcp login t3 -``` +## Quick setup -`claude mcp login` opens the sign-in page in your browser. On a machine -without a browser, add `--no-browser`, open the printed URL elsewhere, and -paste the final URL back when asked. `claude mcp list` shows `t3` as connected -once you approve. +Open the command palette (`Cmd/Ctrl+K`) and run **Use T3 Code in another app (MCP)** (or open **Settings → Sharing & access**), pick your app, and follow the prompts. -## Codex +- Cloud assistants (like ChatGPT or Claude) require **T3 Connect** enabled on the environment. +- To also reach other machines through the same connection, enable **Settings → Labs → Linked environments** and [link them](./remote-access.md#link-another-environment). +- To copy the raw MCP endpoint (`https:///mcp`), open an environment's menu in **Settings → Environments → Copy MCP URL**. OAuth requires `https://` or `localhost` (plain `http://` LAN/Tailscale addresses cannot complete OAuth). -```sh -codex mcp add t3 --url https:///mcp -codex mcp login t3 -``` +### CLI clients and ChatGPT -`codex mcp login --no-browser` prints the sign-in URL instead of opening it. -`codex mcp list` shows `t3` with OAuth once you approve. +- **Claude Code**: + ```sh + claude mcp add --transport http t3 https:///mcp + claude mcp login t3 # add --no-browser on headless hosts + ``` +- **Codex**: + ```sh + codex mcp add t3 --url https:///mcp + codex mcp login t3 # add --no-browser on headless hosts + ``` +- **ChatGPT / other OAuth MCP clients**: Add a custom remote MCP server pointing to `https:///mcp` with **OAuth** authentication (no client ID or secret needed). -## ChatGPT +## Approve access and permissions -Add the environment as a custom MCP app in ChatGPT's apps settings: +The first time an outside agent connects, approve its sign-in page (via your T3 Connect account, an already-authorized browser, or a one-time pairing code from **Settings → Sharing & access** / `t3 auth pairing create`). -1. Create a new app or plugin with a custom MCP server. -2. Set the server URL to `https:///mcp`, using the T3 - Connect address. -3. Choose **OAuth** for authentication. ChatGPT discovers the rest; you do not - need a client ID or secret. -4. Create the app, then approve the sign-in page that opens. +- **Read only**: Inspect projects, threads, providers, and models. +- **Supervised → Full access**: Also launch, message, and stop threads up to the granted permission mode. Managing [workflow runs](./workflows.md) or using approval-skipping agent modes requires **Full access** (or your policy's maximum mode). +- Sign-ins last **30 days**; revoke anytime in **Settings → Sharing & access**. -## Other agents and bots +## Available tools and limits -Any agent that supports remote MCP servers over HTTP with OAuth can connect. Give -it the MCP URL and choose OAuth, and the agent finds the sign-in settings itself. -Agents without OAuth support cannot connect. +Tools that act as a running T3 thread (`delegate_task`, `create_threads`, `request_secret`, `html_render`, `preview_*`, `device_*`, `t3_worktree_handoff`) only work for agents running **inside** T3 Code. -A bot that supports MCP Events (`io.modelcontextprotocol/events`) can learn -when something happens without reading threads over and over: a turn ended, an -agent waits on a person, a guest asked something, a watched pull request woke -its thread. [Workflow runs](workflows.md) are events too: a run started, paused, -resumed or ended, or waits on a person. A bot can poll, stream, or receive each -event type by webhook, narrowed to projects and threads or to workflows and -runs; runs another run started are left out unless asked for, as subagent -threads are, and narrowing thread events to a run picks out its agent steps. -The environment keeps its latest 1,000 milestones in memory, so a bot that was -away longer, or reconnects after a restart, is told some may be missing and -should reread what it cares about. Webhooks go only to public `https` addresses, -a subscription lasts at most an hour before the bot must renew it, and signing -the bot out ends its subscriptions. To test with a receiver on your own machine -or network, start the environment with `T3CODE_MCP_WEBHOOK_ALLOWED_HOSTS` set to -its host names, for example `localhost,127.0.0.1`; those hosts may also use -plain `http`. +- Use `t3_thread_launch` + `t3_thread_wait` / `t3_thread_read` to run and follow work. +- Pass `projectId` or `threadId` explicitly (or `allProjects: true` on `t3_thread_list`). +- **MCP Events (`io.modelcontextprotocol/events`)**: Bots can poll, stream, or subscribe via HTTPS webhooks (up to 1-hour leases; latest 1,000 milestones buffered in memory) for turn, approval, guest, PR watch, and workflow events. For local webhook testing, set `T3CODE_MCP_WEBHOOK_ALLOWED_HOSTS=localhost,127.0.0.1` on the server. -## Scripts on the host +## Host scripts (`t3 thread`) -On the machine that runs the environment, `t3 thread` uses the same tools -without a sign-in: +On the server machine itself, drive threads directly without OAuth: ```sh id=$(t3 thread start . "Find why the tests are slow") @@ -169,26 +51,5 @@ t3 thread show "$id" t3 thread list ``` -`.` means the project that contains the current folder, or a git worktree of -its repository; a project id also works. A new thread uses the project's -default model and permission mode, and runs in the project folder unless you -pass `--worktree `. Its title is the message's first line, or -`--title`; add `--generate-title` to have it named from the message, as threads -started in the app are. `send` never interrupts: a busy thread gets the message -as its next turn. Pass `-` as the message to read it from stdin. - -To choose the model, pass `--provider --model `. Add -`--option id=value` for each model option. For reasoning effort, Codex uses -`--option reasoningEffort=high`, while Claude uses `--option effort=high`. -Option ids and allowed values depend on the provider and model; use those -reported by `orchestrator_capabilities`. `true` and `false` set on/off options. - -`--wait` prints the agent's reply. It exits 1 when the run fails or stops, and -2 when the agent waits for an answer you give in the app. Add `--json` for a -result that always includes the thread id. - -## Remove an agent - -Approved agents appear under **Settings → Sharing & access** like other clients. -Revoke one there to cut off its access immediately. A sign-in lasts 30 days; -after that the agent asks you to approve it again. +- Pass `--worktree `, `--title` / `--generate-title`, `--provider --model `, `--option id=value` (e.g. `reasoningEffort=high` for Codex, `effort=high` for Claude), or `-` to read the prompt from stdin. +- `--wait` prints the reply and exits `1` on failure/stop or `2` when waiting for user input. Add `--json` for structured output including the thread ID. diff --git a/docs/user/permission-modes.md b/docs/user/permission-modes.md index 3078f16dbdbee..aaf6870f76627 100644 --- a/docs/user/permission-modes.md +++ b/docs/user/permission-modes.md @@ -1,93 +1,37 @@ # Permission modes -Permission modes control when an agent needs your approval to act. Choose a mode in the message -composer; it applies to that thread. A new thread names its mode under the composer. In a thread -on your default mode, open the model picker and choose **Permissions** at its bottom, or press -`mod+shift+a`. A thread on another mode shows the mode next to the model. +Permission modes control when an agent must ask for your approval before running commands or editing files. Set the mode per thread from the composer (`mod+shift+a` or the model picker's **Permissions** menu). -Set the default for new threads in **Settings → Threads → New threads → Permissions**. -Projects can override the environment default. New threads use this setting rather than the -mode of the thread you were viewing. The initial default is **Full access**; existing threads -and modes you choose in a draft keep their permissions. +Configure the default for new threads in **Settings → Threads → New threads → Permissions** (default: **Full access**; projects can override). Administrators can cap available modes with a [managed policy](./managed-policy.md#permission-modes). -| Mode | Behavior | -| --------------------- | ------------------------------------------------------------------------------------- | -| **Supervised** | Requests approval for commands and file changes. | -| **Auto-accept edits** | Approves file edits automatically; other actions can still require approval. | -| **Auto** | Uses the provider's automatic review to approve routine actions and ask about others. | -| **Full access** | Allows commands and edits without approval prompts. | +| Mode | Behavior | +| --------------------- | ----------------------------------------------------------------------------------------- | +| **Supervised** | Requests approval for commands and file changes. | +| **Auto-accept edits** | Approves file edits automatically; commands and other actions may still ask. | +| **Auto** | Uses the provider's automatic review to approve routine actions and ask about risky ones. | +| **Full access** | Runs commands and edits without approval prompts. | -An administrator can cap the modes available on a machine with a -[managed policy](./managed-policy.md#permission-modes); modes above the cap show who manages them. +Permission modes never stop an agent from asking clarifying questions. Subagent approval requests appear in the parent conversation with the subagent's name so you can approve without switching threads. -When an agent below **Full access** opens a pull request with T3 Code's own pull request tool and -the push would run one of the repository's Git hooks (`pre-push` or `reference-transaction`, as a -project with husky has), T3 Code asks you first. The request names the branch and the hooks: the -hook files, and any hook set up in Git's configuration (`hook..command`, which Git 2.54 and -later run). **Approve** pushes and runs them; **Decline** pushes nothing. You are asked each -time: there is no "always allow" for this request, and Plan mode asks too. An approval covers the -contents of the files and the commands it names: if one of them changes, you are asked again. A -change made in the moment between T3 Code's last look and Git starting the hook is not caught. -With husky 9 and Vite+ that is the hook's script, such as `.husky/pre-push`, along with the two -files they generate to start it. It does not cover what those go on to run or read, such as a -package script or another file a hook sources (`.husky/_/husky.sh` with husky 8), so a change -there is not asked about. A push that would run no hook is not asked about. An agent -whose provider cannot show the request pushes without running the hooks and is told so. -With Claude and Codex the push waits for your answer in T3 Code itself; with any other client -that asks you by itself, T3 Code goes by the answer that client sends. +## Git push hooks below Full access -This request is for that tool only. An agent that runs `git push` or a command such as -`gh pr create` itself, in its own shell, goes through its provider's approval for commands as the -table above describes, and the repository's hooks run with that command. +When an agent below **Full access** opens a PR using T3 Code's built-in pull request tool and the push would execute local Git hooks (`pre-push`, `reference-transaction`, or `hook..command`), T3 Code prompts you every time—naming the branch and hook files/commands—before pushing. -Approve or reject requests in the conversation to let the agent continue. Permission modes do -not prevent the agent from asking questions about the task. Subagent approval requests appear in -the parent conversation with the subagent's name, so you can respond without switching threads. +- Declining cancels the push. There is no "always allow" option, and Plan mode prompts too. +- Providers that can't show this prompt push without running hooks and inform the agent. +- Direct shell commands (`git push`, `gh pr create`) follow the provider's normal command approval rules instead. ## Provider differences -Providers enforce permissions differently. Some read-only actions can proceed in **Supervised**. -**Auto** uses automatic review on Codex, Claude, Cursor, Grok, Antigravity, and fx; providers without -an equivalent, including OpenCode, fall back to asking. On Grok and Antigravity, actions their review -does not approve come to you for approval. On fx, prompts it still sends also come to you. +Providers enforce permissions differently, and some read-only actions proceed even in **Supervised**: -Antigravity offers **Auto** only when your Antigravity sign-in provides its Auto mode; some accounts, -including some personal Google accounts, do not. Without it, an Antigravity thread already set to -**Auto** runs in **Supervised**. +- **Auto mode**: Supported by Codex, Claude, Cursor, Grok, Antigravity (account-dependent; falls back to Supervised if unavailable), and fx. Providers without an equivalent (including OpenCode) fall back to asking. +- **Claude**: In **Auto**, asks about actions its review leaves open (unavailable if disabled in Claude settings or by the model). In **Full access**, Claude's own settings can still require approval or block dangerous removals. While an approval is pending, typing a reply declines it with feedback directly to that agent or subagent. +- **Codex**: In **Full access**, skips dangerous-command prompts, though managed network restrictions can still prompt unless commands were allowed for the session. +- **Grok**: No **Auto-accept edits** (falls back to Supervised). File approvals offer session-wide allow; command approvals do not. +- **fx**: No **Auto-accept edits**; **Full access** requires fx 0.0.14+ (otherwise falls back to Supervised). +- **Muse Code & Kiro**: Only **Supervised** and **Full access** (other modes fall back to Supervised). In Supervised, Kiro also asks you to review turn file changes; see [Kiro](./providers-kiro.md#permission-modes). +- **Antigravity**: May still send native approval prompts in **Full access**. +- **ACP Registry agents**: T3 Code answers their approval requests according to the selected mode; see [ACP Registry permissions](./providers-acp.md#permissions-and-terminals). -Muse Code offers only **Supervised** and **Full access**. A Muse thread already set to another mode -runs in **Supervised**. - -T3 Code offers no **Auto-accept edits** for fx, and **Full access** only with fx 0.0.14 or later. An fx -thread set to a mode its fx lacks runs in **Supervised**. - -Grok offers no **Auto-accept edits**. A Grok thread already set to it runs in **Supervised**. Grok -file-change approvals offer **Allow all edits this session**. Its command approvals have no -session-wide choice, because Grok would remember that command for the whole project. - -ACP Registry agents run their own tools in their own mode; T3 Code answers their approval requests -by the permission mode. See [ACP Registry permissions](./providers-acp.md#permissions-and-terminals). - -In **Full access**, commands that Codex's dangerous-command check would ask about run without -asking. Codex still asks before network access its managed network settings don't allow, unless -you already allowed commands for the session. - -In **Auto**, Claude asks you about the actions its review leaves open. Where Claude's settings turn -its Auto mode off, the permissions menu shows **Auto** as unavailable for that project, with whose -settings do it. A Claude thread that is set to **Auto** anyway, or whose model has no Auto mode, -asks like **Supervised** and says so once in the thread. - -Claude can still ask in **Full access** when its settings disable bypass permissions or require -approval for an action. Dangerous-removal safety checks in bypass mode reject the command with -the original warning. Claude can use a safe rewrite when the warning supplies one; otherwise it -continues without the removal and tells you what it skipped. -While a Claude approval is pending, type a text reply to decline that request and give feedback -directly to the agent that asked, including a subagent. Other pending requests stay unanswered. - -Antigravity can still send native approval requests in **Full access**. It only offers remembered -approvals for actions that support them. - -Kiro offers only **Supervised** and **Full access**. In **Supervised** Kiro also asks you to -review a turn's file changes. See [Kiro permissions](./providers-kiro.md#permission-modes). - -See the [provider guides](./install.md#providers) for setup and provider-specific limits. +See the [provider guides](./install.md#providers) for provider-specific setup and limits. diff --git a/docs/user/portable-handoffs.md b/docs/user/portable-handoffs.md index 04b2a8ce14987..56a660dc85166 100644 --- a/docs/user/portable-handoffs.md +++ b/docs/user/portable-handoffs.md @@ -1,48 +1,20 @@ # Context in portable handoffs -T3 Code transfers conversation context when you switch providers, continue through a portable -restart, or use a fork that the provider cannot resume itself. +When you switch providers mid-thread, continue after a portable restart, or fork a thread the provider cannot resume natively, T3 Code transfers a budgeted selection of conversation history to the new provider session. -Short conversations transfer intact. For longer conversations, T3 Code favors recent requests and -answers, the original request, and relevant activity such as command outcomes. Selected messages -keep their full text, order, and user or assistant role, including partial work from failed or -interrupted turns. Your new request stays separate and is never shortened to make history fit. +## What transfers -Codex receives historical messages directly when its installed version supports that operation. -Other providers receive the same selection as attributed conversation context. A handoff does not -copy the outgoing provider's reasoning, tool-call state, or attachments. +- Short conversations transfer intact. +- Longer conversations prioritize the original request, recent user/assistant turns (including partial work from interrupted turns), and key activity like command outcomes. +- Your new prompt is never shortened to make history fit. +- Codex receives historical messages directly when supported; other providers receive attributed conversation context. +- Reasoning traces, raw tool-call state, and attachments are not copied. +- Omitted history is referenced so the agent can retrieve saved messages on demand using T3 Code's thread-reading tool. Still, repeat any critical constraint in your next message if you want to be sure. -The handoff includes references to omitted history. The agent can use T3 Code's thread-reading tool -to retrieve saved messages and activity, including the remainder of a long item. For an important -constraint, you can still repeat it in your next message. A handoff is a budgeted selection, not an -agent-written summary. +## Context limits and configuration -## Context limits +If the target session doesn't have enough context room, T3 Code automatically starts a fresh provider session with a bounded history selection and sends your request—no manual `/compact` needed. If your request and attachments alone exceed the model's window, shorten the message or choose a larger-context model. -A handoff must leave room for existing provider context, your request and attachments, instructions, -tools, and subsequent work. If the target conversation has no room for the handoff, T3 Code starts -a fresh provider conversation with a bounded selection of saved history and sends your request -automatically. You do not need to compact manually. If the request and attachments leave too little -room even in a fresh conversation, shorten the request or select a larger-context model. T3 Code -never shortens your request to make it fit. - -Recovery leaves running background work intact. Let it finish or stop it before retrying the handoff. - -Server operators can set `T3CODE_CONTEXT_HANDOFF_TOKEN_CAP` to change the initial history allowance -(default 16,000; clamped to 1,024–64,000). This is an upper bound, not a provider context-window -guarantee. Text accounting conservatively charges one token per UTF-8 byte, including attribution -and JSON escaping. Imported history has a separate 64,000-byte ceiling; your current input and -attachment payloads do not consume that ceiling. - -T3 Code uses available capacity information for your selected model and options, together with -provider context telemetry. Starting a fresh provider conversation clears prior usage, while keeping -known model capacity. Changing models or context-window options discards stale usage and compaction -thresholds. - -When no capacity information is available, T3 Code assumes a 128,000-token window. It reserves at -least 16,000 tokens, or a quarter of the window when larger, for instructions, tools, and subsequent -work. Images reserve an estimated 8,192 tokens each, independent of their file size; other -attachments reserve 4,096 each for their references. Existing context is estimated from saved -activity when usage telemetry is unavailable. Known smaller windows still constrain the handoff. -These are fallback estimates, not exact token counts. Image resolution, custom models, and hidden -native context can differ, so the provider may still reject an input. +- **History budget**: Operators can set `T3CODE_CONTEXT_HANDOFF_TOKEN_CAP` (default `16000`, range `1024`–`64000`) to adjust the initial history allowance. Imported history has a separate 64,000-byte ceiling. +- **Fallback estimates**: When a model doesn't report capacity, T3 Code assumes a 128,000-token window, reserves at least 16,000 tokens (or 25%) for instructions/tools/work, and conservatively estimates 1 token per UTF-8 byte, 8,192 tokens per image, and 4,096 tokens per other attachment. +- Running background work stays intact during recovery—let it finish or stop it before retrying a handoff. diff --git a/docs/user/project-settings.md b/docs/user/project-settings.md index 9b907dcd0a90d..96f648470a053 100644 --- a/docs/user/project-settings.md +++ b/docs/user/project-settings.md @@ -1,305 +1,69 @@ # Settings and project overrides -On web and desktop, the "Applying settings for …" sentence at the top of Settings pages picks -the project and environment a change applies to. Pages that only hold device preferences, such as -Appearance, don't show it. They start at **All projects** and **All environments** -and stay selected as you move between categories or search for a setting. +T3 Code separates **device preferences** (saved locally per browser/device, like Appearance and Confirmations) from **server settings** (stored on each environment, like Threads, Worktrees, and Source control). -Preferences saved on this device, such as appearance, confirmations and browser profiles, ignore -the environment selection. On the Browser and Labs pages they are read-only while a project is -selected, though browser profiles can still be added, renamed and removed. Everything else is -stored on a server. Choose one environment to edit its settings, or leave **All environments** to -edit every connected environment at once. Offline environments keep their current values; this is a -bulk edit, not a synced global default. +## Scope and inheritance -Choose a project to override settings for it on the selected environments. A layers icon beside -each server row's title shows where the value comes from: the built-in default, the environment, -or a project override. Click it to see that chain on every selected environment. An override can -be reset to inherit again. Settings that cannot be overridden by a project are shown read-only -while a project is selected. +Use the **"Applying settings for …"** selector at the top of Settings (web/desktop) or the header filter (mobile) to choose which **environment(s)** and **project** you are editing: -When the selected environments disagree, the control shows **Mixed** in place of a value and the -layers icon turns amber. Picking a value applies it to every selected environment. - -Changing an environment value never touches a project's own override. When projects override the -setting you are editing, the layers icon counts them and the chain lists each one with its value: -click a project to jump to it, or **Reset all** to make those projects follow the environment -again. - -Providers and diagnostics are per machine: they show one environment at a time, the primary -one until you pick another. Every other setting fans out to the selection. - -With a project selected, a provider's switch in **Settings → Providers** turns it on or off for -that project only, in either direction: a provider off on the machine can be used in one project, -and one on everywhere can be kept out of another. That project's model pickers follow the switch, -and no new turn there can start on a provider it turned off, including queued messages and -follow-ups from delegated tasks. A turn already running when the switch flips finishes. A delegated -task's result still lands in its parent thread, which sees it on its next turn. Reset returns the project to the -machine's setting. Every other provider setting stays per machine. - -On mobile, open **Settings** and use the filter in its header to choose connected environments -and a project. The filter stays available in server-setting pages. With **All projects** selected, -the server-setting pages, such as Threads, Source control & issues and Worktrees, edit the selected -environments' defaults. Choosing a project edits its overrides on the selected -environments. Use **Use defaults** in a page to remove that page's project overrides. -Open **Settings → Projects** to rename the project across its selected -connected checkouts and see where those checkouts live. -Settings that are environment-wide stay read-only while a project is selected. When selected -targets disagree, a control shows **Mixed** until you choose one value. Appearance, keyboard, -and other phone-only settings ignore the filter. - -## Projects with several repositories - -A project covers every repository inside its folder, and any folder you add under **Settings → -Projects → Repositories**; see [Projects with several repositories](multi-repo-projects.md). +- **All environments**: Bulk-edits every currently connected environment (offline environments keep their values). Controls show **Mixed** where environments disagree. +- **Project scope**: Creates a project override for that setting without changing environment defaults. Settings that cannot be overridden appear read-only. +- **Inheritance order**: `Project override` → `Environment setting` → `t3.json` in the repo → `Built-in default`. Leave a setting on **Inherit** to defer to the next tier. +- Click the **layers icon** beside a server setting to inspect its inheritance chain, jump to overriding projects, or **Reset all** back to the environment default. +- **Per-project providers**: With a project selected in **Settings → Providers**, toggling a provider enables or disables it for that project only (in either direction). Running turns finish; no new turns start on a disabled provider. ## Pin and archive projects -Pinned projects come first in the project pickers: the project picker on a new thread, the -new-thread list, the command palette, the sidebar project filter, and mobile. In the boring sidebar, pinned projects get the top -folders, even with no active threads. Pin or unpin a project from its row in any of those lists, -or press the thread pin shortcut (`mod+shift+p` by default) on the highlighted row. **Pin -project** in the command palette and **Settings → Projects** work too. A list keeps its order -while it is open, so a new pin moves up the next time you open it. - -Archive a project you are done with in **Settings → Projects**. It leaves the project pickers. -Its threads, settings, and files stay as they are, and archived projects still show in the -Settings project list, marked **Archived**. Choose one there and select **Unarchive** to bring it -back. On mobile, both are in **Settings → Projects → Organize**. - -A project on several machines must have every machine connected to pin or archive it. - -## Worktree branch names - -In **Settings → Worktrees → Worktree branch naming**, choose a static prefix, -a model-selected semantic prefix such as `feat/` or `fix/`, or custom instructions -for the complete name. The static prefix defaults to `t3/`; a trailing slash is -optional, and an empty prefix adds nothing. Invalid characters in a static prefix -are replaced with hyphens. Custom instructions are appended to -the naming prompt and can specify issue IDs, namespaces, and casing. - -These settings apply to automatically named new worktree branches. Select a project -to override its environment defaults. Worktree directories keep their original names. -If generation fails, or a custom name is invalid or already taken, the temporary -branch name remains. - -## Scheduled tasks on mobile - -Open **Settings → Scheduled tasks** to create scheduled tasks or manage existing -ones across your connected environments. Use the settings filter to narrow the -list by environment or project. Each task runs on the environment you choose, -using its project, model, and workspace settings. Fixed-time schedules use that -environment's time zone, which may differ from your phone's. Choose **Once** -to run a task a single time at a date and time in your own time zone. If the -environment is offline then, the task runs when it is back. - -Under **Destination**, choose where runs go. **New thread each run** keeps every -run separate. The two one-thread choices start a thread on the first run and post -later runs there: one continues the same conversation, the other starts each run -in a fresh session that doesn't see earlier runs, so the thread stays readable -without the agent's context growing. To move a one-thread task, pick another -thread in its project under **Destination**. Moving such a task to another -project starts a new thread there on its next run. - -Deleting a thread also deletes tasks that post into that thread. Tasks that start -a new thread on each run survive deletion of their previous threads. -An archived thread refuses messages, so a task that posts into one stays on and fails -each run until you unarchive the thread or pick another destination. To set a task's thread -aside without breaking it, settle the thread; see [Settle or archive](thread-sidebar.md#settle-or-archive). - -You can edit, pause, resume, run immediately, or delete a task from the list. -Webhook tasks only run when their URL is called, so they can't be run -immediately. -Leaving an edited form asks before discarding unsaved changes. - -## Webhook automations - -In **Settings → Scheduled tasks**, choose **On webhook** -as a task's schedule to run it whenever another service calls its URL, such as -GitHub on a new pull request or a CI job that failed. A public URL needs a -[T3 Connect](remote-access.md) managed tunnel; after you save the task, copy -its URL from the editor. Without one, the editor shows only the URL's path. -**Rotate** replaces the URL and the old one stops working. - -The prompt decides what the agent sees. Placeholders pull values out of the -request: `{{body.path}}` for a JSON or form field, `{{headers.name}}`, -`{{query.name}}`, `{{body}}` for the raw body, and `{{request}}` for everything. -For example, `Review this PR: {{body.pull_request.html_url}}` sends only the -pull request link. A placeholder with no value is left empty. +- **Pin**: Pinned projects sort first in project pickers, the command palette, the sidebar filter, and mobile (`mod+shift+p` on a highlighted row, or **Settings → Projects**). +- **Archive**: Archive finished projects in **Settings → Projects** (mobile: **Settings → Projects → Organize**). Archived projects leave pickers while keeping their threads, settings, and files; unarchive anytime from Settings. +- Pinning or archiving a project that exists on multiple machines requires all of those machines to be connected. -Each value reaches the agent wrapped in `` tags and marked as -untrusted request data. This helps the agent tell it apart from your -instructions, but it doesn't guarantee the agent ignores what the text says. -Inside a value, every `$`, other currency sign and `@`, and a `/` that starts -a lone word, gets an invisible character after it, so mentions like `$skill`, -`@file` and `/command` don't act. Text copied from a value, such as an email -address or a command, carries that character too. Without a signature, anyone -with the URL can start a run with any content. A signature only proves which -service sent the request: a GitHub payload still carries text written by any -GitHub user. +## Project icons and multi-repo projects -For GitHub, turn on **Require signature**, keep the header -`x-hub-signature-256`, hex encoding and the `sha256=` prefix, and enter the -same secret in the repository's webhook settings with content type -`application/json`. Requests without a valid signature are rejected. Set this -up on desktop or web; mobile keeps an existing signature check but can't turn -one on. +- **Icons**: In **Settings → Projects**, set an icon, emoji, monogram, or image (applies across checkouts). Without one, T3 Code generates a two-character monogram (or single CJK character) from the project name. +- **Multiple repositories**: See [Projects with several repositories](./multi-repo-projects.md). -To run only for some requests, add **Filters**. Each one tests a value named -like a placeholder, without the braces, such as `headers.x-github-event` equals -`pull_request` or `body.action` is one of `opened, reopened`. A task runs only -when every filter matches; other requests are answered normally, logged as -**Filtered** with the first filter that failed, and start nothing. Values -compare as text, and a value that is an object or a list only passes -**exists**. Separate **is one of** values with commas; a value can't contain -a comma or start or end with a space. +## Worktree settings -To suppress repeated deliveries, set a **Duplicate request key** template, such as -`{{headers.delivery-id}}`. The same key is ignored for seven days per task. -To combine a burst, set a **Coalesce key**, such as `{{body.id}}`, and a window -of 10–3600 seconds (120 by default). One run uses the latest body, headers, -and query when the window from the first delivery closes; later requests -do not extend it. Pending windows survive a server restart. Keys must contain -request placeholders; if any placeholder is missing, or the render is empty, -that key's rule is skipped. Clear the templates to turn dedupe off. +Configure worktrees in **Settings → Worktrees** (environment default or project override): -Duplicate and coalesced log entries share a limit of 10 per task per minute. -Additional deliveries are accepted without a log entry, and coalesced deliveries -always replace the persisted payload. Coalesced updates count toward a separate -60-per-minute validation limit; exceeding it receives HTTP 429. +- **Branch naming**: Choose a static prefix (default `t3/`), model-selected semantic prefix (`feat/`, `fix/`), or custom instructions. Falls back to the temporary branch name if generation fails or collides. +- **Submodules** (under Advanced): Defaults to recursive checkout; set to **Top level only** or **Skip** (or `"worktreeSubmodules"` in `t3.json`) for repos with heavy nested submodules. +- **Sparse checkout**: Set `"worktreeSparsePatternsPath"` in `t3.json` to a repo-relative file of Git sparse-checkout patterns (non-cone syntax; requires Git 2.35+; enables `extensions.worktreeConfig`). Set Submodules to **Skip** if you don't want submodules initialized under excluded paths. +- **Worktree location** (per machine): Set an absolute path (e.g. `D:\worktrees` or `~/worktrees`) to store new worktrees elsewhere. Existing worktrees stay where they are; cleanup covers both folders. +- **Fast worktree checkout (macOS beta)**: Enable **Settings → Labs → Fast worktree checkout** (Git 2.42+) to clone new worktrees via APFS copy-on-write from a local cache. Falls back to normal checkout for cross-drive paths, sparse checkouts, or Git LFS/filter repos. -On desktop and web, pick **Deliveries** from a task's menu to see recent -requests and the prompt each one produced. +### Storage cleanup -If the environment is offline, the sender gets an error and nothing runs; -redeliver from the sender, such as GitHub's **Recent Deliveries**, once it is -back. To have T3 Connect keep requests instead, turn on **Hold webhooks while -offline** in **Settings → Sharing & access**. T3 Connect then stores requests to a -T3 Connect URL for up to 24 hours and delivers them when the environment -returns. Leave it off if you don't want request bodies stored outside your -machine. To skip requests that waited too long, set **Skip requests older -than** on the task. +Enable automatic cleanup in **Settings → Worktrees → Cleanup** (off by default; runs on startup, on change, and hourly). Projects can set **Automatic worktree cleanup** to **Inherit**, **Off**, or **Custom**. -## Defaults and inheritance +- **Triggers**: Inactive days, days after settlement (`0` = next cleanup), merged PRs (including GitHub squash/rebase merges into the default branch), or settled/archived threads with no commits beyond the default branch. +- **Safety**: Active sessions and shared worktrees are never removed. **Keep worktrees with local changes** defaults to **Uncommitted changes** (protects tracked edits and untracked files; removes ignored files like `.env`/build output). Choose **Any local files** (also protects ignored files except `node_modules`) or **Edited tracked files** (protects tracked edits only). +- **Delete with deleted threads**: Enable **Delete worktrees with deleted threads** to automatically clean up safe worktrees once their last thread is deleted. +- **Scratch folders**: Inactive and settled rules also apply to [no-project scratch folders](./thread-sidebar.md#start-without-a-project) (skipped if they contain a Git repo or enabled scheduled task). Because scratch files aren't in Git, deleted files cannot be recovered. +- **Manual run**: Click **Delete now** to run rules immediately and inspect what was removed, kept, or orphaned (untracked folders are listed but never auto-deleted). +- **Captures and logs**: Browser captures and rotated logs have separate machine-wide retention periods. -Threads contains the model and workspace for new threads. Browser controls agent browser -access. Source control & issues contains automatic pull, the default pull request merge method and text -generation. The same rows edit environment defaults or project overrides depending on the -project crumb. - -The Projects category, under Code, holds the project's name, icon, actions, -checkouts and removal. Actions belong to a project: editing them creates the project's own list -on each selected environment, and reset returns to the environment's shared list. A project's -`t3.json` actions can be imported there. When a project has several checkouts on one environment, -choose one in the scope line at the top to see or change only that checkout's settings. - -Settings a repository can also declare in `t3.json`, such as the workspace for new threads, -resolve in one order: a project override, then the environment setting, then `t3.json`, then the -built-in default. Leave a setting on **Inherit** to let the next tier decide. -Browser access changes apply when an agent session next starts. - -New worktrees initialize git submodules recursively. If that step is slow because the repository -declares many nested submodules, set **Submodules** in **Settings → Worktrees** under Advanced (with the project -selected to override it there) to **Top level only** to stop at the ones the repository declares -itself, or **Skip** to leave them for a setup script. It resolves in the same order as the -workspace default: a `"worktreeSubmodules"` value in the `t3.json` of the branch being checked out -applies when the project and environment are both on **Inherit**. - -New worktrees check out every file. For a large repository, set `"worktreeSparsePatternsPath"` in -`t3.json` to a repository-relative file of git sparse-checkout patterns in non-cone syntax. New -worktrees then check out only the matching files, before any other file is written. Both files are -read from the branch being checked out, so the patterns can leave out `t3.json` and `.gitmodules`. -If the pattern file is missing, creating the worktree fails instead of checking out everything. -Submodules still follow **Submodules** above, also under excluded paths; set it to **Skip** to leave -them empty. The first sparse worktree turns on Git's `extensions.worktreeConfig` for the repository. -This needs Git 2.35 or newer. - -## Worktree location - -New worktrees go in the `worktrees` folder of the T3 home directory. To put them somewhere else, -such as another drive, set **Settings → Worktrees → Worktree location** to an absolute path like -`D:\worktrees` or `~/worktrees`. The setting is per machine. Existing worktrees stay where they -are, and cleanup covers both the default folder and the custom one. - -## Fast worktree checkout on macOS - -Fast worktree checkout is a beta. Turn it on for each Mac in **Settings → Labs → Fast worktree -checkout**. T3 Code then keeps a few recent checkouts of each repository in the `caches` folder of -the T3 home directory. A new worktree is cloned from one of them with APFS copy-on-write, which is -about twice as fast as writing every file and makes the first `git status` in it fast as well. -Turning it off deletes the cache. - -The first worktree of a repository uses Git's normal checkout and fills the cache. It needs Git 2.42 -or newer. Git's normal checkout is also used for worktrees on a different drive from the T3 home -directory, sparse checkouts, repositories whose attributes use filters such as Git LFS, and -repositories whose checkout settings changed. - -## Storage cleanup - -Open **Settings → Worktrees → Cleanup** to enable automatic cleanup on one machine or all connected -environments. Policies are off by default and run on the server at startup, when changed, and -hourly. Offline machines keep their existing policies. - -Select a project to set **Automatic worktree cleanup** to **Inherit**, **Off**, or **Custom**. -Inherit follows each machine's rules; Off keeps that project's worktrees until you remove them -manually. Custom applies separate worktree rules to the selected project or checkout. Browser -captures and log retention remain machine-wide. - -Worktrees can be removed after a chosen number of inactive days, after a thread settles, after -merging, or when they have no commits beyond the default branch and their thread is settled or -archived. Set settled retention to 0 days to remove a worktree at the next cleanup after -settlement. In repositories without remotes, -unchanged-worktree cleanup compares against the branch checked out in the project workspace; -if that checkout has a detached HEAD, the worktree is kept. Only T3-managed worktrees are eligible. -Active sessions and shared worktrees prevent removal. **Keep worktrees with local changes** defaults -to **Uncommitted changes**, which protects tracked edits and untracked files but deletes ignored -files such as `.env` and build output. **Any local files** also protects ignored files other than -`node_modules`. **Edited tracked files** protects only tracked edits and allows untracked and -ignored files to be deleted. Branches and thread history stay; starting another turn recreates the checkout. -Merge cleanup requires a merged pull request whose commits are included in the remote default -branch. A squash or rebase merge on GitHub also counts when the pull request targeted the default -branch and the worktree is still at the pull request's last commit. - -Enable **Delete worktrees with deleted threads** to remove safe worktrees after their last -thread is deleted, including archived threads and worktrees left by earlier deletions. The -server waits for sessions and terminals to stop and retries skipped worktrees after restart. -Existing prompts for deleting a worktree manually remain available when this policy is off. - -Choose **Delete now** to run the enabled rules immediately. The latest results show which -worktrees were removed or kept and why, plus any failures. -Results also list folders in the worktree folder that no thread uses, with their sizes; cleanup never removes them, so remove them manually if you want. - -The inactive and settled retention periods also apply to the folders of -[threads without a project](./thread-sidebar.md#start-without-a-project). Those folders are not -Git repositories, so their files are deleted with them and cannot be recovered; the thread stays, -and its next turn starts in a new, empty folder. A folder is kept when it has a Git repository -anywhere inside it or when its thread has an enabled scheduled task. Every file in such a folder -counts as untracked, so only **Edited tracked files** removes a folder that holds anything other -than `node_modules`; the other two rules remove only empty folders. Folders that no thread uses -are listed here too. - -Browser captures and rotated logs have separate retention periods. Expired capture links stop -working. Current logs, message attachments, and browser profiles are kept. +## Keep the default branch current -## Project icons +Enable **Settings → Source control & issues → Automatically pull** to fast-forward clean default-branch checkouts from their configured upstream. Skips checkouts with local changes, untracked files, local commits, other branches, or no upstream. -Select the project and open Project to choose an icon, emoji, monogram, or image. The choice applies to -every checkout in the project group and appears on connected clients. Choose **Automatic** to let -T3 Code detect an icon again. +## Scheduled tasks and webhooks -Choose **Monogram** in the icon picker to set one or two letters or numbers and a color. +Create and manage scheduled tasks in **Settings → Scheduled tasks** (web, desktop, and mobile). -When no image is found, web and desktop show a two-character monogram with a color -from the icon palette, derived from the saved project name. For example, `Nebula` becomes `NA`, -`Silver Orchard` becomes `SO`, and `M7 Forge` becomes `M7`. A name that starts with a Chinese, -Japanese, or Korean character uses only that character, so `健康顾问` becomes `健`. +- **Schedules**: Recurring fixed-time schedules use the target environment's time zone. **Once** uses your local time zone (runs on reconnect if offline). +- **Destination**: Choose **New thread each run**, **One thread (continue conversation)**, or **One thread (fresh session each run)**. Deleting a target thread deletes tasks bound to it; archiving a target thread causes runs to fail (settle it instead). +- **Controls**: Edit, pause, resume, run now (except webhook tasks), or delete from the list. -## Keep the default branch current +### Webhook automations -In Source control & issues, enable **Automatically pull** to keep the default-branch checkout up to date -with its configured upstream. Choose an environment to set the default or a project to override it. -On mobile, use **Settings → Source control & issues** to change selected environment defaults or project overrides. +Choose **On webhook** as a task's schedule to trigger runs from external services (e.g., GitHub PR or CI events). A public URL requires a [T3 Connect](./remote-access.md) tunnel; click **Rotate** to invalidate and replace the URL. -T3 Code only pulls when it can fast-forward and the checkout has no changed files, untracked files, -or local commits. It skips checkouts on another branch or without an upstream. If a checkout has -local work, resolve it yourself before automatic pulls can resume. +- **Prompt placeholders**: Insert `{{body.path}}`, `{{headers.name}}`, `{{query.name}}`, `{{body}}`, or `{{request}}`. Missing values render empty. +- **Untrusted input protection**: Placeholder values are wrapped in `` tags, and `$`/`@`/leading `/` tokens are neutralized so untrusted payloads can't invoke skills or commands. +- **Signatures** (web/desktop setup): Enable **Require signature** to verify HMAC signatures (for GitHub, keep `x-hub-signature-256`, hex, and `sha256=` prefix with the same secret and `application/json`). +- **Filters**: Add conditions (using paths without braces, e.g. `headers.x-github-event` equals `pull_request`, or `body.action` is one of `opened, reopened`). All filters must match; non-matching requests are logged as **Filtered**. +- **Deduplication & coalescing**: Set a **Duplicate request key** (e.g. `{{headers.delivery-id}}`; ignores repeats for 7 days) or a **Coalesce key** with a 10–3600s window (default 120s; runs once with the latest payload when the window closes). Coalesced updates are rate-limited to 60/min (`HTTP 429`). +- **Offline delivery**: By default, offline environments return an error. Enable **Settings → Sharing & access → Hold webhooks while offline** to buffer T3 Connect webhooks for up to 24 hours, and optionally set **Skip requests older than** on the task. +- **Debugging**: Open **Deliveries** from a task's menu (web/desktop) to inspect recent payloads and rendered prompts. diff --git a/docs/user/prompt-links.md b/docs/user/prompt-links.md index 2c5ab07bec939..5429e9a39b1da 100644 --- a/docs/user/prompt-links.md +++ b/docs/user/prompt-links.md @@ -1,64 +1,41 @@ # Prompt links -A prompt link opens T3 Code with a prompt ready to send. Use one to share a prompt on social -media, or to put a one-click fix in a pull request comment. +A prompt link opens T3 Code with a prefilled draft—useful for sharing prompts or adding one-click fixes in pull request comments. -A link never runs anything. It opens a draft. You read the prompt, then press Send. A link cannot -change your permission mode, branch, or worktree. Your own defaults apply. +Links **never** auto-send or change your permission mode, branch, or worktree. They only open a draft for you to review and send. -## Make a link +## Create a link -Open the command palette and choose **Copy prompt link**. It copies the draft in the composer. -When the project is on GitHub, **Copy prompt link with repo and model** also adds the repository -and the model you picked. Sent messages have a **Copy prompt link** button too. +- **From the composer**: Open the command palette and choose **Copy prompt link** (or **Copy prompt link with repo and model** on GitHub projects). +- **From a sent message**: Click **Copy prompt link**. +- **By hand** (URL-encode the prompt, e.g. with `encodeURIComponent`): -You can also write a link by hand: - -``` +```text https://app.t3.codes/new?prompt=Rate%20my%20swearing https://app.t3.codes/new?prompt=Fix%20the%20build&repo=owner/name&provider=codex&model=gpt-5.5 https://app.t3.codes/new?pr=owner/name/123&prompt=Fix%20the%20failing%20check ``` -| Parameter | Meaning | -| ---------- | ----------------------------------------------------------------------------- | -| `prompt` | The prompt. Required, except on pull request links. At most 8,000 characters. | -| `repo` | A GitHub repository, as `owner/name` or its URL. | -| `provider` | A provider such as `codex` or `claude`. | -| `model` | A model of that provider, by its id or name. | -| `pr` | A GitHub pull request, as `owner/name/123` or its URL. | - -Encode the prompt for a URL. In JavaScript, use `encodeURIComponent`. - -## Open a link +| Parameter | Description | +| ---------- | ----------------------------------------------------------------- | +| `prompt` | Draft text (up to 8,000 characters). Required unless `pr` is set. | +| `repo` | GitHub repository (`owner/name` or URL). | +| `provider` | Provider ID (e.g. `codex`, `claude`). | +| `model` | Model ID or name for that provider. | +| `pr` | GitHub pull request (`owner/name/123` or URL). | -On app.t3.codes, the link first asks where to open it: the desktop or mobile app, this browser -when it is connected to a machine, or the download page. Select **Remember my choice** to skip -this step next time. +## How links open -- **No `repo`**: the draft opens without a project, on the machine you used last. -- **`repo`**: the draft opens in your most recently used project for that repository. A fork - counts only for its own owner. When you do not have the repository, choose **Clone** or **Use - without project**. -- **`provider` and `model`**: used when you have that provider set up. Otherwise your default - model is used, and T3 Code tells you. -- **`pr`**: opens the thread linked to that pull request on any connected machine, with the prompt - in its composer. When no thread is linked, the draft goes on the pull request branch in a new - worktree. T3 Code checks the code out only after you confirm, because the checkout runs your - setup script on it. +Opening a link on `app.t3.codes` asks whether to use the desktop/mobile app, the current browser, or the download page (**Remember my choice** skips this next time). -A thread link with a prompt, such as `https://app.t3.codes//?prompt=…`, -puts the prompt in that thread's composer. If you already typed a draft there, T3 Code asks -before it replaces it. +- **No `repo`**: Opens a no-project draft on your last-used machine. +- **`repo`**: Opens in your most recent project for that repo (or offers **Clone** / **Use without project**). +- **`provider` / `model`**: Applied if configured; otherwise falls back to your default with a notice. +- **`pr`**: Opens the thread linked to that PR, or prepares a new worktree draft on the PR branch after you confirm checkout. +- **Thread prompt link** (`https://app.t3.codes//?prompt=…`): Prefills that thread's composer (asks before overwriting an existing draft). -T3 Code removes characters you cannot see, such as zero-width and hidden tag characters, because -they can hide instructions for the agent. When a prompt had them, T3 Code warns you that it may be -malicious. +T3 Code strips invisible characters (such as zero-width and hidden tag characters) and warns you if a prompt contained them. ## Share a thread -**Copy thread** copies a link such as `https://app.t3.codes/threads//`. Paste -it anywhere, such as Slack, a GitHub comment, or your notes. On a phone with T3 Code installed, it -opens the thread in the app. Elsewhere, opening it asks where to open it, like a prompt link, then -opens the thread. Only someone connected to the machine that runs the thread can see it. In T3 Code, -a thread link in a message opens the thread in the app. +**Copy thread** copies a link (`https://app.t3.codes/threads//`) that opens in T3 Code on desktop, web, or mobile and pastes into any composer as a thread chip. Only someone connected to the machine running that thread can view it. diff --git a/docs/user/providers-acp.md b/docs/user/providers-acp.md index 7310d6ad913fd..671280bad41a0 100644 --- a/docs/user/providers-acp.md +++ b/docs/user/providers-acp.md @@ -1,149 +1,45 @@ # ACP providers -T3 Code can run installed ACP commands or coding agents from the official -[ACP Registry](https://agentclientprotocol.com/get-started/registry). Registry agents bring their -own models, tools, and sign-in, while T3 Code provides projects, threads, checkpoints, and task -delegation. +T3 Code can run any coding agent from the official [ACP Registry](https://agentclientprotocol.com/get-started/registry) or any local ACP-compatible command. Built-in providers (Codex, Claude, Cursor, Grok, OpenCode, Pi, Antigravity) are enabled directly in **Settings → Providers** instead. -Agents that T3 Code supports as their own providers, such as Codex, Claude, Cursor, Grok, OpenCode, -Pi, and [Antigravity](./providers-antigravity.md), don't appear in the Registry list. Enable them in -**Settings → Providers** instead. - -T3 Code prefers the current ACP v2 preview protocol and uses its richer messages, usage, plans, -configuration, compaction, and agent-terminal updates when the agent supports them. It also -negotiates ACP v1 for Registry agents that have not migrated yet, so they continue to work through -the same generic integration. - -Claude Agent uses the ACP v2 preview by default for Registry and local `claude-agent-acp` -commands. If you encounter preview issues, set `CLAUDE_AGENT_ACP_EXPERIMENTAL_V2=0` in the -provider instance's environment overrides to use ACP v1. +T3 Code negotiates ACP v2 preview when supported and falls back to ACP v1 automatically. For `claude-agent-acp`, set `CLAUDE_AGENT_ACP_EXPERIMENTAL_V2=0` in the instance's environment overrides if you need ACP v1. ## Add an agent -1. Open **Settings → Providers**. -2. Select **Add provider**, then **Show more**. -3. Search the ACP Registry for the agent and select **Add** on its result. -4. Confirm the name and instance ID, then complete the agent's sign-in step. - -Search only shows agents that can run on the connected server. Registry agents are third-party -code; review an agent's source and license before adding it. - -## Add a local command - -In **Settings → Providers → Add provider**, select **Show more**, then **Local ACP command**. Enter the executable -name or path on the selected environment, add one literal argument per row, and choose a display -name. For DeepSeek Harness, use `dsh` with arguments `--profile` and `acp`. - -Local commands require no registry entry or download. Environment overrides apply to the command; -credentials and skills remain managed by the installed agent or its wrapper. Models and reasoning -options come from ACP, including model IDs that contain JSON. T3 Code launches the executable directly -without expanding shell expressions. - -## Where agents run - -Registry agents always run on the machine that hosts your T3 Code server. That stays true when you -connect through `app.t3.codes`, T3 Connect, or a relay. - -Agents install under `tools///` inside T3 home. T3 Code verifies SHA-256 when the Registry entry -provides one; entries without a checksum retain the Registry's HTTPS distribution guarantee. -Registry `npx` and `uvx` packages use T3-owned npm prefixes and Python tool directories at the exact -version published by the Registry. Their commands are available in a new server terminal for -sign-in and direct use. Removing an agent's last provider instance removes T3-managed binary files -but keeps package installs. To use an existing local binary, set **Executable override** explicitly. - -T3 Code checks the Registry for new versions in the background and installs them for T3-managed -agents on the next provider check; a check is skipped while that agent is starting a session. -Refreshing providers in Settings checks the Registry right away. +- **From the ACP Registry**: Open **Settings → Providers → Add provider → Show more**, search for an agent compatible with your server, click **Add**, and complete sign-in. Registry agents are third-party code—review an agent's source and license before adding it. +- **Local ACP command**: Under **Show more → Local ACP command**, enter the executable path/name, literal arguments (one per row—no shell expansion; e.g., `dsh` with `--profile` and `acp`), and a display name. -## Signing in +## Installation and updates -Open the agent's account section in **Settings → Providers** on web or desktop. Choose -**Sign in** and, if the agent offers several methods, select one. For an installed, configured -provider, mobile also offers **Settings → Providers**. +Registry agents run on your T3 Code server (including when accessed remotely) and install under `/tools///` with SHA-256 verification when provided. T3 Code checks for Registry updates in the background and installs them on the next provider refresh. Set **Executable override** to use your own local binary instead. -Browser sign-in shows the agent's URL and waits for you to open or copy it before telling the -agent to proceed. The page opens on your device, while the agent runs on the environment. -Terminal methods run in an in-app terminal on that environment. On mobile, send responses -through the terminal response field. T3 Code reconnects after terminal login and waits for the -agent to confirm sign-in before reporting success. You can cancel or retry an expired attempt. +## Sign in -Browser and terminal sign-in leave credentials in the agent's own store. Agents that use API keys -through environment variables still take those keys in the instance's environment settings. -A configured environment or agent home applies to both sign-in and chat. +Open the agent's account section in **Settings → Providers** and click **Sign in** (choose an auth method if multiple are offered). -If the agent advertises logout, choose **Sign out**. Changing a shared agent login stops running -threads for instances of that same agent on the environment. Thread history and workspace files -are kept. ACP does not describe account isolation, so adding another instance does not guarantee -a separate account; use the agent's own configuration to isolate accounts when supported. +- **Browser sign-in**: Opens the auth URL on your device while the agent runs on the server. +- **Terminal sign-in**: Runs in an in-app terminal on the server (or uses a response field on mobile). +- **API keys**: Add required variables in the instance's **Environment** settings. -If an agent cannot complete its advertised flow remotely, its CLI remains available on the -server. For example, Codex supports `codex login --device-auth`, and Grok Build supports -`grok login --device-auth`. +Credentials stay in the agent's own store; changing a shared login stops running threads for that agent on the server while keeping history. -## Models and options +## Models, commands, and native sessions -The model picker lists the models the agent reports. If the agent reports none, or hides some, add -your own model IDs under **Custom models** in the instance settings. - -Other settings the agent offers, such as reasoning effort or approval mode, appear in the -composer's model picker, beside the model list, like they do for built-in providers. Models and options that change while an agent -is running update the picker without waiting for another provider probe. - -## Commands and skills - -Slash commands the agent provides appear under **Provider** in the `/` menu while a session is -running. Commands the agent names with a `$` prefix appear in T3 Code's `$` skill menu instead. - -## Native sessions - -When an agent advertises ACP session listing and import support, expand its provider card, -choose a project, and select **List sessions**. Importing one creates a deterministic T3 thread -backed by that native session. Importing the same agent session again returns the existing thread, -including when another client performs the import. - -The thread keeps the native session's title and last-update value as provider metadata without -overwriting a title you set in T3 Code. Agents that report ACP context usage drive the thread details -context window and cumulative cost metadata. See -[commands and skills](./composer.md#commands-and-skills) to show it on web and desktop. -Text resources and links render as assistant output; -binary resources, images, and audio that T3 Code cannot render yet appear as explicit placeholders -instead of disappearing. +- **Models & options**: Reported automatically by the agent in the model picker. Add unlisted model IDs under **Custom models**. +- **Commands & skills**: Agent slash commands appear under **Provider** in `/`; `$`-prefixed commands appear in the `$` skill menu. +- **Native sessions**: When supported by the agent, expand its provider card, choose a project, and select **List sessions** to import existing sessions into T3 Code threads. +- **Text generation**: Select an ACP model in **Settings → Threads → Text generation model** to generate titles, commit messages, and PR descriptions. ## Permissions and terminals -Registry agents read files, edit, and run commands themselves, under their own sandbox and -approval rules. They start in their own default mode, and their mode picker in the model options -menu switches it. How far an agent is confined depends on that mode and the agent's own settings, -so use its sandbox and permission controls when that matters. - -When a registry agent asks for approval, T3 Code answers by the thread's -[permission mode](./permission-modes.md): **Supervised** shows the request in the conversation, -**Auto-accept edits** approves edits inside the thread's folders and shows the rest, and **Auto** -and **Full access** approve automatically. File reads and searches never wait for approval. +Registry agents enforce their own sandbox and approval rules (switchable via their mode picker in model options). When an agent asks for approval, T3 Code answers according to the thread's [permission mode](./permission-modes.md): -Devin runs its commands through T3 Code's terminals, and those commands follow the thread's -permission mode. For other agents, T3 Code shows the command, output, and exit status the agent -reports but does not run or stop their terminals. +- **Supervised**: Shows approval requests in chat. +- **Auto-accept edits**: Auto-approves edits inside the thread's folders; asks for everything else. +- **Auto** and **Full access**: Approves automatically. -Registry agents can schedule work and use T3's MCP tools. Child-task presentation depends on what -the agent exposes: ACP has no portable native subagent-lineage contract, so richer delegation views -remain agent-specific. +File reads and searches never wait for approval. Devin runs commands in T3 Code terminals; other agents run their own terminals and report output/exit status. ## Checkpoints -Checkpoint rollback restores your files as usual. ACP agents cannot rewind their own conversation, -so the next turn after a rollback starts a fresh agent session and T3 Code sends it the kept -conversation, without the turns you rolled back. - -Select an ACP model in **Settings → Threads → Text generation model** to use it for generated text, -such as thread titles, commit messages, and pull request descriptions. Branch names use this model -unless a source-control writer model is configured. Each request opens a separate session outside -the project checkout. T3 requests session deletion when the agent supports it. The agent controls -whether it retains session history. - -## Advanced configuration - -- **Executable override** runs an existing local executable instead of the managed distribution, - keeping the registry-declared arguments and environment. -- **Authentication method** picks a specific method when the agent advertises more than one. -- **Custom models** adds model IDs the agent does not report. +Checkpoint rollback restores workspace files as usual. Because ACP agents cannot rewind their own conversation, the next turn starts a fresh session with the kept conversation history. diff --git a/docs/user/providers-antigravity.md b/docs/user/providers-antigravity.md index 614fda68f2c1d..63128713dc5f6 100644 --- a/docs/user/providers-antigravity.md +++ b/docs/user/providers-antigravity.md @@ -1,172 +1,57 @@ # Antigravity -T3 Code runs Google's official Antigravity ACP agent on your selected environment. -T3 manages its own CLI installation and sign-in, separate from your terminal or IDE. Google controls -which models and account access are available through this agent. +T3 Code runs Google's official Antigravity ACP agent on your selected environment, with a T3-managed CLI installation and sign-in separate from your terminal or IDE. ## Set up Antigravity -On web or desktop, open **Settings > Providers**, choose the environment that runs -your project, and enable Antigravity. Install its runtime there, then choose -**Sign in** and complete the browser sign-in. Wait for T3 Code to confirm -account access and load models before starting a thread. Once the runtime is installed, -you can also sign in from **Settings > Providers** in the mobile app. +1. Open **Settings → Providers** (web or desktop), choose your environment, and enable **Antigravity**. +2. Install the managed runtime (requires 1.25+ GiB free disk space; supports macOS Apple Silicon/Intel, Linux x64/ARM64 glibc/musl, and Windows x64/ARM64). +3. Click **Sign in** and complete browser sign-in. Wait for T3 Code to confirm access and load models. (Once installed, you can also sign in from mobile.) -Installation continues if you leave settings or reconnect. Setup requires -permission to operate the environment; update an older server if it does not offer -Antigravity setup. +- **Remote sign-in**: Paste the temporary code (or full URL) from Google's completion page into T3 Code's code field. +- **Manual binary**: Install [Antigravity CLI](https://antigravity.google/docs/getting-started) and set **Binary path** to `agy`. Leave blank to use the managed runtime (or `PATH`). +- **Updates**: Click **Update Antigravity** in provider settings. T3 Code requires Antigravity **1.5+** (1.5.12+ recommended); running threads finish on their original runtime. -### Sign in from a remote device +### Sign-in methods -Google finishes on an Antigravity page that shows a code. Paste that code, or the -page's full address, into the code field in the client where you started sign-in. -This works the same from any device. +Choose **Sign-in method** in the Antigravity instance settings: -The code is temporary. Paste it only into the setup field. The page alone does not -confirm account access; wait for T3 Code's confirmation. +| Method | Credentials | +| ------------------------------ | ----------------------------------------------------------------------- | +| **Google account** | Personal Google browser sign-in | +| **Gemini Enterprise** | Browser sign-in, GCP project, and GCP location | +| **Gemini API key** | API key (no browser required) | +| **Agent Platform / Vertex AI** | API key, or GCP project + location with Application Default Credentials | -### Other sign-in methods +API keys are stored outside `settings.json`, and ambient `GEMINI_API_KEY` / Google env vars do not override the instance's configured method. -Choose **Sign-in method** in the Antigravity provider settings: +## Models, planning, and goals -| Method | Credentials | -| -------------------------- | -------------------------------------------------------------------------------------------- | -| Google account | Personal Google sign-in in the browser | -| Gemini Enterprise | Browser sign-in, GCP project, and GCP location | -| Gemini API key | API key; choose Connect without a browser | -| Agent Platform / Vertex AI | API key, or GCP project and location with Application Default Credentials on the environment | - -The environment stores the Antigravity API key outside its settings file, and -clients only see whether one is saved. The agent uses the method and credentials selected for this instance; -ambient `GEMINI_API_KEY` and Google credential variables do not override them. -Changing the method stops the instance's sessions. Sign out before replacing an -account. - -## Runtime installation - -Managed installation supports Apple Silicon and Intel macOS, Linux x64 or ARM64 -with glibc or musl, and Windows x64 or ARM64. Allow at least 1.25 GiB of free disk -space for downloading and staging an update. - -### Use a manual installation - -Install [Antigravity CLI](https://antigravity.google/docs/getting-started) on the environment. -Set **Binary path** to its `agy` executable and update it yourself. -Leave the field blank to use the managed runtime, or a compatible executable on -`PATH` if no managed runtime is installed. - -## Update the managed runtime - -In web or desktop provider settings, choose **Update Antigravity** when an update -is available. T3 checks Google's CLI release channel while provider update checks -are enabled. Installing or reinstalling also checks that channel. Updates keep -your profile and existing runtime available if the new release fails validation. - -T3 needs Antigravity 1.5 or newer and recommends 1.5.12 or newer. Sessions do not -start on an older runtime: update the managed runtime here, or update the executable -a custom binary path or `PATH` points at. You may need to sign in again after -updating from a runtime older than 1.5. Threads already running finish with their -original runtime; new sessions use the updated release. Custom binary paths keep -using the executable you selected. - -## Models and threads - -The model list comes from your Antigravity account, including Claude and GPT models -when your plan has them. Pick a thinking level beside the model list in the model picker; it -shows only the levels the selected model supports. A resumed thread keeps its -selected model. If access to that model ends, select another available model -before continuing. - -Antigravity creates empty `.gemini/skills` and `.agents/skills` folders in the -workspace when a session starts. Git does not track empty folders, so they never -appear in commits. - -Use Antigravity's native `/plan` command for planning. Tool approvals follow [Permission modes](./permission-modes.md). -Questions with fixed choices still need one of the offered answers, even in -**Full access**. - -On web and desktop, [Edit from here](./composer.md#edit-an-earlier-prompt) works with -Antigravity. Antigravity cannot rewind its own conversation, so the next turn -starts a fresh Antigravity session and T3 Code sends it the kept conversation, -without the turns you removed. - -Use `/compact` to summarize a long conversation when your Antigravity runtime -offers that command. If it is unavailable, update Antigravity in provider settings -or send `/clear` when you need a fresh context. +- Models (including Claude and GPT when included in your plan) and thinking levels come from your Antigravity account. +- Use `/plan` for planning, `/compact` to summarize (if supported by your runtime), or `/clear` for a fresh session. +- **Edit from here** starts a fresh Antigravity session with the kept conversation history. +- **Native goals**: Send `/goal ` when supported by your runtime. Use **Stop** to interrupt, then tell Antigravity to stop pursuing it before starting new work (`pause`/`resume`/`clear` are not supported). +- **Subagents**: Batched subagent activity is inspectable read-only via **Subagent work** (**Work** on mobile). +- Antigravity creates empty `.gemini/skills` and `.agents/skills` directories in workspaces on start (untracked by Git). ### Skills and attachments -Put project skills in `.agents/skills`. T3 Code also reads `.gemini/skills` and the -legacy `.agent/skills` directory. Among these project locations, the first copy -wins in this order: `.gemini/skills`, `.agents/skills`, `.agent/skills`. See -[commands and skills](./composer.md#commands-and-skills) for invoking them. - -Skills for every project go in `~/.gemini/config/skills` or -`~/.gemini/antigravity-cli/skills`. Antigravity does not read `~/.agents/skills` -on its own; to share a folder like that one, list it in `~/.gemini/config/skills.json` -(or a project's `.agents/skills.json`), and T3 Code shows the skills it declares, -honoring `inherits`, `include_only`, and `exclude`. - -Antigravity receives images and audio directly, and reads PDFs and text files as -documents. Other attachments, including videos, are passed as a saved file path for -the agent to inspect with its tools. - -### Subagents - -Antigravity groups subagent activity into batches. Open a batch and select -**Subagent work** (**Work** on mobile) to read each child's role, prompt, and recent steps. This view -is read only: you cannot message or control individual subagents, and an idle -batch does not confirm that every child succeeded. If Antigravity did not record -which children a batch started, the view says so. See -[agent work](./thread-sidebar.md#inspect-agent-work) for where to inspect -activity. - -## Accounts and removal - -Add an Antigravity provider instance for each Google account in -**Settings > Providers** on web or desktop. Each has its own sign-in; downloaded -runtimes are shared on the environment. - -| Action | Effect | -| ------------------------- | ----------------------------------------------------------------- | -| Disable | Stops the instance's sessions and keeps its Google sign-in. | -| Sign out | Stops the instance's sessions and removes its saved Google login. | -| Remove downloaded runtime | Removes the shared installation and keeps Google credentials. | - -All three keep thread history and workspace files. Sending `/logout` by itself in -a thread signs out its instance, including stopping that instance's other sessions. -That needs a client allowed to manage providers, and it has to be your own message: -`/logout` from an agent or a scheduled task is refused. -Sign out, then sign in again to replace an account. - -Before removing a managed runtime, disable its instances and cancel any active -installation. Clear any explicit binary path pointing into that runtime. Removal -is refused while the runtime is in use. - -## Run a native goal - -When your Antigravity runtime offers `/goal`, send `/goal` followed by a verifiable -objective. Antigravity keeps working until it completes the goal or you cancel it. - -Use Stop to interrupt a running goal, then ask Antigravity to stop pursuing it -before starting more work. Ordinary follow-ups wait until the running turn ends. -T3 does not support Antigravity goal status, pause, resume, or clear commands. - -## Check access and troubleshoot +- **Project skills**: Loaded in priority order from `.gemini/skills`, `.agents/skills`, then `.agent/skills`. +- **Global skills**: Loaded from `~/.gemini/config/skills` or `~/.gemini/antigravity-cli/skills` (list `~/.agents/skills` in `~/.gemini/config/skills.json` or `.agents/skills.json` to include it). +- **Attachments**: Images and audio go directly to the model; PDFs and text files load as documents; videos and other files pass a saved file path (supported videos go natively to Gemini models). -Open **Usage > Limits** to see the remaining Gemini and shared Claude/GPT allowances -for Google sign-ins. Each group has separate five-hour and weekly limits and reset -times. Limits refresh with provider status and include usage outside T3 Code. +## Multiple accounts and removal -A server restart keeps your Google sign-in. The provider shows the saved account -until a session, a refresh, or a sign-out reports something new. +Add a separate Antigravity instance in **Settings → Providers** for each Google account (runtimes are shared on disk). -To check access and reload models, use **Refresh provider status** in web or desktop -provider settings, or **Refresh models** in mobile thread settings. If asked to -sign in again, use provider settings on web or desktop, or **Settings > Providers** on mobile. +| Action | Effect | +| ----------------------------------- | ----------------------------------------------------------------------- | +| **Disable** | Stops sessions; keeps saved login and history. | +| **Sign out** (or `/logout` in chat) | Stops sessions and removes saved login; keeps history. | +| **Remove downloaded runtime** | Deletes shared runtime after instances are disabled; keeps credentials. | -If Google reports `SUBSCRIPTION_REQUIRED`, an account restriction, or a usage limit, -follow the provider's message and any retry time. See [Google's account plans][plans] -for eligibility. +## Usage and troubleshooting -[plans]: https://antigravity.google/docs/plans +- Check 5-hour and weekly Gemini / shared Claude & GPT quotas under **Usage → Limits**. +- Use **Refresh provider status** (web/desktop) or **Refresh models** (mobile) to reload models and access. +- For `SUBSCRIPTION_REQUIRED` or account restriction errors, see [Google's account plans](https://antigravity.google/docs/plans). diff --git a/docs/user/providers-claude.md b/docs/user/providers-claude.md index 009a237a67574..12b068d6622d3 100644 --- a/docs/user/providers-claude.md +++ b/docs/user/providers-claude.md @@ -1,182 +1,55 @@ # Claude -T3 Code uses Claude Code's login and configuration. Start with the default provider -for one account; [provider setup](./install.md#providers) covers installation and -shared provider settings. +T3 Code drives your Claude Code installation, login, skills, and plugins. See [provider setup](./install.md#providers) for initial installation. -## Separate accounts or configurations +## Multiple accounts and presets -Use a separate Claude config directory for each account. This also works for named -presets that need different Claude settings or a router connection. - -Keep your existing account in the default directory. On the environment's machine, -create the second login: +Isolate separate Claude accounts or router presets with distinct `CLAUDE_CONFIG_DIR` directories: ```bash mkdir -p ~/.claude_personal CLAUDE_CONFIG_DIR=~/.claude_personal claude auth login ``` -Add another Claude instance in **Settings > Providers**: +Add a second Claude instance in **Settings → Providers** (or **Add Claude account** on mobile) pointing **CLAUDE_CONFIG_DIR path** to `~/.claude_personal` (leave empty for the default directory). Always use `CLAUDE_CONFIG_DIR` rather than `HOME` so system keychain paths stay intact. -| Instance | Binary path | CLAUDE_CONFIG_DIR path | -| --------------- | ----------- | ---------------------- | -| Claude Work | `claude` | Leave empty | -| Claude Personal | `claude` | `~/.claude_personal` | +- Existing threads can only switch between Claude instances sharing the same config directory. +- Put API keys and endpoint overrides in **Environment variables** (not **Launch arguments**). +- Paths in `--settings` and `--append-system-prompt-file` expand `~` to the server's home directory; other relative paths resolve from the thread's workspace. -On mobile, tap **Add Claude account** in **Settings > Providers** and enter a name and the -config folder. The login itself still happens on the environment's machine. +## Compact long conversations -An empty config-directory setting uses Claude Code's normal configuration. The -custom setting changes `CLAUDE_CONFIG_DIR`, leaving `HOME` and the system keychain -location intact. Use the same variable for the login command. Setting `HOME` -instead can put credentials where this provider will not find them. +- **Auto-compact threshold**: Set **Auto-compact after** (`100000`–`1000000` tokens) in the Claude instance settings to trigger summarization earlier without changing the model's context window. +- **Manual compaction**: Send `/compact` in chat. +- **Idle compaction (>200k tokens)**: Configure **Settings → Providers → Advanced → Compact idle threads** (overridable per instance): + - **When you return** (default): Shows a **Compact** chip next to Send once Claude's prompt cache expires (~1 hour on subscriptions, 5 min on API/Bedrock/Vertex). Click it to switch to **Keep** if you want full history. + - **Before the cache expires (beta)**: Automatically sends `/compact` shortly before the cache expires while history is still cached (falls back to **When you return** if missed). + - **Never**: Disables idle compaction prompts. -Check the account reported in provider settings after signing in. Existing -threads can switch only between Claude instances with the same config directory. -Separate account directories stay isolated, including their local conversation -state. Claude does not have Codex's shared-home and shadow-home arrangement. +## Steering, usage limits, and tasks -For presets that differ only in API keys or endpoints, use the instance's -**Environment variables**. Variable assignments do not belong in **Launch arguments**. +- **Steering**: Steered messages wait until Claude finishes its active tool calls, then enter the same turn (or queue for the next turn if Claude exits or drops them). +- **Usage limits**: Mid-turn limit hits display the window and reset time; Claude holds the turn until reset, or you can stop and resume later. +- **Task lists**: Add `CLAUDE_CODE_ENABLE_TODO_TOOLS=1` in the instance's **Environment → Variables** to show Claude's task list progress in web and desktop threads. +- **Auto mode**: Uses Claude Code's native auto mode (disabled if `disableAutoMode` is set in Claude's managed, user, or project settings). See [Permission modes](./permission-modes.md). -File paths in the `--settings` and `--append-system-prompt-file` launch arguments -can start with `~` for the home directory of the machine running T3 Code. Any -other relative path is read from the thread's project folder, or its worktree. +## Skills and MCP sign-in -Claude Code's verbose mode can stay enabled when you use Claude for text generation, including -thread titles, branch names, commit messages, and pull request descriptions. On a remote connection, -T3 Code uses the Claude configuration on the connected server. +- **Skills**: Loaded from `/skills`, the project's `.claude/skills` (config dir wins on name collisions), and enabled Claude plugins (e.g. `plugin:review`). Invoke via `$`. Send `disable-model-invocation` skills one per message. +- **MCP OAuth**: When a Claude MCP server needs sign-in, click **Sign in** on the thread notice, approve in your browser, and paste the final redirect URL into T3 Code (**Finish sign-in**). Connectors added on `claude.ai` authenticate there instead. -## Compact long conversations +## Claude in Chrome -Set **Auto-compact after** in the Claude provider settings to an integer between -`100000` and `1000000`. For example, `300000` asks Claude to summarize at about -300,000 tokens. This changes when compaction happens, not the model's context -window. Leave it empty for Claude Code's default. - -You can also send `/compact` in an existing conversation. Claude Code also -compacts automatically. To see context usage, see -[commands and skills](./composer.md#commands-and-skills). - -When you return to a large thread after Claude's prompt cache expires, a -**Compact** chip with the thread's token count shows -next to the send button. While it is on, Enter summarizes the history first, then -sends your message. Click the chip to switch it to **Keep** and keep the full -history for that message. The mobile app shows the same chip, labelled with the -token count: tap it to keep the full history for that message. The cache lasts about an hour on a Claude -subscription and 5 minutes with an API key, Bedrock, or Vertex. See [commands and skills](./composer.md#commands-and-skills) for using -composer commands. - -**Compact idle threads** in **Settings > Providers > Advanced** controls this for threads -over 200,000 tokens. Each Claude provider's settings can override it: - -- **When you return** shows the **Compact** chip described above. This is the default. -- **Before the cache expires (beta)** tries to compact an idle thread shortly before its - prompt cache expires, while the history is still cached. - The compaction appears in the thread as a `/compact` turn sent by T3 Code. - If the window is missed, such as when you enable this mode after the cache has - expired or the server restarts before compaction runs, it falls back to - **When you return**. Switch the chip to **Keep** to keep the full history for that message. -- **Never** skips idle compaction and Claude's resume prompt. **Auto-compact after** - still applies, and you can still compact by hand. - -## Usage limits - -If your Claude subscription runs out of usage mid-turn, the thread shows which -limit was reached and the remaining wait when Claude provides a reset time. -Claude Code holds the turn until that window reopens, so it can keep showing as -working. Wait for the reset, or stop the turn and continue later. The warning's -timestamp shows when the displayed wait started. - -## Steering - -A steer waits until Claude finishes the tool calls it is running, then Claude reads it -in the same turn. The message shows as unread until then. If Claude drops it before -reading it, the message is sent as the next turn, after any messages queued before it. -If Claude exits or the server restarts first, the message waits in the queue in that -same place until you resume it. If you press Stop, T3 Code shows a notice with the text -of any steer Claude had not read. - -## Skills - -Claude skills come from the config directory's `skills` folder and the project's -`.claude/skills` folder. If both define the same name, the config-directory copy -wins. Skills disabled in Claude's settings do not appear in the composer. - -Use `$` in the composer to select a skill. Enabled installed Claude plugins, -and plugins synced from your claude.ai account, also contribute skills under -names such as `plugin:review`. Skills marked `disable-model-invocation` can -still be started by you. Invoke those one per message: Claude directly runs only -the last named skill and may try to start earlier ones through its Skill tool, -which refuses skills reserved for manual invocation. - -## Task lists - -To show Claude task lists in the web and desktop apps, add -`CLAUDE_CODE_ENABLE_TODO_TOOLS=1` under **Variables** in the Claude instance's -**Environment** section in **Settings > Providers**. Each update shows as a Tasks -row in the thread; open it to see every step. - -## Auto mode - -**Auto** on a Claude thread is Claude Code's own auto mode. `disableAutoMode` in Claude's managed, -user, or project settings turns it off: T3 Code then shows **Auto** as unavailable in that project, -and a thread already set to it asks about each action. See [Permission modes](permission-modes.md). - -## Sign in to an MCP server - -When an MCP server you added to Claude needs you to sign in, the thread shows a notice with -**Sign in**, once per session; on mobile, tap the notice. Approve access on the page it opens. Your -browser then goes to a page that may not load, especially when Claude runs on another machine: -copy that page's address, paste it into T3 Code, and choose **Finish sign-in**. Claude keeps the -sign-in and reconnects the server. Connectors you added on claude.ai are signed in on claude.ai, -so T3 Code doesn't ask about them. Signing in needs permission to manage providers. +To use the [Claude in Chrome extension](https://code.claude.com/docs/en/chrome) in T3 Code threads, add `--chrome` to **Launch arguments** in the Claude instance settings (applies to new sessions). Requires a direct Anthropic `/login` plan—not supported with API keys, `setup-token`, Bedrock/Vertex, or WSL. -## Claude in Chrome +## OpenRouter and local routers + +Create a separate Claude instance with its own config directory (e.g. `~/.claude_openrouter`, after running `/logout` if it had a cached Anthropic login) and set **Environment variables**: + +| Variable | Value | +| ---------------------- | ---------------------------------------- | +| `ANTHROPIC_BASE_URL` | `https://openrouter.ai/api` | +| `ANTHROPIC_AUTH_TOKEN` | Your OpenRouter API key (mark Sensitive) | +| `ANTHROPIC_API_KEY` | Explicitly empty | -Claude threads can use the Claude in Chrome extension, which works in your own -Chrome with its sign-ins. T3 Code sessions load it only when asked: add `--chrome` -to **Launch arguments** in the Claude instance's settings in **Settings > Providers**. -It applies to sessions that start after you save. Set up the extension as you would -for Claude Code first; see Claude Code's [Chrome guide](https://code.claude.com/docs/en/chrome). - -The instance must be signed in with `/login` on a direct Anthropic plan. Instances -that use an API key or a `claude setup-token` token don't get it, even with -`--chrome`, and neither do third-party providers such as Amazon Bedrock. Claude Code -doesn't support it in WSL. - -## OpenRouter - -Create a Claude instance with its own config directory, such as -`~/.claude_openrouter`, and keep **Binary path** set to `claude`. In that instance's -**Environment variables**, use: - -| Variable | Value | -| ---------------------- | ----------------------------------------- | -| `ANTHROPIC_BASE_URL` | `https://openrouter.ai/api` | -| `ANTHROPIC_AUTH_TOKEN` | Your OpenRouter API key, marked Sensitive | -| `ANTHROPIC_API_KEY` | An explicitly empty value | - -If that Claude config directory has a cached Anthropic login, run `/logout` in a -Claude Code session using that directory before starting the router setup. Cached -login credentials can conflict with the router token. - -Select the model you want in T3 Code. For an OpenRouter model outside the built-in -list, open that Claude instance in **Settings > Providers** and add its full model -ID with **Add custom model**. Then select it in the chat model picker. -`ANTHROPIC_DEFAULT_*_MODEL` variables map Claude Code aliases such as `sonnet`; they -do not replace the explicit model ID selected in T3 Code. Custom models may have -fewer effort, thinking, or context controls than built-in models. - -Verify the model used in OpenRouter's activity dashboard. For current compatibility -requirements, use the -[OpenRouter Claude Code guide](https://openrouter.ai/docs/cookbook/coding-agents/claude-code-integration). - -## Other routers - -A local router uses an ordinary Claude provider instance. Give it a separate -config directory and put the router's endpoint and credential variables in that -instance's **Environment variables**. The router must run where the environment -can reach it. Follow the [Claude Code Router instructions](https://github.com/musistudio/claude-code-router) -for its installation and routing configuration. +Add unlisted OpenRouter models via **Add custom model** in the instance settings. See the [OpenRouter Claude Code guide](https://openrouter.ai/docs/cookbook/coding-agents/claude-code-integration) or [Claude Code Router](https://github.com/musistudio/claude-code-router) for local router setup. diff --git a/docs/user/providers-codex.md b/docs/user/providers-codex.md index 4b5fe6c33e48d..4e4119382bdbe 100644 --- a/docs/user/providers-codex.md +++ b/docs/user/providers-codex.md @@ -1,178 +1,52 @@ # Codex -Use your ChatGPT plan or an existing Codex CLI login to code in T3 Code. +Use your ChatGPT plan or an existing Codex CLI login to run Codex in T3 Code. ## Connect with ChatGPT -Connect during onboarding or in **Settings → Providers**. For a remote machine, -select that environment first. T3 Code handles Codex installation; sign in on -OpenAI and allow sharing of your ChatGPT plan. +Connect during onboarding or in **Settings → Providers** (select your target environment first for remote machines). T3 Code manages the Codex runtime and signs you in via OpenAI. -Manage shared usage and credits in ChatGPT through **Manage usage** in T3 Code. -If a request uses a feature that ChatGPT sharing does not support, use another -provider for that request. - -Fast and Ultrafast speeds are unavailable with this connection. To use the speed -options your account supports, [use an existing Codex login](#use-an-existing-codex-login). - -When reconnecting, choose the same account in T3 Code and on OpenAI's sign-in -page. Disconnecting stops running threads but keeps their history and lets you -reconnect later. - -If remote sign-in cannot return automatically, paste the full URL from the final -localhost page into the sign-in panel, even if that page could not load. +- Manage shared usage and credits through **Manage usage** in T3 Code. +- **Remote sign-in**: If sign-in doesn't return automatically, paste the full `localhost` redirect URL into the sign-in panel. +- **Speed options**: Fast and Ultrafast speeds are not available through ChatGPT sharing—[use an existing Codex login](#use-an-existing-codex-login) instead. +- Disconnecting stops running threads while preserving history. ## Use an existing Codex login -T3 Code can use your installed Codex and its existing login. Run `codex login` -on the environment's machine to sign in. [Provider setup](./install.md#providers) -covers installation and custom configuration. - -Running `codex login` does not change a managed ChatGPT connection. In -**Settings > Providers**, add a Codex instance, choose **Configure manually**, -and complete the wizard. Then select that instance from the thread's model -picker. See [Use multiple accounts](#use-multiple-accounts). - -## Allow more time for provider checks - -If an authenticated Codex installation reports “Timed out while checking Codex -app-server provider status,” set `T3CODE_CODEX_PROBE_TIMEOUT_MS=60000` in the -T3 server's environment and restart it. See [Provider check timeouts](./install.md#provider-check-timeouts) -for configuration and other providers. - -## Generate images - -Codex can generate images directly in a T3 Code thread when your Codex version, -model, and account support native image generation. - -If Codex reports that its image tool is unavailable, image generation may be -disabled in its configuration. In **Settings → Providers**, edit your existing -Codex provider and add this to **Launch arguments**, keeping any other arguments: - -```text --c features.image_generation=true -``` +Run `codex login` on the environment's machine, then add a Codex instance in **Settings → Providers** via **Configure manually**. See [provider setup](./install.md#providers) for installation details. -This enables the feature for that T3 Code provider without changing your shared -Codex configuration. You do not need another provider instance or a separate image -API key. The flag does not add image support to an unsupported model or account. - -Launch arguments apply to Codex sessions started after you save them. Start a new -thread with the same Codex provider and ask it to generate an image. The completed -image appears in the thread. +If provider status checks time out on a slower machine, set `T3CODE_CODEX_PROBE_TIMEOUT_MS=60000` in the server environment and restart. See [Provider check timeouts](./install.md#provider-check-timeouts). ## Use multiple accounts -Add another ChatGPT account in **Settings → Providers**, then select the account -from the thread's model picker. Compatible accounts can continue the same thread. -Connecting accounts through T3 Code leaves your CLI login unchanged. - -### Multiple CLI logins - -A shared Codex home with a shadow home lets work and personal accounts continue -the same threads. The accounts share Codex sessions and configuration while keeping -their own login and available models. - -Keep your first account in `~/.codex`. On the environment's machine, sign the -second account into a fresh directory: +Add another ChatGPT account in **Settings → Providers**, or configure multiple CLI logins with a **shadow home** so work and personal accounts can continue the same threads: ```bash mkdir -p ~/.codex_personal CODEX_HOME=~/.codex_personal codex login ``` -Then add a second Codex instance in **Settings > Providers**: - | Instance | CODEX_HOME path | Shadow home path | | -------------- | --------------- | ------------------- | -| Codex Work | `~/.codex` | Leave empty | +| Codex Work | `~/.codex` | _(leave empty)_ | | Codex Personal | `~/.codex` | `~/.codex_personal` | -Both instances must use the same **CODEX_HOME path**. T3 Code prepares the shared -state in the shadow directory; do not populate it by copying your whole Codex -home. - -The shadow account needs its own `auth.json` file. If Codex uses an OS credential -store, configure file storage for this setup. See -[OpenAI's credential storage guide](https://learn.chatgpt.com/docs/auth#credential-storage). - -Use a completely separate **CODEX_HOME path**, with no shadow home, when you want -separate Codex sessions and configuration. That instance cannot continue threads -from the other home. - -## Switch accounts in an existing thread - -Choose the other account from the thread's model picker. T3 Code offers compatible -Codex instances that share the thread's **CODEX_HOME path**. Changing accounts does -not move the conversation into a separate Codex home. - -If the account is missing from the picker, compare the home paths in provider -settings. If two instances show the same unexpected account or models, check their -reported accounts, refresh provider status, and confirm the second instance has -its own shadow path and login. A shadow-home conflict usually means the directory -contains a copied Codex setup. Use a fresh shadow directory and sign in again. - -## Answer questions while Codex works - -Codex can ask a question and keep working. Answer it in the thread's question -panel. The answer becomes a new message: it reaches the active turn, or starts -another turn if Codex has finished. Unanswered questions survive reconnects. -If you do not want to answer, dismiss the question from its panel. Dismissing -closes it without sending anything to Codex. This requires a Codex version that -supports async questions. - -## Approve app access - -Codex tools can request access to another app. Respond to the named app's request -in the thread on web, desktop, or mobile. Some tools offer access for one request, -the current session, or permanently. See [Permission modes](./permission-modes.md) -for command and file approvals. - -## Sign in to an MCP server - -When an MCP server you added to Codex needs you to sign in, the thread shows a notice with -**Sign in**; on mobile, tap the notice. Approve access on the page it opens. Your browser then goes -to a page that may not load, especially when Codex runs on another machine: copy that page's -address, paste it into T3 Code, and choose **Finish sign-in**. Codex reconnects the server in that -thread and keeps the sign-in for other threads on the same Codex instance; an instance with its own -home, such as a second account, may need to sign in separately. Signing in needs permission to -manage providers. - -## Use the OpenAI Chrome extension - -Connecting ChatGPT in **Settings → Providers** signs in the Codex provider. -Using your signed-in Chrome profile through the extension requires a browser -connection for the current Codex thread. - -If a T3 Code thread reports `The browser access host is unavailable`, its browser -host is unavailable; this does not identify an extension connection failure. -For a task that requested Chrome, follow [OpenAI's setup guide](https://learn.chatgpt.com/docs/chrome-extension), -then select Chrome in a Codex chat in the ChatGPT desktop app. -If the task runs on a remote environment, `localhost` in the desktop browser -refers to your computer. Forward the remote page's port or use a URL reachable -from your computer before repeating the task. Connecting to T3 Code through a -relay or tunnel does not by itself expose that page. T3 Code's built-in browser -preview uses its own browser session. - -## Use Daybreak - -Models with cyber access programs show a Cyber Access option in the model -options. It starts on Standard, or on Daybreak when `config.toml` in your Codex -home sets `daybreak = true` or the model only runs under Daybreak. Your choice carries -over to new threads. Custom models do not offer it. If Codex rejects a turn -because your login lacks the program, switch Cyber Access back to Standard or -sign in to Codex with an account that has it. - -## Codex says I hit a usage limit - -When Codex stops on a usage limit, the thread names the window that ran out and -when it resets, when Codex reports them. Send the message again after the reset. On a workspace plan the -message also says whether your workspace owner needs to add credits or raise the -spend limit to continue sooner. - -## Send feedback to OpenAI - -In an existing Codex thread, send `/feedback` with an optional description, for -example `/feedback The agent stopped before finishing the tests`. This uploads -the conversation and Codex logs to OpenAI. The returned thread ID can be shared -with OpenAI support. +- Both instances must share the same **CODEX_HOME path**. Keep the shadow directory fresh—don't copy your full Codex home into it. +- The shadow account needs file-based credential storage (`auth.json`); see [OpenAI's credential storage guide](https://learn.chatgpt.com/docs/auth#credential-storage). +- Use a separate **CODEX_HOME path** (no shadow home) if you want completely isolated sessions. + +To switch accounts mid-thread, pick another compatible Codex instance sharing the same **CODEX_HOME path** from the model picker. + +## Features and options + +- **Image generation**: Supported when your Codex version, model, and account allow it. If disabled in Codex config, add `-c features.image_generation=true` to the instance's **Launch arguments** (applies to new sessions). +- **Async questions**: Codex can ask a question while continuing to work; answer in the question panel (steers the active turn or starts a new one) or dismiss it without sending. +- **App access approvals**: Respond to external app access requests directly in chat (one-time, session, or permanent depending on the tool). +- **MCP OAuth sign-in**: Click **Sign in** on the thread notice, approve in your browser, and paste the final redirect URL into **Finish sign-in** (requires provider management permission). +- **Daybreak**: Models with cyber access programs show a **Cyber Access** option (`Standard` or `Daybreak`, initialized from `daybreak = true` in `config.toml`). +- **Usage limits**: Limit stops display the exhausted window, reset time, and (on workspace plans) whether credits or spend limits need adjustment. +- **Feedback to OpenAI**: Send `/feedback ` in an existing Codex thread to upload conversation and Codex logs to OpenAI. + +## OpenAI Chrome extension + +Using your signed-in Chrome profile via [OpenAI's Chrome extension](https://learn.chatgpt.com/docs/chrome-extension) requires a browser connection for the Codex thread. For remote environments, forward the remote page's port or use a reachable URL—T3 Code's built-in preview browser uses its own separate session. diff --git a/docs/user/providers-fx.md b/docs/user/providers-fx.md index e500fac35b3ab..8928626de334a 100644 --- a/docs/user/providers-fx.md +++ b/docs/user/providers-fx.md @@ -1,71 +1,39 @@ # fx -T3 Code can run [fx](https://fx.sh). fx uses the login on the machine that runs the T3 Code server. +Run [fx](https://fx.sh) in T3 Code using the fx login and backends configured on your server machine. Requires **fx 0.0.13+** (macOS 15+ for releases after 0.0.13). -## Set up fx - -1. Install fx on that machine: +## Set up and update +1. Install fx on the server machine: ```bash curl -fsSL https://fx.sh/setup.sh | bash ``` +2. Run `fx login` on that machine. +3. Enable **fx** in **Settings → Providers** and refresh (set **Binary path** if `fx` isn't on `PATH`). -2. Run `fx login` in a terminal on that machine. -3. Open **Settings → Providers**, enable fx, and refresh the provider. - -If `fx` is not on the server's `PATH`, set **Binary path** to the executable. - -T3 Code supports fx 0.0.13 and later. Use the latest release when you can; macOS needs version 15 or later for fx releases after 0.0.13. - -Every fx instance on the same machine shares that machine's fx login. T3 Code does not keep a separate login per instance. - -## Update fx - -When a newer fx release is out, the fx card in **Settings → Providers** shows it. For standalone installs, **Update now** runs the instance's selected executable with `upgrade`, including one set in **Binary path**. For Homebrew's `fx-agent` formula, it uses the owning Homebrew installation to run `brew upgrade fx-agent` and checks Homebrew's release version. If that ownership cannot be confirmed, update through your package manager yourself. For mise-managed installs, T3 Code checks stable releases but leaves updates to your mise configuration. MacPorts and Nix installs are also left to their package manager. - -To update a standalone install manually, run `fx upgrade` on the server's machine. If **Binary path** is set, run that exact executable instead, for example `"/path/to/fx" upgrade`. Standalone version checks cover stable releases only; use the same manual command to get newer dev builds on fx's dev channel. On macOS 14 or earlier, which newer fx releases do not support, T3 Code does not offer fx updates. - -## Backends, models, and effort - -fx can run models through several backends: Vercel AI Gateway, a Codex subscription, a Grok subscription, and any OpenAI-compatible endpoint you configure in fx's settings. In the model picker, the fx tab lists each backend under its own heading. Open a backend to see the models it offers, then pick one. Search lists every backend's models together. - -The backend is part of each thread's model choice, so two threads can run on different backends at the same time. Switching it in T3 Code changes only that thread's fx session. It never changes the default `fx provider` sets for your terminal. - -Sign-ins are different: every fx instance on a machine shares that machine's fx login. A backend you are signed out of shows as unavailable, with the command to run on that machine, such as `fx login grok`. Refresh the provider after signing in. - -**Default** runs whatever fx would start a new session on in the thread's project folder, including a model fx's settings give only that folder. Its label shows the machine-wide default. A custom model you add in the provider settings goes to fx as is, on the thread's current backend, and fx reports an error if that backend does not offer it. - -fx also has an **Effort** control. A new thread starts at Medium. - -Type `$` in the composer to list the skills fx finds in its skill folders, in the order fx's own skill menu shows them. When two different skills share a name, the menu lists the one fx loads for that name: the first copy in fx's folder order, starting with the workspace. The menu shows one skill per name regardless of case; to run a skill whose name differs only in case, such as `Review` next to `review`, type its exact name. - -fx threads load the MCP servers from fx's profile config, `~/.fx/mcp.json`, on the machine that runs the T3 Code server. - -## Permission modes - -| Mode | Behavior | -| --------------- | ----------------------------------------------------------------------------------- | -| **Supervised** | fx asks before it changes files or runs commands. Read requests run without asking. | -| **Auto** | fx handles routine actions itself. Anything it still asks about reaches you. | -| **Full access** | fx runs every action without asking. Needs fx 0.0.14 or later. | - -T3 Code offers **Full access** only when the server's fx reports it. After you upgrade fx, refresh the provider in **Settings → Providers** to see it. On an older fx, or before the provider check finishes, a thread set to **Full access** runs in **Supervised**. - -T3 Code does not offer **Auto-accept edits** for fx. A thread already set to it runs in **Supervised**. Changing the permission mode restarts the connection and reloads the same fx session. +All fx instances on a machine share that machine's fx login. -On fx 0.0.14 and later, fx saves the mode T3 Code sets as its default permission mode. T3 Code sets it each time it opens an fx thread, so fx in the terminal then starts in that thread's mode. +- **Updates**: Click **Update now** in **Settings → Providers** for standalone (`fx upgrade`) or Homebrew (`fx-agent`) installs. Update mise, MacPorts, Nix, or dev-channel installs manually. -A message steered into a running turn stops that turn, and fx answers the new message in the same session. +## Backends, models, skills, and MCP -## Sub-agents +- **Backends**: fx supports Vercel AI Gateway, Codex, Grok, and custom OpenAI-compatible endpoints. Each backend appears under its own heading in the model picker; switching backends applies per thread without changing your terminal's `fx provider` default. Signed-out backends show their login command (e.g. `fx login grok`). +- **Default model & effort**: **Default** uses fx's configured default for that project folder. **Effort** defaults to Medium. +- **Skills & MCP**: Type `$` to invoke skills discovered by fx (case-insensitive deduplication; type exact case if two skills differ only in casing). MCP servers load from `~/.fx/mcp.json`. -When fx hands work to a sub-agent, it opens in its own thread under the parent. That thread shows the sub-agent's task and its reply, which fx shortens to a couple of lines. fx doesn't share the sub-agent's individual steps. +## Permission modes and steering -fx doesn't pass on a sub-agent's permission requests, so a sub-agent that needs one waits until you press **Stop**. This mostly happens in **Supervised**. In **Auto**, sub-agents can finish routine work by themselves. +| Mode | Behavior | +| --------------- | -------------------------------------------------------------------------------------------- | +| **Supervised** | Asks before edits and commands; reads proceed without asking. | +| **Auto** | Handles routine actions automatically; forwards remaining prompts to you. | +| **Full access** | Runs all actions without asking (requires **fx 0.0.14+**; refresh provider after upgrading). | -## Not supported yet +- **Auto-accept edits** is not supported (falls back to Supervised). Changing modes reloads the fx session. +- On fx 0.0.14+, setting a mode in T3 Code also updates fx's saved default permission mode. +- Steering into a running turn stops that turn and answers the new message in the same session. -- **Auto-accept edits**. -- Commit messages, pull request text, branch names, and thread titles. Pick another provider for those. +## Sub-agents and limitations -See [provider setup](./install.md#providers) and [Permission modes](./permission-modes.md). +- **Sub-agents**: Shown as child threads with their task and summarized reply (individual steps are hidden). fx does not forward sub-agent permission prompts—use **Auto** or **Full access** so sub-agents don't stall waiting for approval. +- **Not supported**: **Auto-accept edits**, and T3 Code text generation (titles, commit messages, PR descriptions, branch names)—pick another provider for those. diff --git a/docs/user/providers-grok.md b/docs/user/providers-grok.md new file mode 100644 index 0000000000000..8a3088f74e63f --- /dev/null +++ b/docs/user/providers-grok.md @@ -0,0 +1,26 @@ +# Grok Build + +Run xAI's [Grok Build CLI](https://x.ai/cli) in T3 Code using your xAI subscription or `XAI_API_KEY`. + +## Set up Grok Build + +1. Install the Grok Build CLI (`@xai-official/grok`) on the machine running your T3 Code server. +2. Authenticate on that machine: + - Run `grok login` (or `grok login --device-auth` on a headless/remote host), **or** + - Set `XAI_API_KEY` in the Grok instance's **Environment** settings. +3. Open **Settings → Providers**, enable **Grok Build**, and refresh. Set **Binary path** if `grok` isn't on the server's `PATH`. + +- **Multiple accounts**: Use a separate `GROK_HOME` environment variable per provider instance to isolate logins and usage. +- **Updates**: In-app updates follow your install method (standalone script, Homebrew, mise, or Nix—update Nix and pinned installs via their package manager). + +## Capabilities and limits + +- **Models & options**: Discovers models and reasoning effort levels from Grok Build. Add unlisted models under **Custom models**. +- **Permission modes**: Supports **Supervised**, **Auto** (Grok reviews routine actions and forwards remaining approvals to you), and **Full access**. **Auto-accept edits** is not supported (runs as Supervised). File approvals offer session-wide allow; command approvals are per-request. +- **Skills**: Grok skills appear in the composer's `$` menu. +- **Usage & limits**: Subscription limits under **Usage → Limits** require `grok login` (not `XAI_API_KEY` or custom endpoints). Usage totals only include turns with saved completed-turn records. +- **Not supported**: Conversation rewind (**Edit from here**) and the Plan interaction mode toggle. + +## Troubleshooting + +- **Provider check timeouts**: Startup checks in large directories can take 9–14 seconds. If discovery times out, set `T3CODE_GROK_PROBE_TIMEOUT_MS=60000` in the server's environment and restart ([Provider check timeouts](./install.md#provider-check-timeouts)). diff --git a/docs/user/providers-kiro.md b/docs/user/providers-kiro.md index 6b94ca14f2e5e..831588a29f532 100644 --- a/docs/user/providers-kiro.md +++ b/docs/user/providers-kiro.md @@ -1,60 +1,29 @@ # Kiro -T3 Code runs the [Kiro CLI](https://kiro.dev/docs/cli/) as an agent, using your own Kiro account, -custom agents, steering, hooks, and MCP configuration. +Run the [Kiro CLI](https://kiro.dev/docs/cli/) (V3 engine) in T3 Code with your Kiro account, custom agents, steering, hooks, and MCP config. -## Set Up Kiro +## Set up Kiro -1. Install the Kiro CLI on the machine running the T3 Code server. On macOS or Linux, run - `curl -fsSL https://cli.kiro.dev/install | bash`. On Windows 11, run - `irm 'https://cli.kiro.dev/install.ps1' | iex` in PowerShell. Kiro's - [installation guide](https://kiro.dev/docs/getting-started/installation/) lists other options. -2. Run `kiro-cli login` once in a terminal. Kiro Pro and higher plans can instead set an API key as - `KIRO_API_KEY` in the Kiro provider's environment variables. -3. Open **Settings → Providers**, enable Kiro, and refresh it. +1. Install the Kiro CLI on the server machine: + - macOS / Linux: `curl -fsSL https://cli.kiro.dev/install | bash` + - Windows 11 (PowerShell): `irm 'https://cli.kiro.dev/install.ps1' | iex` +2. Run `kiro-cli login` (or set `KIRO_API_KEY` in the instance's environment variables on Kiro Pro+). +3. Open **Settings → Providers**, enable **Kiro**, and refresh. Set **Binary path** if `kiro-cli` (typically `~/.local/bin`) isn't on `PATH`. -If `kiro-cli` is not on the server's `PATH`, set its **Binary path**. On macOS and Linux, the -installer usually puts it in `~/.local/bin`. T3 Code starts Kiro's CLI V3 engine, so a Kiro CLI -that cannot run V3 will not start. +## Models and custom agents -## Models +- **Models**: Listed from your signed-in Kiro account (defaults to `auto` unless your account/org sets another). Supported models expose a **Reasoning** effort selector. +- **Custom agents**: Pick built-in agents (e.g. Spec, Plan) or user agents from `~/.kiro/agents` in the **Agent** selector next to the model (refresh provider after adding/removing agents). Project `.kiro/agents` are not listed yet. The thread's model takes precedence over an agent's `model` field. -The model picker lists the models your Kiro account can use once Kiro is signed in. New threads -start on your Kiro default model: `auto`, which lets Kiro choose, unless your account or -organization sets another. A model your account cannot use stops the turn with an error instead of -running on another model. +## Permission modes -Models with adjustable reasoning effort, such as recent Claude Opus and Sonnet models and GPT-5.6, -show a **Reasoning** setting with only the levels Kiro offers for that model. Your default model and -models without effort control run at Kiro's own setting. +- **Supervised**: Prompts for writes and commands, disables Kiro Autopilot, and asks you to review file changes at the end of a turn. +- **Full access**: Approves tool calls automatically with Autopilot on. -## Agents +**Auto** and **Auto-accept edits** are not supported. Kiro's **Always allow** (which persists workspace-wide) is only shown when Kiro offers no one-time option. -The **Agent** setting next to the model picks the -[Kiro agent](https://kiro.dev/docs/custom-agents/) a thread runs as: Kiro's built-in agents such as -Spec and Plan, and your own agents in `~/.kiro/agents`. Agents in a project's `.kiro/agents` are -not listed yet. Refresh the Kiro provider after adding or removing an agent. +## Steering, forks, and compaction -The thread's model still applies when an agent sets its own `model`. An agent that was removed -leaves the thread on Kiro's current agent. - -## Permission Modes - -Kiro asks before tool calls such as writes and commands, and T3 Code answers by the permission mode: - -- **Supervised** sends those requests to you. Kiro's Autopilot is off, so Kiro also asks you to - review the turn's file changes before it finishes. -- **Full access** approves them without asking you. Autopilot stays on, so there is no review step. - -Kiro offers no **Auto** or **Auto-accept edits**. Approvals offer only the choices Kiro sends. Kiro's -**Always allow** saves a rule for the whole workspace, so T3 Code shows it only when Kiro offers no -one-time choice. - -## Steering, Forks and Compaction - -- A message you send while Kiro is working joins the running turn. Kiro reads it once its current - step or tool call finishes. A message with images stops the turn and starts a new one with it. -- Forking a thread from a message gives the fork Kiro's own copy of the conversation up to that - message. -- `/compact` uses Kiro's own compaction. Kiro also compacts on its own as the conversation fills its - context. +- **Steering**: Text follow-ups join the running turn after the current step; messages with images restart the turn. +- **Forking**: Uses Kiro's native conversation copy up to the selected message. +- **Compaction**: Supports `/compact` as well as Kiro's automatic compaction. diff --git a/docs/user/providers-muse.md b/docs/user/providers-muse.md index df506e678bcc1..fd2734eb4dfc7 100644 --- a/docs/user/providers-muse.md +++ b/docs/user/providers-muse.md @@ -1,66 +1,22 @@ # Muse Code -Muse Code is disabled by default. Install -[Muse Code](https://dev.meta.ai/docs/muse-code) on the machine hosting your -environment, then run `muse login` as the account that runs T3 Code. +Run [Muse Code](https://dev.meta.ai/docs/muse-code) on your T3 Code server. Muse Code is disabled by default. -Open **Settings → Providers** in the web or desktop app, select the environment, -and enable **Muse Code**. Set **Binary path** if Muse is not on the host's `PATH`. -Refresh provider status after installation or login, then select Muse in a -thread's model picker. +## Set up Muse Code -Provider status does not check your login. If you are signed out, messages -fail until you run `muse login` on the host. +1. Install Muse Code on the server machine and run `muse login` as the user running T3 Code. +2. Open **Settings → Providers**, select the environment, enable **Muse Code** (set **Binary path** if not on `PATH`), and refresh provider status. -## Sign-in and API keys +> Note: Provider status does not verify login—if you are signed out, turns fail until you run `muse login` on the host. -T3 Code ignores a `META_API_KEY` that the T3 server inherits from its own -environment, so Muse uses the credential saved on the host by `muse login`. To -use an API key instead, add `META_API_KEY` to the Muse instance's environment -variables in **Settings → Providers**. Muse gives that key priority over the -saved login. +- **API key**: T3 Code ignores inherited server `META_API_KEY`. To bill an instance via API key instead of `muse login`, add `META_API_KEY` in that instance's **Environment** settings (overrides the saved login). +- **Multiple instances**: Instances on the same host share `muse login` unless given their own `META_API_KEY`. +- **Updates**: In-app updates work when T3 Code recognizes the Muse launcher; otherwise update Muse on the host manually. -## Remote access and instances +## Models, permissions, and limitations -Connect from web, desktop, or mobile through [remote access](./remote-access.md). -Muse uses the selected environment's files and login; connecting devices do not -need Muse installed. Install and sign in separately on each host where you want -Muse to run. - -Add a provider instance for a separate configuration. Instances on the same host -share its Muse login; give an instance its own `META_API_KEY` to bill it -separately. Existing conversations retain their instance when its model catalog -becomes unavailable. - -## Models - -Models and reasoning choices come from Muse on the selected host. After changing -Muse configuration, refresh provider status in **Settings → Providers**. On -mobile, pull down in thread settings to refresh models. If a saved model becomes -unavailable, select an available model before sending another message. - -Muse can list models that your account cannot use. If a message fails with -"does not exist or you lack access", pick another model, or add one your account -can use under **Custom models** in the instance settings. - -## Permissions and limitations - -Muse offers two [permission modes](./permission-modes.md): **Supervised** asks -before commands and edits, and **Full access** runs them without asking. Muse has -no equivalent of **Auto-accept edits** or **Auto**, so they are not offered. - -Muse can use T3 Code's tools. If Muse cannot reach them, the turn continues -without them. Switching providers can pass conversation context as a handoff. - -Muse skills do not appear in the composer's `$` menu. Muse still loads them -itself. Manage them with `muse skills` on the host. - -Forking a Muse conversation starts a new session with a copy of the conversation -context. Conversation rewind is unavailable. - -Install Muse and sign in on the host; in-app installation and sign-in are not -available. Updates can run from **Settings → Providers** when T3 Code recognizes -the Muse launcher; otherwise update Muse on that host manually. - -To stop using Muse in an environment, disable it in **Settings → Providers**. -This keeps the host's Muse login, thread history, and workspace files. +- **Models**: Reported by Muse on the host (refresh provider status after config changes). If a listed model fails with an access error, pick another or add an allowed ID under **Custom models**. +- **Permission modes**: Supports **Supervised** and **Full access** only (**Auto** and **Auto-accept edits** are unavailable). +- **Skills**: Muse loads its own skills (`muse skills` on the host); they do not appear in the composer's `$` menu. +- **Forks & rewind**: Forking starts a new session with copied conversation context; conversation rewind is not supported. +- **T3 tools**: Muse can use T3 Code's MCP tools when reachable (turns continue without them if unavailable). diff --git a/docs/user/providers-opencode.md b/docs/user/providers-opencode.md index da8d14d4a6cf7..37a9f79cf9cf1 100644 --- a/docs/user/providers-opencode.md +++ b/docs/user/providers-opencode.md @@ -1,93 +1,22 @@ # OpenCode -Install and authenticate OpenCode on the machine running your environment, then -enable it in **Settings > Providers**. See [provider setup](./install.md#providers). -T3 Code requires OpenCode 1.14.19 or newer, including when you connect an existing -OpenCode server. +Run OpenCode **1.14.19+** or **OpenCode 2.0.18+** in T3 Code. Install and authenticate OpenCode on the server machine, then enable it in **Settings → Providers** (see [provider setup](./install.md#providers)). -## OpenCode 2 +## OpenCode 1.x vs. 2.x -T3 Code supports OpenCode 2.0.18 and newer. It detects the version on its own, so -the same provider settings work for OpenCode 1.x and 2.x. OpenCode 1.x shows -**Limited support** in its provider settings. +T3 Code detects your installed version automatically. OpenCode 1.x has **Limited support**. -OpenCode 2 is a separate package, `@opencode/cli`. To move from 1.x, install it -yourself, for example `npm install -g @opencode/cli`. Then refresh provider status. -T3 Code's update button updates whichever package you have installed. It never -switches a 1.x install to 2.x. - -OpenCode 2 converts the shared OpenCode database to its own format the first time it -runs. Don't run OpenCode 1.x and 2.x side by side on the same machine. Threads you -started on 1.x continue on 2.x. - -## Compaction - -OpenCode compacts long conversations itself, and T3 Code has no setting for it. On -OpenCode 2, change it under `compaction` in an OpenCode configuration file, such as -`opencode.json`: `auto` turns -automatic compaction on or off, `buffer` sets the token headroom, and `keep.tokens` -sets how much recent context stays. OpenCode 1.x configures compaction differently. -Send `/compact` to compact a thread yourself. +- OpenCode 2 ships as a separate package (`@opencode/cli`, e.g. `npm install -g @opencode/cli`). T3 Code's update button upgrades your installed package without switching 1.x to 2.x. +- Do not run 1.x and 2.x side by side on the same machine—OpenCode 2 converts the shared database on first run. Existing 1.x threads continue on 2.x. ## Local or external server -Leave **Server URL** empty to let T3 Code start OpenCode locally. A password in -provider settings applies to both that server and T3 Code's connection. With no -password setting, the local server uses `OPENCODE_SERVER_PASSWORD` from its -environment, and with neither T3 Code generates a password for it. - -To use an existing OpenCode server, set **Server URL** and its password in provider -settings. T3 Code uses only that configured password for an external server; it -does not forward a local `OPENCODE_SERVER_PASSWORD`. If connection or version checks -fail, check the URL, credentials, and OpenCode version, then refresh provider status. - -When **Server URL** points to a locally running server (such as `127.0.0.1`), -the update button upgrades its installed CLI. If that server is this machine's -OpenCode background service, T3 Code then restarts it on the new version. The URL -must use the service's own protocol, host, and port. For a service listening on -`0.0.0.0` use `127.0.0.1`, and for `[::]` use `[::1]`. - -Restarting interrupts running turns, and the service then runs with T3 Code's -environment. Set any variables it needs with `opencode service set env `. - -T3 Code does not restart any other server, including the background service -reached through `localhost`. That server can still report the previous version -until you restart it. For a loopback URL, T3 Code shows that restart requirement -instead of treating the CLI update as a failure. - -T3 Code waits for a local server it started to recover after a lost connection. -You can stop the turn while it reconnects. If the server exits or an external -connection cannot be restored, send another prompt to resume the same OpenCode -session. - -## Approvals - -OpenCode follows the shared [permission modes](./permission-modes.md). **Auto** has -the same rules as **Supervised** because OpenCode has no AI approval reviewer. -Environment files such as `.env` and `.env.local` need approval in restricted -modes even though normal file reads do not; `.env.example` is allowed. - -**Allow for workspace** applies to matching requests in other OpenCode sessions -using the same workspace. It is broader than the current thread, especially on a -shared external server. Use **Allow once** for a single request. Denying an action -does not stop the whole turn. - -## Refresh models, commands, and skills - -After changing an OpenCode login or configuration, use **Refresh provider status** -in **Settings > Providers** for that environment. On mobile, use **Refresh models** -in the thread settings. Reconnecting also refreshes the catalog; periodic provider -health checks do not. - -Credential changes are read on refresh. Native OpenCode configuration can remain -cached while the local helper is running. Let it sit for 30 seconds without model -refreshes or text-generation work, then refresh again to reload the files. Repeated -refreshes keep the helper alive. An external server may need its own reload or -restart before T3 Code can see configuration changes. +- **Managed local server** (default): Leave **Server URL** empty. Uses your configured password, `OPENCODE_SERVER_PASSWORD`, or a generated password. +- **External server**: Set **Server URL** and password in provider settings (does not forward local `OPENCODE_SERVER_PASSWORD`). +- **Updating a local service**: When **Server URL** points to a local OpenCode background service (using its exact host/port—`127.0.0.1` for `0.0.0.0`, `[::1]` for `[::]`, not `localhost`), T3 Code upgrades the CLI and restarts the service (interrupting active turns; configure service env vars with `opencode service set env `). Other external servers must be restarted manually. -Models defined in a project's own `opencode.json` appear only in that project's -model picker, after T3 Code reads the project's catalog the first time the picker -opens there. +## Compaction, approvals, and catalog refresh -Existing threads keep their selected model and options even when it disappears -from the catalog. If OpenCode rejects that model, select an available one and retry. +- **Compaction**: Send `/compact` manually, or configure `compaction` (`auto`, `buffer`, `keep.tokens`) in `opencode.json` on OpenCode 2. +- **Approvals**: Follows [permission modes](./permission-modes.md); **Auto** behaves like **Supervised**. Reading `.env` / `.env.local` asks for approval in restricted modes (`.env.example` is allowed). **Allow for workspace** applies across all OpenCode sessions sharing that workspace—use **Allow once** on shared servers. +- **Refreshing config**: Click **Refresh provider status** (web/desktop) or **Refresh models** (mobile) after auth/config changes. Local helper caches clear after 30 seconds of inactivity; external servers may need a restart. Project-specific models in `opencode.json` load when opening that project's model picker. diff --git a/docs/user/providers-pi.md b/docs/user/providers-pi.md index b434250e9a12d..e86267c490410 100644 --- a/docs/user/providers-pi.md +++ b/docs/user/providers-pi.md @@ -1,94 +1,33 @@ # Pi -T3 Code can use your existing Pi coding agent installation while keeping Pi's models, auth, -extensions, skills, context files, and native session history. +Run your existing [Pi](https://pi.dev) (**0.84.3+**, Node.js **22.19+**) installation in T3 Code while keeping Pi's models, auth, extensions, skills, and native session history. -## Set Up Pi +## Set up Pi -1. Install [Pi](https://pi.dev) on the machine running the T3 Code server. Pi requires Node.js - 22.19 or newer; its platform installers can install Node if needed. T3 Code supports Pi - 0.84.3 or newer. -2. Run `pi` in a terminal, then `/login` to connect your model provider or configure its API key. -3. Open T3 Code Settings, enable Pi, and refresh the provider. +1. Install Pi on the server machine (via Pi's installer or `npm install -g --ignore-scripts @earendil-works/pi-coding-agent`). +2. Run `pi` and `/login` in a terminal on the server (over SSH for remote hosts, or set your model provider's API key in the Pi instance's environment variables). +3. Open **Settings → Providers**, enable **Pi**, and refresh. Set **Binary path** if `pi` isn't on `PATH`. -For an npm installation, use: +- In **Launch arguments**, `--provider` must be paired with `--model`. Flags that alter Pi's execution mode or session selection are rejected because T3 Code manages them. +- Update installer-managed Pi with `pi update`, or via your package manager (e.g. `nix profile upgrade pi`). -```sh -npm install -g --ignore-scripts @earendil-works/pi-coding-agent -``` +## Features and extensions -If `pi` is not on the server's `PATH`, set Pi's binary path to the executable. Provider environment -variables and launch arguments are also available for installations that need a custom agent -directory, endpoint, or model configuration. `--provider` must be paired with `--model`. T3 Code -rejects launch arguments that change Pi's execution mode or select a session because T3 owns those -parts of the process lifecycle. +- **Models, thinking & speed**: Discovers Pi models, thinking levels, and `serviceTiers` (exposed as a speed picker). +- **Native sessions**: Resume, rollback, and same-instance forks use Pi's native session files; switching providers uses a [portable handoff](./portable-handoffs.md). +- **Skills & extensions**: Pi user and trusted project skills appear in `$`. Extension `select`, `confirm`, `input`, and `editor` dialogs render in the composer, notifications appear in the activity log, and status text appears near the composer. +- **Subagents**: T3 Code's `delegate_task` creates full child threads; Pi's example `subagent` extension also displays task progress/results (read-only). -On a remote or headless server, connect to that machine over SSH and run `pi`, then `/login`. -Open the authorization URL on your own computer. If the callback cannot reach the server, -paste the final redirect URL or authorization code back into Pi when prompted. You can also -set your model provider's API-key environment variable in the Pi instance's settings; mark -secret values as sensitive. +## Permission modes -Update installer-managed Pi with `pi update`. If another package manager owns the installation, -update it through that manager instead. For example, a Nix profile installation uses -`nix profile upgrade pi`. +- **Supervised**: Asks before commands, file edits, and extension tools (reads proceed). +- **Auto-accept edits**: Allows Pi's edit/write tools; asks for commands and extension tools. +- **Full access**: Allows all tool calls without prompts. -## What Carries Over - -T3 Code discovers the models reported by Pi and exposes their supported thinking levels. The -thinking picker marks the discovered active model's configured level as its default without -overriding it. Other models keep their Pi defaults when no level is selected. A model that lists -`serviceTiers` (for example `[{ "id": "priority", "name": "Fast" }]`) in its Pi definition gets -a speed picker with Standard plus those tiers. A chosen tier is sent as the request's -`service_tier`; Standard sends none and leaves the endpoint's default. Threads -use Pi's native session files for resume, rollback, and forks within the same Pi instance. Forks -preserve the native conversation through the selected turn in the destination workspace. -Switching providers uses portable conversation context. Extension -dialogs appear in the T3 Code composer, and the thread details context window follows Pi's own usage -reporting while a response streams and after it settles. - -Pi skills appear in the composer's `$` menu. This includes user skills and project skills that Pi -loads for the current workspace; selecting one uses Pi's native skill expansion. - -Pi loads its normal user extensions, and project extensions once the folder is trusted in Pi. -Blocking `select`, `confirm`, `input`, and `editor` dialogs work in T3 Code. Notifications appear in -the work log. Extensions can publish status text near the composer. Terminal titles and generic -widgets do not have a T3 Code equivalent. - -## Permission Modes - -T3 Code applies the composer permission mode through Pi's blocking tool hook: - -- **Supervised** asks before commands, file changes, and extension tools. Read-only tools continue. -- **Auto-accept edits** allows Pi's edit and write tools, but asks before commands and extension - tools. -- **Full access** allows tools without T3 Code approval prompts. - -The **Auto** option is not shown for Pi because Pi does not expose an AI approval reviewer. -Threads that already stored Auto before Pi support was added behave and display as Supervised. - -Changing the mode restarts the Pi provider session and resumes the same native conversation. The -policy covers Pi tool calls; it is not an operating-system sandbox, and code that a trusted Pi -extension runs outside a tool call remains governed by Pi's own extension trust model. - -T3 Code's `delegate_task` tool creates durable child threads in the shared subagent UI. If the user -installs Pi's example `subagent` extension, T3 Code also shows its task progress and results in that -UI. Pi runs those children without a session, so they cannot be opened or resumed as T3 Code -threads. +**Auto** is not supported (behaves as Supervised). Changing modes restarts the Pi session and resumes the same conversation. Note that permissions govern Pi tool calls—not an OS sandbox. ## Troubleshooting -- If Pi is unavailable, confirm that the configured binary runs on the server machine, then refresh - the provider in Settings. -- If no models appear, open Pi directly and confirm its authentication and model configuration. -- If discovery cannot complete, T3 Code keeps Pi available with the `Pi default` model. Start a - thread to let the interactive Pi session handle any startup prompt. -- If Pi skips project settings, extensions, skills, prompts, MCP servers, or system prompt files - because the folder is not trusted, the thread shows a notice on the first turn of the Pi session. - Run the configured Pi binary in that folder on the server machine, using the same provider - environment, including `PI_CODING_AGENT_DIR` if set. Trust the folder or its parent with `/trust`, - then start a new thread using that same worktree. Launch arguments with `--no-approve` keep - project files off without the notice. -- To see context usage on web and desktop, turn on **Context window** in **Settings → Appearance → - Thread details**. It appears once Pi reports usage for the thread. Some model providers only - report usage when a response completes, so it can wait for the first reply. +- **Untrusted project folder**: If Pi skips project extensions/skills/MCP, run `pi` in that folder on the server (with the same `PI_CODING_AGENT_DIR` if set), run `/trust`, and start a new thread in that worktree. Add `--no-approve` to launch arguments to keep project files disabled without the notice. +- **Discovery fails**: T3 Code keeps Pi usable with `Pi default` so an interactive session can handle startup prompts. +- **Context window**: Enable **Settings → Appearance → Thread details → Context window** (some model providers report usage only after the first reply completes). diff --git a/docs/user/question-attachments.md b/docs/user/question-attachments.md index de05ee75c58e9..ceeebd0b46ef6 100644 --- a/docs/user/question-attachments.md +++ b/docs/user/question-attachments.md @@ -1,9 +1,14 @@ # Files in question answers -When an agent asks a question that accepts a custom answer, use **Attach files** or paste an image into the answer field. On mobile, use the attachment button to choose photos or files. You can send a file by itself, with a selected option, or with a typed answer. +When an agent asks a question that accepts a custom answer, you can attach files or paste images alongside (or instead of) a typed response. -Each question keeps its own attachments as you move between questions. Your normal prompt draft stays separate. Wait for uploads to finish before submitting; retry or remove any failed upload. A failed response keeps the draft available to try again. +- **Web and desktop**: Click **Attach files** or paste an image into the answer field. +- **Mobile**: Tap the attachment button to choose photos or files. -Files upload to the environment running the thread, including remote environments. The agent receives paths to those saved files with your answer and can open them with its available tools. Questions that only accept predefined choices do not offer attachments. Older servers need updating before this option appears. +## Behavior and limits -Submitted attachments remain in the thread history. Reverting a thread removes attachments belonging to discarded answers; deleting the thread uses the same file cleanup as other attachments. You can attach up to 100 files across one set of answers, using the same file and total image size limits as the normal composer. +- **Limits**: Up to 100 files across one set of answers, with the same per-file and image size limits as the [composer](./composer.md#attach-files). +- **Per-question drafts**: Each question keeps its own attachments while you move between questions, separate from your main composer draft. Wait for uploads to finish before submitting. +- **How the agent sees them**: Files upload to the thread's environment (including remote environments), and the agent receives their saved file paths with your answer. +- **Availability**: Only shown for questions that accept custom text (not fixed-choice-only questions). Requires an up-to-date server. +- **Cleanup**: Submitted attachments stay in thread history and are cleaned up when you revert past or delete the thread. diff --git a/docs/user/remote-access.md b/docs/user/remote-access.md index 378ec90d28ef5..8b1a2df162aea 100644 --- a/docs/user/remote-access.md +++ b/docs/user/remote-access.md @@ -1,691 +1,101 @@ # Remote access -Connect a phone, browser, or another desktop app to T3 Code running on a different -machine. That machine must stay running and reachable while you work. +Drive T3 Code from your phone, browser (`app.t3.codes`), or another desktop app while your agents run on a host computer or server. The host must stay awake and running while you work. -## T3 Connect +## T3 Connect (recommended) -T3 Connect makes an environment available to your other devices without setting -up router forwarding. In the desktop app on the host, open **Settings → -Sharing & access**, sign in, and enable **T3 Connect** for that environment. +T3 Connect links your host to your other devices without router port-forwarding. -For a command-line host, run: - -```bash -t3 up -``` - -It asks how your other devices reach the machine: T3 Connect, the local network, -or both. Choose T3 Connect and follow the sign-in instructions. It then runs -T3 Code as a [background service](./background-service.md). -`t3 connect` is the same as `t3 up --connect`. Run `t3 up` again to change your -choice, and `t3 status` to see it. - -Instead of the background service, you can keep the desktop app running with -its local environment enabled. Closing the desktop app's last window stops its -local server. Saving your sign-in alone does not start a server or make the -machine reachable. - -On your other device, sign in to the same T3 Connect account and choose the -environment. On the app.t3.codes home page with no computer added yet, signing -in adds compatible computers linked to your account. Over SSH, the CLI prints a -browser link and a short code. Open the link on any device, confirm the code -matches, and approve. The CLI continues on its own, so you do not need to forward -an OAuth callback port. - -T3 Connect renews access credentials when needed without disconnecting a healthy -connection. Pull request diffs and provider settings keep working after the -previous credential expires. A failed renewal affects that request; it does not -disconnect an otherwise healthy conversation. +- **Desktop host**: Open **Settings → Sharing & access**, sign in, and turn on **T3 Connect** (note: closing the desktop app's last window stops its local server—use the [background service](./background-service.md) for unattended access). +- **CLI / headless host**: Run `t3 up` (or `t3 connect` / `t3 up --connect --lan --yes` for non-interactive scripts) and complete the printed sign-in link on any device. Check status with `t3 status [--json]`. +- **Other devices**: Sign in to the same T3 Connect account and pick the environment. ### Approve new devices -By default, any device signed in to your T3 Connect account can open a linked -machine. To require approval instead, turn on **Require approval for new -devices** with the T3 Connect settings in **Settings → Sharing & access** on the -host, or when you first set up T3 Connect. Then someone who takes over your T3 -Connect account cannot reach the machine from a new device without your -approval. Review the devices that are already approved, described below. - -A new device waits and shows a code such as `K7QM-2XFD`. Approve it from a -device that is already connected, using the prompt or **Settings → Sharing & -access**. Check that the code matches the one on the waiting device. On a -headless host, run `t3 auth connect-device list` and then -`t3 auth connect-device approve K7QM-2XFD`. A request expires after 10 minutes, -and the device asks again when it retries. Deny keeps that device out until its -request expires. - -Each device is approved once. Revoke it from **T3 Connect devices** in the same -settings page, or with `t3 auth connect-device revoke `. With approval on, -it has to ask again. With approval off, it can connect again on its own, so -revoking in the app offers to turn approval on first. Devices that connected through T3 Connect while approval was off stay -approved and appear in that list for you to review. A device that has not -connected since you updated T3 Code asks for approval like a new one. Older apps -cannot show the code, so update them before you turn approval on. - -### Scripts and agents - -`t3 up` asks nothing when you name a choice: `--connect`, `--lan`, or their -`--no-` forms. Choices you do not name keep their settings, and `--yes` takes -the defaults. Without a terminal: - -- T3 Connect sign-in prints a URL and a code. Approve it on any device. -- A needed restart runs without asking, and stops running agent turns. -- With nothing set up and no choice named, `t3 up` stops and names the flags. - -`t3 status --json` prints the settings. `t3 up --help` lists every flag with -examples. +By default, any device signed into your T3 Connect account can connect. Turn on **Require approval for new devices** in **Settings → Sharing & access** on the host so new devices must present a short code (valid 10 minutes) that you approve from an existing device or via `t3 auth connect-device approve `. Revoke devices anytime in **Settings → Sharing & access** or `t3 auth connect-device revoke `. ### More machines with T3 Chat -Each T3 Connect account can link up to 3 machines. Phones and browsers do not -count. A paid T3 Chat plan raises the limit to 10 machines with Pro, or 100 with -Premier. - -To link T3 Chat, open your account menu on the web or desktop app, go to -**T3 Chat**, and select **Link T3 Chat**. Sign in to T3 Chat in the window that -opens and approve. The new limit applies the next time you add a machine. If you -cancel or downgrade T3 Chat, machines you already linked stay linked, but you -cannot add more until you are under the limit again. +Free T3 Connect accounts can link up to **3 host machines** (phones and browsers don't count). Link a paid T3 Chat account from your account menu → **T3 Chat → Link T3 Chat** to raise the limit to **10** (Pro) or **100** (Premier). ## Pair over a LAN or private network -Use direct pairing when the other device can reach the host's network address. - -On a desktop host, open **Settings → Sharing & access**, enable **Network access**, -then create a pairing link using an address the other device can reach. Changing -network access restarts the desktop app. You can turn it off in the same place. - -For a command-line host, choose the local network in `t3 up`, or run: - -```bash -t3 up --lan -``` - -For a server in a terminal, run `t3 serve --lan`. Either way, T3 Code then -accepts connections from your local network and tailnet, so a pairing code is -all that keeps other devices on them out. - -If a server is already running, generate a fresh link without restarting it: - -```bash -t3 pair -``` - -Scan the QR code on your phone or paste the pairing URL into **Add environment** -in the receiving app. Connection settings are under **Settings → Environments** -on web and desktop and **Settings → Environments** on mobile. A loopback address -such as `127.0.0.1` reaches only the device opening the link. - -On a computer with the desktop app, you can open the printed `t3code://pair` -app link instead. The desktop app asks you to confirm the server address, then -adds it. - -If your HTTPS endpoint uses a certificate from your own certificate authority, -install that CA on Android as a **CA certificate** in its security settings; the -Android app then trusts it. - -Pairing authorizes that device for future connections. Use a fresh one-time link -for each new device; you do not need the original token to reconnect. A device -stays signed in while you keep using it, until you revoke it in **Settings → -Sharing & access** on the host. One unused for 30 days, or paired with a host -older than this release, has to pair again. Links -created in Settings can only be copied from the client that created them while -its Sharing & access page stays open. If you leave or reload that page, create -another link to share. +- **Desktop host**: Enable **Settings → Sharing & access → Network access** (restarts desktop) and create a one-time pairing link. +- **CLI host**: Run `t3 up --lan` (background service) or `t3 serve --lan` (foreground), then run `t3 pair` to generate a QR code / pairing URL (`t3code://pair` opens directly in the desktop app). +- **Hosted web app (`app.t3.codes`)**: Requires an HTTPS endpoint (T3 Connect or Tailscale HTTPS). For plain HTTP on a LAN, open the direct pairing URL in a local browser or pair from the desktop/mobile app. For custom CAs on Android, install the CA certificate in Android security settings. +- **Session lifetime**: Paired devices stay signed in while active; sessions unused for 30 days must re-pair. ### Reach one machine several ways -A machine can have more than one route: LAN, Tailscale, another VPN, a public -URL, SSH, or T3 Connect. Tailscale shares its `100.64.0.0/10` address range with -other VPNs such as Cloudflare WARP, so an address in that range shows as VPN -unless the machine confirms it is on Tailscale. To add a route, choose **Add -route** in the machine's route list, or next to it in the T3 Connect list. -A pairing link for a saved machine is refused when it comes from an address -that machine does not have yet; add that address with **Add route** instead. -Pairing again over an address the machine already has still works. A new route -is placed by speed, in that order, and you can reorder routes at any time. - -While connected through T3 Connect or a paired address, T3 Code also learns the -machine's current LAN and Tailscale addresses and adds them as routes, so -pairing once through T3 Connect is enough to use the LAN at home. When the -machine's LAN address changes, for example after it joins another Wi-Fi network, -the learned route follows it. The machine must allow network access for its LAN -address to be learned: **Network access** in the desktop app, or the -[local network](./background-service.md#local-network-access) choice in `t3 up`. -You can reorder a learned route, but not remove it; it -goes away with the route it was learned through, or when the machine stops -reporting that address. - -T3 Code connects over the first route that answers. Away from home, a LAN -address that does not answer is checked briefly and skipped. It is only tried -again, after the other routes, if none of them connect. While connected over a -later route, T3 Code checks the earlier ones when your network changes, when you -return to the app, and every minute, and moves back as soon as one works. A -route whose machine refused this device's sign-in is marked **Sign-in -refused**; pair that address again with **Add route** to use it. - -On web and desktop, select the route count under the machine's name in -**Settings → Environments** to see its routes. Drag a route to change the order, -or remove it. On mobile, open the machine under **Settings → Environments** and -choose **Edit**. Signing out of T3 Connect removes only that route; a machine -you can still reach another way stays saved. - -Open **Permissions** next to **Routes** in web or desktop, or **Your permissions** -in the mobile route details, to see what your current connection can do on that -environment. For a remote environment, this is in its route details. Permissions -shown there apply only to the route marked **In use**; other routes are not -checked. Direct pairing and T3 Connect have separate sessions and may grant -different permissions. - -### Balance new threads across machines - -Auto balance is off by default. On web and desktop, enable it in -**Settings → Environments → Load balancing** to automatically choose a machine for -new threads in projects grouped across connected environments. The section -appears once two or more machines are switched on. -Each machine starts at **Normal**. Choose **Prefer** to favor it when it has CPU and -memory available, **Less often** to reduce its share, or **Manual only** to exclude -it from automatic selection. These are preferences, not fixed traffic percentages. -Preferences are saved separately in each client. - -The composer checks eligible machines when choosing a draft's environment, then keeps -that choice stable. Choose **Auto balance** again to check current resources, or choose -a specific machine to override it. Choosing a branch or worktree also keeps the draft -on that machine. Existing threads stay where they started. If resource checks are -unavailable or all eligible machines are full, choose a machine manually to continue. -Mobile keeps its manual environment selection. +A host can have multiple routes (LAN, Tailscale, VPN, public URL, SSH, T3 Connect). T3 Code automatically learns LAN and Tailscale routes when network access is enabled, connects over the fastest working route, and switches back to higher-priority routes when you return home. Reorder or add routes in **Settings → Environments** (**Add route**). ### Tailscale HTTPS -Join both devices to the same tailnet. In the desktop app, enable **Tailscale -HTTPS** in **Settings → Sharing & access**. Turn it off there to remove that route. - -Your tailnet needs MagicDNS and HTTPS certificates enabled; see -[Tailscale's HTTPS setup](https://tailscale.com/docs/how-to/set-up-https-certificates). -On Linux, T3 Code also needs permission to manage Tailscale; see -[operator permission](https://tailscale.com/docs/reference/troubleshooting/linux/linux-operator-permission) -for non-root users. If any of these is missing, T3 Code still starts but can't -add the HTTPS route. - -To start a command-line server with Tailscale HTTPS: - -```bash -t3 serve --tailscale-serve -``` - -For an already-running server: - -```bash -t3 pair --tailscale -``` - -The pairing link uses an address such as `https://machine.tailnet.ts.net/`. -The mapping created by `pair --tailscale` persists across restarts. Remove its -default-port mapping with: - -```bash -tailscale serve --https=443 --set-path=/ off -``` +Join both devices to a tailnet with [MagicDNS and HTTPS certificates](https://tailscale.com/docs/how-to/set-up-https-certificates) enabled (on Linux, grant [operator permission](https://tailscale.com/docs/reference/troubleshooting/linux/linux-operator-permission)). -If that port is already in use, choose another with -`--tailscale-serve-port`. See `t3 pair --help` for other pairing options. +- **Desktop**: Enable **Settings → Sharing & access → Tailscale HTTPS**. +- **CLI**: Run `t3 serve --tailscale-serve` or `t3 pair --tailscale` (use `--tailscale-serve-port` if 443 is taken; remove with `tailscale serve --https=443 --set-path=/ off`). -### Hosted web app - -[app.t3.codes](https://app.t3.codes) needs an HTTPS endpoint. It connects directly -to your server; a hosted pairing link does not make an unreachable backend -reachable or convert HTTP to HTTPS. Opening a hosted pairing link shows the -server address and asks you to confirm before adding it. +### Balance new threads across machines -For a plain HTTP LAN endpoint, use the direct pairing URL in a browser that can -open it, or pair from the desktop app. On mobile, an IP address entered without a -scheme uses HTTP, so include `https://` when your server uses HTTPS. +On web and desktop with 2+ connected machines, enable **Settings → Environments → Load balancing** (per client) to auto-select a host for new threads in shared projects. Set each machine to **Prefer**, **Normal**, **Less often**, or **Manual only**. ## Desktop-managed SSH -In the desktop app, open **Settings → Environments → Add environment**, choose -**SSH**, and enter a host or SSH alias such as `user@example.com`. T3 Code starts -or reuses a server there and opens the port forward for you. Projects, provider -credentials, and agent work stay on the remote machine. - -The remote host must be Linux or an Apple Silicon Mac with `curl` or `wget`, -`tar`, `sha256sum` or `shasum`, and [provider setup](./install.md#providers). -The first launch downloads T3 Code's server to `~/.t3/runtime` on the host, so -it takes longer than later ones. -Provider CLIs must be on the `PATH` of a non-interactive login shell there; -check with: - -```bash -ssh user@example.com 'sh -lc "command -v claude codex"' -``` - -T3 Code cannot answer a second sign-in prompt such as a Duo code. On macOS and -Linux it can reuse a connection you signed in to in a terminal instead: turn on -connection sharing for the host in `~/.ssh/config`, run `ssh `, then -connect. When that connection closes, sign in again in a terminal and retry. - -```sshconfig -Host - ControlMaster auto - ControlPath ~/.ssh/cm-%C - ControlPersist 8h -``` - -If SSH reconnecting fails after an app update, retry the launch once. Removing -the connection stops a server that T3 Code launched; a server that was already -running is left alone. +In the desktop app, open **Settings → Environments → Add environment → SSH** and enter a host or SSH alias (e.g. `user@example.com`). T3 Code downloads its runtime to `~/.t3/runtime` on the Linux or Apple Silicon macOS host, starts or reuses a server, and manages port forwarding automatically. -Each desktop app keeps one session on the host for its SSH connection and reuses -it when it reconnects. Revoke sessions you no longer use in **Settings → -Sharing & access** on the host, or on a headless host with `t3 auth session list` and -`t3 auth session revoke `. A desktop that can still sign in over SSH pairs -again on its next connect. - -For Antigravity's Google callback on a remote host, see -[remote sign-in](./providers-antigravity.md#sign-in-from-a-remote-device). +- Provider CLIs must be on a non-interactive login shell's `PATH` (check with `ssh user@example.com 'sh -lc "command -v claude codex"'`). +- For 2FA/Duo hosts on macOS/Linux, enable SSH `ControlMaster` in `~/.ssh/config` and open a terminal SSH session first. +- Revoke unused SSH sessions in **Settings → Sharing & access** or `t3 auth session revoke `. ## Browser on a remote environment -Browser tabs belong to the environment, so you and your agents see the same -tabs from any device. The desktop app shows its own environment's tabs -directly. Every other device, and the desktop app for other environments, -streams them from the host. Agents keep using them while no device is -connected, and `localhost` addresses reach servers on the host. - -A tab you open yourself in the desktop app for another environment loads on -your computer instead, so the element picker, screenshots, and annotations work -as they do locally. Its `localhost` addresses still reach servers on the host, -over the connection the app already has, whichever way you connected. If the -host cannot be reached, the tab shows a connection error; a `localhost`, -`127.0.0.1`, or `[::1]` address never opens a server on your own computer. -Other names that point at your computer, such as `/etc/hosts` entries, still -do. These tabs ignore your system proxy settings, so they can't reach a host -you connect to only through a proxy or over HTTPS with a privately issued -certificate. The web app keeps streaming. - -The desktop app can also forward a port on the host to your computer, so any -app there, such as your own browser, `curl`, or a database client, reaches it -at `localhost`. Use the forward button on a server in the thread's **Servers** -list, or **Forwarded ports** in the command palette, where you can also type -any port number and stop forwards. A forward keeps the host's port number -unless that port is taken on your computer, in which case it uses a free one -and shows it. Forwards end when you stop them or quit the app. ⌘-click -(Ctrl-click on Windows and Linux) on a remote server forwards it and opens it -in your browser. - -A forwarded port behaves like a server running on your computer: anything on -your computer can reach it, including web pages open in your browser, so a -forwarded service is exposed the same way a local dev server is. Forwards -listen only on your computer's loopback, never on your network. On Linux they -accept only apps running as your user; on macOS and Windows, other users signed -in to the same computer can reach them too. - -On iPhone, iPad, and Android, a tab showing one of the host's `localhost` pages -has **Open on this device** in its menu. So does a long press on a `localhost` -link in a chat. It opens the page in the phone's own browser view, at the same -`localhost` address, so it scrolls and responds to touch natively. Like the -desktop app, it never opens a server on the phone itself. The streamed tab -stays where it was, and agents keep using it. Each host keeps its own cookies -and site data on the phone. On iPhone and iPad the page runs under a stand-in -address while the address bar shows `localhost`, so browser features that need -a secure page, such as the clipboard or service workers, aren't available there. - -All of this rides the host's preview tunnel. Turn off **Settings → Sharing & -access → Preview tunnel** on the host to stop other devices from loading its -`localhost` pages themselves: port forwarding and **Open on this device** go -away, and open tunnels close. Tabs keep working by streaming from the host, so -anyone who can use the host's browser tabs can still view its `localhost` pages -there. An administrator can also turn it off with a -[managed policy](./managed-policy.md#other-capabilities). - -The first tab downloads a headless Chrome, about 120 MB, into the T3 home. It -is the same browser [HTML renders](html-renders.md) use, so a host downloads it -only once. Some Linux hosts need [setup](#browser-host-setup) before it can -start. - -Agent tabs have separate storage and share a Chromium process. Take control before -typing into an agent's tab, then release control when you want the agent to -continue. Read-only connections can watch without changing the page. - -While you have control, the tab works with your device: text the page copies or -cuts goes to your clipboard, a file picker on the page opens your device's -picker, a dropdown on the page shows its options on your device, and a finished -download is offered for you to save. Popups such as sign-in windows open as -their own tabs. Downloads stay on the host until the tab closes. Audio does not play on your device. - -On a phone, tap the floating preview's corner dot to show its controls, then -**Pop into separate window** to keep watching in picture-in-picture over other -apps. - -### Local servers - -The browser lists ports held by processes your terminals and agents started. -T3 Code reads which process holds each port and never connects to it, so a -listed port opens as `http://localhost:` and might not be a web page. For -an HTTPS server or a specific path, set the **Preview URL** on the project -script that starts it; T3 Code checks that address and opens it as written. - -To stop listing ports, set `T3CODE_PORT_DISCOVERY=0` in the environment that -starts the T3 Code server, such as -[`service.env`](./background-service.md#configure-the-service-environment) for -the background service, and restart it. Script preview URLs still appear. +Browser tabs belong to the host environment so you and your agents share them from any device. + +- **Streaming & local loading**: Web and mobile stream tabs from the host. In the desktop app, tabs you open for a remote environment load locally while routing `localhost` requests to the host over the **preview tunnel** (so element picker and annotations work locally). +- **Port forwarding (desktop)**: Forward any remote host port to your local `localhost` via the thread's **Servers** list or **Forwarded ports** in the command palette (`Cmd/Ctrl-click` forwards and opens in your browser). +- **Open on this device (mobile)**: Tap **Open on this device** on a streamed `localhost` tab or long-press a `localhost` link in chat for native touch scrolling. +- **Disable preview tunnel**: Turn off **Settings → Sharing & access → Preview tunnel** on the host (or via [managed policy](./managed-policy.md#other-capabilities)) to disable port forwarding and **Open on this device** (streamed tabs continue working). +- **Take control**: Click **Take control** before typing into an agent's tab, and release control when done. +- **Local servers**: T3 Code lists listening ports from your terminals and agents as `http://localhost:` (set a script's **Preview URL** for HTTPS or subpaths). Disable discovery with `T3CODE_PORT_DISCOVERY=0`. ### Browser host setup -macOS, Windows, and Linux desktops run the browser as is. Some Linux hosts need -one-time setup: Ubuntu 23.10 and later block the sandbox the browser runs in, -and minimal images and containers lack libraries it loads. When that happens, -the server says so at startup, and browser tabs and HTML previews show the -command to run on the host: +The first server browser tab downloads ~120 MB headless Chromium (shared with [HTML renders](./html-renders.md)). On Ubuntu 23.10+ or minimal Linux containers, run the one-time setup command on the host: ```sh sudo t3 browser setup ``` -The server shows the exact line for how you started it, and keeps your `PATH` -when you started it with `npx` and Node is installed only for your user. Where `t3` is not on your `PATH`, such as with only the -desktop app installed, it names the full path of the app's own `t3` instead. It allows Chrome's sandbox with an AppArmor profile and installs -any missing libraries and system fonts with apt; pages that load without text -can mean the host has no fonts. It is safe to run again, and each run reloads -the AppArmor profile: run it again if the browser reports a blocked sandbox on a -host restored from an image or snapshot, where the profile can be on disk -without being loaded. Without `sudo`, it only reports what it would change. - -The browser runs in Chrome's sandbox by default. Chrome cannot start that sandbox -as root. If your T3 server runs as root, run it as a nonroot user to keep -sandboxing enabled. `t3 browser setup` does not fix this root restriction. - -If you need to run as root, or cannot enable the sandbox on your host, set -`T3CODE_SERVER_BROWSER_SANDBOX=0` in the **T3 server's environment** and restart -the server. This disables Chrome's sandbox. For a manual launch: - -```sh -T3CODE_SERVER_BROWSER_SANDBOX=0 t3 serve -``` - -For a systemd service, add `Environment=T3CODE_SERVER_BROWSER_SANDBOX=0` under -`[Service]` in its configuration, run `sudo systemctl daemon-reload`, then restart -your T3 service. Setting the variable in an agent's terminal does not change the -environment of an already running T3 server. +This installs an AppArmor profile for Chrome's sandbox plus missing libraries and fonts. Never run the T3 server as root (Chrome's sandbox rejects root); if sandboxing is impossible on your host, set `T3CODE_SERVER_BROWSER_SANDBOX=0` in the server environment and restart. -## Connect an outside agent +## Link another environment -Claude Code, Codex, ChatGPT and other agents T3 Code did not start can drive -threads on an environment through its MCP server. See -[outside agents](./outside-agents.md) for setup. +Link two T3 Code machines (beta) so agents on one can launch, message, delegate to, and manage threads on the other. -## Link another environment +1. Enable **Settings → Labs → Linked environments** on **both** machines (or `"linkedEnvironmentsEnabled": true` in `userdata/settings.json`). +2. On the source machine, open **Settings → Environments → Linked environments → Link** (or drag from one machine's `+` to another on the Environments map, or run `t3 environment link
        --pairing-code --access `). Use **Link several…** or `--from ` for batch linking. +3. Links are one-way (tick **Also link … back** for two-way) and do not chain. Links expire after 30 days of inactivity and can be revoked in **Settings → Sharing & access** or **Forget**. -Link two machines, such as your laptop and a VPS, and agents on one can work on -the other: launch, message, wait on and stop its threads, answer their -questions, and manage its queues, projects and scheduled tasks. - -Linked environments is a beta. Turn it on for both machines in **Settings → -Labs**; on mobile, **Settings → Labs** lists each connected machine. On a -headless server, open its address in a browser and pair to reach its **Settings -→ Labs**, or add `"linkedEnvironmentsEnabled": true` to `settings.json` in its -`userdata` directory, such as `~/.t3/userdata/settings.json`; a running server -picks it up. While it is -off on either machine, agents start nothing over a link between them. A task -already running on the other machine still finishes, and if that machine has it -off, its result arrives once it is back on. - -On the machine you will work from, open **Settings → Environments → Linked environments**, -choose **Link**, and pick the other machine or enter its address. The list -holds the machines this app knows and those on your T3 Connect account. If this -app has an address for that machine and is connected to it with a session that -manages access there, it makes the pairing code itself; otherwise paste one -from that machine's **Settings → Sharing & access**. An address you type always -needs a pasted code. From a terminal, use -`t3 environment link
        --pairing-code --access `. - -To link many machines at once, choose **Link several…** (it appears once this -app has two other machines saved). Tick the machines, pick one access level for -all of them, and confirm once. A machine can be ticked when this app is -connected to it with a session that manages access there and has an address -another machine can reach; the list says why when it cannot. Each machine -reports its own result, and the ones that failed stay ticked so you can try -only those again. Machines already linked are left as they are. - -For machines no app is connected to, put one `
        ` per -line in a file (make each code with `t3 pair` on that machine) and run -`t3 environment link --from --access `, or `--from -` to read -standard input. It prints a result per line, leaves machines already linked as -they are, and exits non-zero if any line failed, so the same file can be run -again with fresh codes for the failures. - -You can also ask an agent to link a machine by name, such as "delegate this to -my vps". It shows a card in the thread where you pick the machine the same way -and the access, then approve. An address the agent gives that this app does -not know for one of your machines also needs a pasted code. Paste one only for -an address you trust: the code is sent there. - -- The access you pick is the most agents from this machine may do there. An - agent also never gets more there than its own mode here. -- Threads a link starts are marked **From** and this machine's name there. -- A full-access link works there like that machine's own agents. Below full - access, the link's agents can change only threads it started, not that - machine's own threads, projects or settings, and they skip its project setup - scripts. -- The link shows up in that machine's **Settings → Sharing & access** like any - outside agent, and can be revoked there. **Forget** on this machine also ends - it there when that machine confirms it. If it can't, such as when it is - offline or on an older T3 Code, Forget says so; revoke it in that machine's - Sharing & access. -- A link stays valid while agents use it. One unused for 30 days expires, as - does one to a machine on an older T3 Code after 30 days; link again with a - new pairing code. - -On web and desktop, **Settings → Environments** opens as a map of your machines: -this app, each environment with one line per route (the one in use is -highlighted), and the machines an environment links to. Select a machine to -manage it, or switch to **List** for the same controls as rows. To link from -the map, drag the plus on an environment onto another machine, or press it and -pick one. If this app is connected to both machines, knows an address the first -can reach the other at, and its session on the other one manages access there, -it needs no pairing code. - -A machine this app is not connected to, shown only because another environment -links to it, can still be linked without a code when that link has full access: -drop the plus on it and the environment holding the link gets the pairing code -from it. Your session on that environment must manage access there and already -have the access you pick. The result -is a separate link with the access you pick, listed and revocable on the linked -machine like any other. Links still do not chain. - -A link goes one way. To let the other machine's agents work back, tick **Also -link … back** when you create the link, or select a one-way link and use -**Link back…**. It is offered when this app is connected to both machines and -may manage access on each. Two machines linked to each other at the same access -are drawn as one line with an arrowhead at each end; they are still two links, -and each is forgotten on its own. - -To link one environment to several machines at once, Shift-click the machines -(or Shift-drag a box around them, or press Space on a focused machine), then -drag the environment's plus onto any of them, or use **Link several…** above -the map. Dropping the plus on a stack offers the stack's machines. The dialog -ticks the machines it can link without a pairing code and says why for the -rest. When this app is connected to none of them, each needs a pairing code, -so the map says so and offers to link one at a time instead. - -Large setups fold: machines known only through links that share the same -linking environments and access levels become one stack, and once this app -knows more than 12 environments, the ones that are not connected and have no -links fold by state. Select a stack to list and filter every machine in it. -Opening a stack on the map draws its first 24 below its card: the rest of the -map stays where it is and the map grows taller, so pan or press the fit button -to see all of it. **Find a machine** above the map searches by name, and Enter -goes to the first match. The **?** button above the map lists these gestures. - -The map draws the links of the machines this app is connected to; a machine it -is not connected to may hold links the map cannot show. A link reaches one -machine and does not carry on through that machine's own links. - -An agent can also hand a task to a linked machine with `delegate_task`: it runs -there as an ordinary thread, in the project with the same repository (or the -one `target.projectId` names), and this thread wakes with its result when it -ends, as for any delegated task. It keeps following the task across restarts. -If the other machine revokes the link, or the link is removed here, the task -fails with that reason. +- **Access boundary**: Agents never get more permissions on the target than the link's access level or their own thread mode. Below Full access, linked agents can only modify threads they started and skip project setup scripts. +- **Delegation**: Agents can target a linked machine with `delegate_task`, or ask you to link an unlinked machine via an in-thread approval card. ### Read a linked machine's threads -You can read a thread on a linked machine without connecting this app to it. Open -a task that was delegated there from the thread's agents, or a thread link that -points there, and the thread opens read-only, streamed through the machine you -are connected to over its link. It follows the thread live. On web and desktop -it opens as a tab in the right panel, beside the thread you are in, or in the -main view with ⌘/Ctrl-click, like -[subagents and side chats](thread-sidebar.md#open-a-thread-beside-the-one-you-are-in). -On mobile it opens in the inspector on layouts that have one, where Maximize -fills the screen, and as its own screen elsewhere. It shows the same timeline as -any other thread on web and desktop, and a shorter read-only list on mobile. - -- The view is marked **Read-only** with both machines' names. To reply, approve - or stop the thread, choose **Connect to interact**. When the link has full - access, this app pairs with that machine in one step and opens the thread - there; you need permission to manage access on the machine you are connected - to. Otherwise the add-environment form opens for that machine and asks for a - pairing code you create on it. -- This app connects to that machine directly, so it must be able to reach one of - the addresses the link uses. If it cannot, the view says so and stays - read-only. The new connection appears in that machine's **Settings → Sharing & - access**, named after this device and the machine it came through, and is - revoked there like any other. -- Files, images and published visuals stay on that machine and do not load - here. A command's output shows as of when you open its row. -- If this app is already connected to that machine, the thread opens there as - usual instead. -- You need permission to read threads on the machine you are connected to, and - Linked environments must be on there. Both machines need a version of T3 Code - that has this view. +Open a delegated task or thread link on a linked machine to follow it live (read-only) in the right panel without pairing your client directly. Click **Connect to interact** to pair and take action (one-click if the link has Full access and you can manage access). Files, images, and HTML renders stay on the remote machine until you connect directly. ## Manage or revoke access -On the host, **Settings → Sharing & access** lets authorized administrators create -pairing links and revoke client sessions. Revoking an unused link prevents new -pairings; revoke a device's session to remove its existing access. Command-line -management is available through `t3 auth --help`. +Manage pairing links and active client sessions in **Settings → Sharing & access** or via `t3 auth --help`. -When the app connects to more than one environment, choose one at the top of the -page. A desktop app with **Local environment** off can manage a background -service on the same machine this way, including its T3 Connect link. +- **Scoped tokens**: Pass `--scope ` (repeatable) to `t3 pair`, `t3 auth pairing create`, or `t3 auth session issue` to restrict permissions (e.g. `orchestration:read`, `source-control:write`, `filesystem:read`, `filesystem:write`, `terminal:operate`, `relay:configure`). Re-pair with a fresh link to change an existing client's scopes. +- **Deregister from T3 Connect**: Open your account menu → **T3 Connect → Deregister** (or `t3 connect unlink` / `t3 connect logout` on CLI hosts). Idle tunnels are automatically cleaned up after 5–10 minutes offline and recreated on reconnect (hosts on older versions offline for 7+ days need an update first). +- Treat pairing URLs and codes as passwords—never paste them into logs or screenshots. -A session with an open connection stays listed after its access credential -expires. +## Desktop app as a remote only -To choose a token's permissions, pass `--scope` once for each scope you want: +Switch off **Settings → Environments → Local environment** in the desktop app to run with no local server, WSL backend, or incoming connections while continuing to drive remote hosts (if a local background service uses the same T3 home, **Open in** still works locally). -```sh -t3 pair --scope orchestration:read --scope relay:read -``` +## Troubleshooting -The selected scopes replace the default permissions. The same option works with -`t3 auth pairing create` and `t3 auth session issue`; each command's -`--help` lists the available scopes. Without `--scope`, pairing tokens and issued -bearer sessions get the standard client permissions, including managing access. -Setting up or replacing a T3 Connect link requires the separate `relay:configure` permission. -A terminal or a full-access agent on the host can reach those as well, so a -client that should not manage access also needs to go without `terminal:operate` -and `orchestration:operate`. - -To change an existing client's permissions, create a fresh pairing link with the -scopes it needs. In a browser opened directly on the environment, open that link -to replace the browser's current grant. For mobile or a saved remote environment -in web or desktop, use **Add Environment** with the fresh link or code; pairing -the same environment replaces its saved grant. Reconnecting alone does not change -permissions. - -Grouping checkouts does not combine their permissions. Shared project settings -require `orchestration:operate` on every member environment; actions on one -checkout use that checkout's permissions. - -`source-control:write` covers direct Git and pull request changes made from the -client: pushing, switching or creating branches, cloning, and removing -worktrees. It does not restrict what a task does. Starting a task in a new -worktree still creates that branch and worktree with `orchestration:operate`, -and the agent it runs can use Git however the environment allows. A project -that [lays out its worktrees with its own command](multi-repo-projects.md#lay-the-folder-out-yourself) -runs that command on the host, so creating a worktree there from the client also -needs `orchestration:operate` or `terminal:operate`; without one of them, -removing a worktree skips the project's `remove` command. The command also has -to be [approved](multi-repo-projects.md#approve-the-commands) first, from a -client with `terminal:operate`. - -Settings changes, provider management, environment maintenance, access -management, and T3 Connect preferences can each be granted separately. Setting -up or replacing a T3 Connect link requires the administrative -`relay:configure` permission. `relay:write` covers preferences and unlinking. -New pairings without `--scope` include the standard client permissions. Existing clients keep the -permissions they paired with and can stay connected after an update, but newly -separated features may require pairing again with the permissions they need. -Older clients may show controls that the server denies. Create a fresh pairing -link to change a client's permissions. - -`filesystem:read` allows browsing host files, opening workspace files, and viewing -local changes. Add `filesystem:write` to allow editing files or saving plans to -the workspace. These scopes control direct file access from the client. - -Some permissions also give a client indirect access. With `terminal:operate`, -a client can run commands that read or change any files the server’s OS account -can access, even when the pairing link omits file permissions. With -`relay:configure`, a client can replace the trusted issuer of pairing -credentials. Grant these permissions only to clients you trust with those -capabilities. - -To remove an environment from T3 Connect, open your account menu's **T3 Connect** -page, or **Settings → T3 Connect** on mobile, and choose **Deregister**. This -revokes its cloud access and frees its host space even when the environment is -offline or has been wiped. When T3 Connect rejects a host's link, the host -shows that it was removed from T3 Connect. To link it again, turn on -**T3 Connect** in **Settings → Sharing & access** on web or desktop, or turn on -**Live Activity Updates** in **Settings → Notifications** on mobile; if it is -already on, turn it off and on again. Either needs a client paired with -`relay:read`, `relay:write`, and `relay:configure`. The desktop app's own session -and the startup pairing link include all three; a pairing link created in -**Settings → Sharing & access** needs `relay:configure` selected. You can also -run `t3 connect link` on the host and then restart T3 Code there. A -command-line host that released its tunnel when it last stopped may link itself -again on its next start; run `t3 connect unlink` on that host to keep it off. -Removing an environment from a device's connection settings only forgets it on -that device and doesn't change your T3 Connect account. A device keeps a saved -environment after it's deregistered until you remove it from that device. - -When idle tunnel cleanup is enabled, T3 Connect removes a linked environment's -tunnel after it stays offline for several minutes. The environment stays linked -and keeps the same address. When the host starts again or wakes, T3 Connect -creates a replacement tunnel on its own. You do not need to pair again. Cleanup -usually runs five to ten minutes after the tunnel goes down. - -T3 Connect also removes the tunnel of an environment running an older version of -T3 Code once it has been offline for seven days. That environment shows a message -asking you to update. Start T3 Code on that computer and update it to the latest -version; it reconnects at the same address without pairing again. - -On a command-line host, `t3 connect unlink` disables exposure while retaining -your login; `t3 connect logout` also clears that login. Background-service -[removal](./background-service.md#manage-the-service) is separate. - -Treat pairing URLs and authorization codes as passwords. Do not include them in -screenshots, logs, or bug reports. - -## T3 Connect troubleshooting - -When a T3 Connect connection fails, see -[T3 Connect troubleshooting](./t3-connect-troubleshooting.md). It explains each -error, where the problem is, and how to fix it. - -## Using the Desktop App as a Remote Only - -If a computer should only drive work running elsewhere, turn off its local environment. In the -desktop app, open **Settings → Environments** and switch off **Local -environment**. T3 Code restarts without a local server: no local agents or terminals run, WSL -backends stay off, and other devices can no longer connect to this computer. Your projects, -history, and saved connections are kept, and you keep working through pairing, T3 Connect, or SSH. -If a [background service](./background-service.md) on this computer uses the same T3 home, the -app still treats it as this computer: **Open in** and file reveal for its projects run here, -whichever connection you reach it through. - -Switch **Local environment** back on in the same place to restart with your previous local -settings. +See [T3 Connect troubleshooting](./t3-connect-troubleshooting.md) for step-by-step connection diagnostics, and [Outside agents](./outside-agents.md) for MCP connections. diff --git a/docs/user/secrets-1password-connect.md b/docs/user/secrets-1password-connect.md index 56cd4c621fecc..607250404b1a7 100644 --- a/docs/user/secrets-1password-connect.md +++ b/docs/user/secrets-1password-connect.md @@ -1,34 +1,18 @@ # 1Password Connect on a remote server -Use a 1Password Connect server when you already run one, for example on a home server or in Kubernetes, and -want the T3 Code server to read secrets through it. Connect needs no desktop approval, so it works on a -headless or [remote](./remote-access.md) host. - -If you do not run Connect, a [service account](./secrets-1password-service-account.md) is simpler. For the -basics, see [Secrets](./secrets.md). +Read secrets from a self-hosted 1Password Connect server on headless or [remote](./remote-access.md) T3 Code hosts without desktop approval prompts. If you don't already run Connect, a [1Password service account](./secrets-1password-service-account.md) is simpler. See [Secrets](./secrets.md) for basics. ## Set it up -1. In 1Password, create a Connect server and an access token. Limit the token to the vaults T3 Code needs. +1. In 1Password, create a Connect server and access token scoped **only** to the vaults T3 Code needs. 2. Deploy the Connect API and sync containers where the T3 Code server can reach them. -3. Install the [1Password CLI](https://developer.1password.com/docs/cli/get-started/) (`op`) on the machine - that runs the T3 Code server. -4. Put `OP_CONNECT_HOST` and `OP_CONNECT_TOKEN` in the server's environment. `OP_CONNECT_HOST` is the Connect - API's address, including the port if it is not the default for its scheme. Use an `https://` address - unless Connect runs on the same machine or a private network you trust, because the token and secrets - travel over that connection. For a - [background service](./background-service.md), add both to `service.env` and restart the service. See - [Configure the service environment](./background-service.md#configure-the-service-environment). -5. In **Settings → Secrets**, select **Add provider**. The account is required, but `op` ignores it while - Connect is configured, so enter any sign-in address such as `my.1password.com`. - -Then use references as usual, for example `op://Automation/provider-token/credential`. +3. Install the [1Password CLI](https://developer.1password.com/docs/cli/get-started/) (`op`) on the T3 Code server machine. +4. Set `OP_CONNECT_HOST` (use `https://` unless local or on a trusted private network) and `OP_CONNECT_TOKEN` in the server's environment (for a background service, add them to [`service.env`](./background-service.md#configure-the-service-environment) and run `t3 service restart`). Do not set `OP_SERVICE_ACCOUNT_TOKEN` in the same environment. +5. In **Settings → Secrets → Add provider**, enter any sign-in address (e.g. `my.1password.com`; `op` ignores it while Connect is configured), then use `op://vault/item/field` references. -## Check that it works +## Verify -On the server's machine, set `OP_CONNECT_HOST` and `OP_CONNECT_TOKEN` in your shell to the values the -server uses. Confirm the address is a Connect server, then read a secret with a clean environment so only -the Connect variables can sign in: +On the server machine, test with a clean environment: ```bash curl -s "$OP_CONNECT_HOST/health" @@ -36,23 +20,8 @@ env -i PATH="$PATH" HOME="$(mktemp -d)" OP_CONNECT_HOST="$OP_CONNECT_HOST" OP_CO op read --no-newline "op://Automation/provider-token/credential" >/dev/null && echo "Secret read" ``` -The health response names the 1Password Connect API. Any other page means the address points at something -else, such as a reverse proxy that answers for every hostname. - -This checks the Connect variables in your shell, not the server's own environment. To confirm the server -can read the secret, use the reference in a setting and then use the feature that needs it. If the server -cannot read the secret, that feature shows an error naming the secret provider. - -## Things to know - -- Agents run with the server's environment, so an agent can use the Connect token to read anything it can. - Give the token only vaults whose items you would let an agent read. -- Through Connect, `op` can read items but cannot list vaults or accounts. Test with `op read`, not - `op vault list`. -- A name in a reference can contain letters, digits, spaces, `.`, `_`, and `-`. An item titled - `Service Token: CI` cannot be written as a reference, so use its item ID instead, for example - `op://Automation//credential`. -- A Connect token sees only the vaults it was created for. A reference to any other vault cannot be read. -- T3 Code waits up to 45 seconds for 1Password. After that the secret counts as unreadable and the feature - that needs it shows an error naming the secret provider. -- Do not set `OP_SERVICE_ACCOUNT_TOKEN` in the same environment. +## Notes + +- **Agent scope**: Agents inherit the server's environment and can read any vault accessible to the Connect token—grant only vaults you're comfortable exposing to agents. +- **Reference names**: Use item IDs if an item title contains characters outside letters, digits, spaces, `.`, `_`, and `-` (e.g. colons). +- `op` over Connect supports `op read` (not `op vault list`), and T3 Code times out secret reads after 45 seconds. diff --git a/docs/user/secrets-1password-service-account.md b/docs/user/secrets-1password-service-account.md index 8ca28d8b047a1..e87eac802e19b 100644 --- a/docs/user/secrets-1password-service-account.md +++ b/docs/user/secrets-1password-service-account.md @@ -1,53 +1,25 @@ # 1Password service account on a remote server -Use a 1Password service account when the T3 Code server runs on a machine you are not sitting at, such as a -headless host, a VM, or a [background service](./background-service.md) you reach through -[remote access](./remote-access.md). - -Signing in to 1Password through its desktop app asks for approval on the server's machine. A remote user -never sees that prompt, so the secret cannot be read. A service account signs in with a token instead, so -nothing needs approving. - -For the basics, see [Secrets](./secrets.md). To use a self-hosted Connect server instead, see -[1Password Connect](./secrets-1password-connect.md). +Use a 1Password service account so a headless, VM, or [background-service](./background-service.md) T3 Code server can read secrets via `op` without desktop approval prompts. See [Secrets](./secrets.md) for basics, or [1Password Connect](./secrets-1password-connect.md) for self-hosted Connect. ## Set it up -1. In 1Password, open Developer, then Service Accounts, and create one. -2. Give it read access to only the vaults T3 Code needs. Access is fixed when the account is created, and a - service account cannot reach Personal, Private, or Employee vaults. -3. Copy the token. It is shown once. -4. Install the [1Password CLI](https://developer.1password.com/docs/cli/get-started/) (`op`) on the machine - that runs the T3 Code server. -5. Put `OP_SERVICE_ACCOUNT_TOKEN` in the server's environment. For a background service, add it to - `service.env` and restart the service. See - [Configure the service environment](./background-service.md#configure-the-service-environment). -6. In **Settings → Secrets**, select **Add provider**. The account is required, but `op` ignores it while - the token is set, so enter any sign-in address such as `my.1password.com`. +1. In 1Password (**Developer → Service Accounts**), create a service account with read access **only** to the vaults T3 Code needs (cannot access Personal/Private/Employee vaults). Copy the one-time token. +2. Install the [1Password CLI](https://developer.1password.com/docs/cli/get-started/) (`op`) on the T3 Code server machine. +3. Set `OP_SERVICE_ACCOUNT_TOKEN` in the server's environment (for a background service, add it to [`service.env`](./background-service.md#configure-the-service-environment) and run `t3 service restart`). Do not set `OP_CONNECT_HOST` / `OP_CONNECT_TOKEN` in the same environment. +4. In **Settings → Secrets → Add provider**, enter any sign-in address (e.g. `my.1password.com`; `op` ignores it while the token is set), then use `op://vault/item/field` references. -Then use references as usual, for example `op://Automation/provider-token/credential`. +## Verify -## Check that it works - -On the server's machine, set `OP_SERVICE_ACCOUNT_TOKEN` in your shell to the same token the server uses, -then read a secret with a clean environment so only the token can sign in: +On the server machine, test with a clean environment: ```bash env -i PATH="$PATH" HOME="$(mktemp -d)" OP_SERVICE_ACCOUNT_TOKEN="$OP_SERVICE_ACCOUNT_TOKEN" \ op read --no-newline "op://Automation/provider-token/credential" >/dev/null && echo "Secret read" ``` -If it prints `Secret read`, the token can read the secret. This checks your shell, not the server's own -environment. To confirm the server can read it, use the reference in a setting and then use the feature -that needs it. If the server cannot read the secret, that feature shows an error naming the secret provider. - -## Things to know +## Notes -- Agents run with the server's environment, so an agent can use the token to read anything the service - account can. Give it only vaults whose items you would let an agent read. -- A name in a reference can contain letters, digits, spaces, `.`, `_`, and `-`. An item titled - `Service Token: CI` cannot be written as a reference, so use its item ID instead, for example - `op://Automation//credential`. -- T3 Code waits up to 45 seconds for 1Password. After that the secret counts as unreadable and the feature - that needs it shows an error naming the secret provider. -- Do not set `OP_CONNECT_HOST` and `OP_CONNECT_TOKEN` in the same environment. +- **Agent scope**: Agents inherit the server's environment and can read any vault accessible to the service account—grant only vaults you're comfortable exposing to agents. +- **Reference names**: Use item IDs if an item title contains characters outside letters, digits, spaces, `.`, `_`, and `-`. +- T3 Code times out secret reads after 45 seconds. diff --git a/docs/user/secrets.md b/docs/user/secrets.md index 4f2a4b0de138c..16cb8fe68be2a 100644 --- a/docs/user/secrets.md +++ b/docs/user/secrets.md @@ -1,65 +1,27 @@ # Secrets -T3 Code can read credentials from a secret provider, so the credential stays in your password -manager and T3 Code saves only a reference to it. Agents can also ask you for a secret in a -private card instead of in the chat. +Keep credentials in 1Password instead of storing raw values in T3 Code, and let agents request one-off secrets in a private card instead of chat history. -The Secrets settings page is in preview and is not in every build yet. Secret requests from agents -work everywhere. +> Note: **Settings → Secrets** is in preview and may not appear in every build. In-thread secret request cards from agents work everywhere. -## Secret providers +## Connect 1Password -1Password is the supported provider. T3 Code reads secrets with the -[1Password CLI](https://developer.1password.com/docs/cli/) (`op`), so `op` must be installed and -signed in on the machine that runs the T3 Code server. When you use T3 Code on another machine or -from your phone, that is the remote machine, not the device in front of you. +Install and sign in to the [1Password CLI](https://developer.1password.com/docs/cli/) (`op`) on the **T3 Code server machine**. On headless or remote servers, use a [1Password service account](./secrets-1password-service-account.md) or [1Password Connect](./secrets-1password-connect.md) so `op` doesn't wait for desktop approval. -A desktop sign-in asks for approval on that machine, which a remote user cannot answer. On a remote -or headless server, sign `op` in with a [service account](./secrets-1password-service-account.md) or a -[Connect server](./secrets-1password-connect.md) instead. +1. Open **Settings → Secrets → Add provider** (configured per environment). +2. Enter a name and the 1Password account shorthand, sign-in address (without `https://`), or ID from `op account list`. -To add one, open **Settings → Secrets**, select **Add provider**, and enter a name and the -1Password account: the shorthand, sign-in address (without `https://`), or ID that -`op account list` shows. Secret providers belong to the environment you are connected to. Each -environment keeps its own list. +## Use secret references -## Use a secret reference +Credential fields in Settings (provider env vars, source control tokens, usage keys, device host tokens) include a source picker: choose **Value** for a literal value or select your 1Password provider and paste a reference like `op://vault/item/field`. -Credential fields in Settings, such as provider environment variables and credentials, source -control tokens, usage limit keys, and device host tokens, show a source picker next to the field. -Pick **Value** to save the credential itself, or pick a secret provider and enter a reference such -as `op://vault/item/field`. Copy the reference from 1Password with **Copy Secret Reference**. -Select the check button next to a reference to read it now. If it reads, providers that use it -start using the new value. - -T3 Code reads the secret when it needs it, for example when a provider starts. Change the -credential in 1Password and refresh to use the new value. - -## When a secret cannot be read - -If 1Password is locked or signed out, the provider or feature that needs the secret shows an error -naming the secret provider. Unlock 1Password on the server's machine, then select **Refresh** in -**Settings → Providers**. T3 Code never replaces a saved credential it cannot read with another -login. - -## Remove a secret provider - -When you remove a secret provider in **Settings → Secrets**, T3 Code lists the fields that read -from it. Removing it clears those fields, so set them again before you need them. The secrets in -1Password are not touched. +- Click the check button to verify a reference immediately. +- T3 Code reads secrets on demand (e.g. when starting a provider). If 1Password is locked, unlock it on the server and click **Refresh** in **Settings → Providers**. +- Removing a secret provider clears fields referencing it in T3 Code without touching 1Password. ## When an agent asks for a secret -An agent that needs a token or password shows a secret request card in the thread instead of asking -you to paste it into the chat. Type or paste the value and select **Save securely**, or select -**Decline**. You can answer from web, desktop, or mobile. - -If the environment has a secret provider, the card also lets you pick it and enter a reference -instead of the value. Answering with a reference needs permission to manage providers, as saving a -reference in Settings does; a session without it sees only the value field. T3 Code reads the secret once, when you answer. If 1Password is locked, the -card says so and the request stays open: unlock it and try again, or enter the value. +When an agent calls `request_secret`, T3 Code displays a private card in the thread (web, desktop, and mobile) instead of asking you to paste into chat. -The value never appears in the conversation. Most requests keep it from the agent too: T3 Code -passes it to the tool that needs it. When an agent has to run a command with the value, the card -says so instead: the value goes into a private file that the agent's commands can read for about 24 -hours. +- Enter a value (or pick a 1Password reference if configured and permitted) and click **Save securely**, or **Decline**. +- Values never appear in conversation history. For T3 tools, the secret is passed directly without exposing it to the agent; for shell commands, the card tells you that the value is written to a private temporary file readable by the agent's commands for ~24 hours. diff --git a/docs/user/snap-shot.md b/docs/user/snap-shot.md index ec554b5161f6c..975ba065da7db 100644 --- a/docs/user/snap-shot.md +++ b/docs/user/snap-shot.md @@ -1,99 +1,25 @@ # SnapShots -A SnapShot captures the window you are working in and attaches it to your current draft. The -attachment carries the app name and window title, and when available the app icon and the window's -accessibility data (its controls, text, and their positions in the image). Agents can use that data -to reason about the screenshot. +Capture any window on your desktop—along with its app name, window title, and accessibility text/controls—and attach it directly to your current draft so agents can reason about what's on screen. -SnapShots are off by default and available in the desktop app on macOS, Windows, and Linux with -Wayland. X11 sessions are not supported. +Available in the desktop app on **macOS**, **Windows**, and **Linux (Wayland)** (X11 is not supported). Off by default. -## Turning it on +## Setup and usage -Open **Settings** > **SnapShots** and turn the feature on. Setup has two steps: allow capture, then -choose a shortcut. Each step shows only what your desktop needs. **Finish later** turns capture back -off but keeps anything you already installed, so you can resume where you left off. +1. Enable **Settings → SnapShots** and complete the platform permission and shortcut steps. + - **macOS**: Requires Screen Recording (and Accessibility only if **Include app text** is enabled). + - **Windows**: No extra permissions required. + - **Linux (Wayland)**: Uses a compositor-specific helper/extension (see below). +2. Switch to any window and press the shortcut (default on macOS/Windows: **both Shift keys together**). T3 Code attaches the capture to your active draft (or starts a new draft) and brings itself to the front. -- **macOS** asks for Screen Recording during setup. It asks for Accessibility only when **Include - app text** is on. -- **Windows** needs no setup or permission. -- **Linux** depends on your desktop. See [Linux desktops](#linux-desktops). +- **Include app text**: Toggle in **Settings → SnapShots** to include or omit accessibility tree data (not every app exposes document/terminal contents; slow apps fall back to screenshot-only). +- **Sound, flash, and animation**: Each can be toggled independently in Settings. +- **Customize shortcut**: Pick a modifier pair (macOS/Windows) or key chord in Settings (Linux uses key chords only). -Turning capture off releases the shortcut. It does not uninstall a helper or extension you installed. +## Linux Wayland desktops -## Taking a capture - -Switch to the window you want and press the shortcut. The default on macOS and Windows is both -Shift keys together. T3 Code attaches the image to your draft and brings itself forward. If no thread -is open it starts a draft in the current project. - -Pressing the shortcut while T3 Code is in front captures T3 Code itself. - -Pending captures are kept on disk until the attachment is saved to the draft, so a capture survives -closing the app mid-way and is attached on the next launch. Captures rejected because the image is -too large are discarded. - -## Changing the shortcut - -Select the shortcut in Settings, press the new keys, then **Save**. On macOS and Windows you can use -a modifier pair such as Command+Command or Ctrl+Ctrl, or a key chord. T3 Code refuses shortcuts -that collide with its own keybindings or that the operating system already reserves. - -On Linux, choose a key chord; modifier pairs are not supported. On Niri and Hyprland the shortcut -lives in your compositor config, so **Change shortcut** reopens setup to review the change. - -## Include app text - -**Include app text** controls whether captures include the window's accessibility data. Turn it off -to attach screenshots only. On macOS this also drops the Accessibility permission requirement. - -Availability depends on the app. Some apps expose only their window controls, not the document or -terminal contents. If an app is slow to answer, T3 Code attaches the screenshot without the data -rather than waiting. - -On GNOME, browsers may need app accessibility enabled in the desktop's accessibility settings before -they expose text. Restart the browser after enabling it. - -An icon beside the app name on an attachment shows whether accessibility data was included. Select -it to inspect what was captured. - -## Sound, flash, and animation - -Settings controls the capture sound, the brief flash on the captured window, and the animation that -flies the image into your draft. Each can be turned off independently. The operating system's -reduced-motion setting also disables the animation. - -## Linux desktops - -SnapShots work on Wayland sessions. Each desktop provides capture differently, and setup names your -current desktop and shows only what it needs. Preferences carry across desktops, but each desktop's -helper and shortcut approval are separate. - -**GNOME.** Install the bundled **T3 Code SnapShots** extension during setup. It is installed -per-user, offline, and needs no administrator password. Sign out and back in after the first -install so GNOME discovers it, then enable it from setup or from GNOME's Extensions app. If GNOME -has disabled all user extensions, turn them on there first. Disable or remove the extension in -GNOME's Extensions app to revoke access. - -**KDE Plasma 6.** Install the bundled capture helper during setup; no sign-out is needed. If the -shortcut does not fire, check T3 Code under **System Settings** > **Keyboard** > **Shortcuts**. If a -shortcut using Shift and a number does not work on your keyboard layout, use a letter chord instead. -Remove the helper from **Manage capture** > **Access** > **Advanced**. - -**Hyprland and Omarchy.** Install the bundled helper during setup, then choose a shortcut and select -**Review changes**. T3 Code shows the exact change it will make to your Hyprland config. **Save -shortcut** writes only that change, keeps a backup, and reloads Hyprland. Approve the screen-sharing -prompt for the helper if one appears. On Omarchy, bind in your own config, not the shipped defaults. -Some Hyprland versions return an "access denied" image instead of an error when capture is blocked; -check the helper's screen-sharing permission. - -**Niri.** Choose a shortcut and select **Review changes**. T3 Code shows the exact binding it will -add to your Niri config, validates the result, keeps a backup, and saves it when you approve. Niri -reloads the config on its own. The binding needs the `gdbus` command, normally part of your -distribution's GLib tools. Remove the line from your config to release the key. - -**Other Wayland desktops.** T3 Code uses the desktop's screenshot portal when it can capture the -active window. Otherwise Settings shows **Manual capture only** and the shortcut opens the desktop's -window picker. Picker captures do not include accessibility data. - -Apps running through XWayland inside a Wayland session can still be captured. +- **GNOME**: Installs the per-user **T3 Code SnapShots** extension (sign out and back in once to enable it; revoke via GNOME Extensions). +- **KDE Plasma 6**: Installs the bundled capture helper (manage shortcuts in **System Settings → Keyboard → Shortcuts**; remove via **Manage capture → Access → Advanced**). +- **Hyprland / Omarchy**: Installs the helper and previews the exact config binding before saving a backup and reloading (approve screen-sharing if prompted). +- **Niri**: Previews, validates, and adds the binding to your Niri config (requires `gdbus`). +- **Other Wayland desktops**: Uses the screenshot portal or falls back to a manual window picker (without accessibility data). XWayland windows inside Wayland are supported. diff --git a/docs/user/source-control.md b/docs/user/source-control.md index d436cd64eb144..589fca15f446c 100644 --- a/docs/user/source-control.md +++ b/docs/user/source-control.md @@ -1,455 +1,90 @@ # Source control -T3 Code integrates with GitHub, GitLab, Forgejo, Gitea, Bitbucket, Azure DevOps, GitCafe, and Cursor -Origin to clone and publish repositories, create pull requests, and review changes. - -## Review turn changes - -A turn's changed files and diff show only the turn's own work. When a turn pulls, merges, or -rebases, the files Git brought in are left out. A file stays in the list when the turn edited it, -committed it, or fixed a conflict in it. Use the branch comparison to review everything that changed -against your base branch. Restore still returns the complete saved workspace. - -In a [project with several repositories](multi-repo-projects.md), -the Diff pane shows every repository the turn changed. Use the repository picker next to the source picker to narrow the diff to one of -them. Paths in the diff start at the thread's folder, so the same file name in two repositories -stays apart. This works when the project folder itself is not a Git repository; the branch -comparison and uncommitted changes read one repository at a time, chosen from the same picker. - -The thread details panel lists each repository the thread has changed, most recent first, with its -branch and uncommitted changes. Expand one to commit, push, or open a pull request in that -repository; a pull request opened there, or already open for its branch when a turn ends, is linked -to the thread. **Other repositories...** adds any other repository of the project to the list until you -reload. In a worktree thread of a project with several repositories it adds a worktree of that -repository to the thread instead; see [Worktree threads](multi-repo-projects.md#worktree-threads). A -worktree thread of a single repository does not offer it. - -On web and desktop, open the Diff pane source picker and choose **Commits** to review one local -commit at a time. The list shows the newest 100 commits in the branch comparison. A merge commit -shows its changes against its first parent. - -A commit link from a supported code host opens in the Diff pane when the thread's repository has -that commit locally, on any branch. Otherwise a pull request commit link opens the pull request. Other -commit links follow your **Open links in** setting; on web, when that opens a new tab, T3 Code first -shows an **Open link** button. Command/Ctrl+Click always opens the link in your browser. Commit links follow the **Open pull requests in T3 Code** -setting in **Settings → Diffs**. +T3 Code integrates with GitHub, GitLab, Forgejo, Gitea, Bitbucket, Azure DevOps, GitCafe, Cursor Origin, and Linear to clone/publish repos, review and merge pull requests, manage issues, and watch CI. ## Connect an account -Install Git and configure authentication on the machine running your T3 Code server. For a remote -environment, do this on the remote machine. After signing in, open **Settings → Source control & issues** -and choose **Rescan**. - -### GitHub - -T3 Code talks to GitHub's API directly and only needs a token. Any of these works, in this -order of precedence: - -1. A token saved in **Settings → Source control & issues → GitHub**. It is kept in the server's secret - store, and works without the GitHub CLI. -2. `GH_TOKEN` (`GH_ENTERPRISE_TOKEN` with `GH_HOST` for GitHub Enterprise Server) in the - server's environment. -3. [GitHub CLI](https://cli.github.com/) 2.81.0 or newer, signed in with `gh auth login`. - -If `gh` is signed in to several accounts or hosts, expand **GitHub** in the same place to pick -the account each host uses or turn a host off. A saved token or `GH_TOKEN` takes precedence -over that choice; a host turned off stays off either way. - -For GitHub Enterprise, sign in with `gh auth login --hostname YOUR_HOST`. T3 Code treats a -custom server name as GitHub once it has a credential for that host. - -### Forgejo and Gitea - -Install [Forgejo CLI (`fj`)](https://codeberg.org/forgejo-contrib/forgejo-cli) or -[Gitea CLI (`tea`)](https://gitea.com/gitea/tea) 0.16 or later on your T3 Code server. -Sign in with `fj --host https://your-server auth add-token` or `tea login add`. -Repeat for each server you use, including Codeberg. - -T3 Code prefers a matching `fj` login and falls back to `tea` when `fj` is unavailable -or has no login for that server. Once an account is selected, failed actions stay on that -account. Settings shows the detected CLI. Forgejo and Gitea share one integration entry. -Servers hosted under a URL subpath, such as `https://example.com/forgejo`, use `tea` because -fj does not preserve the subpath when checking its account. - -When cloning or publishing, use a full repository URL to select a specific server. -You can use `owner/repo` when only one fj server is configured, or with your default `tea` -login when fj is unavailable or unconfigured. With multiple fj servers, use the full URL. -If you have multiple `tea` accounts on one server, select one with -`tea login default `. Git push and clone also need Git credentials or an SSH key -for that server. - -### GitLab - -Install [GitLab CLI](https://gitlab.com/gitlab-org/cli), then sign in: - -```bash -glab auth login -``` - -### Bitbucket - -Open **Settings → Source control & issues**, expand **Bitbucket**, and enter one of: - -- **Access token**: a token created for one repository, project, or workspace. It can only reach - what it was created for. -- **Atlassian account email** and **API token**: an Atlassian API token for your account. It can - reach every repository you can. Give it read/write access to repositories and pull requests, plus - user read access (`read:user:bitbucket`) and workspace read access (`read:workspace:bitbucket`). - -A field saves when you leave it, and applies right away. The access token wins when both are saved. -Credentials are saved on the environment's server, so select a remote environment to configure -it. Saved tokens can't be viewed again; enter a new one to replace it, or choose **Remove** to clear -everything saved for Bitbucket. - -If no credentials are saved, T3 Code falls back to these variables in the server's environment. -Restart the server after changing them: - -```bash -export T3CODE_BITBUCKET_ACCESS_TOKEN="your-access-token" -# or -export T3CODE_BITBUCKET_EMAIL="you@example.com" -export T3CODE_BITBUCKET_API_TOKEN="your-token" -``` - -For a background service, put these `KEY=VALUE` entries in -[`service.env`](./background-service.md#configure-the-service-environment) -under T3 home, then run `t3 service restart`. Service installation and updates -preserve that file. - -### Azure DevOps - -Install [Azure CLI](https://learn.microsoft.com/en-us/cli/azure/), add the DevOps extension, and sign in: - -```bash -az extension add --name azure-devops -az login -``` - -### GitCafe - -Install the GitCafe CLI and sign in: - -```bash -bun install -g @gitcafe/cli -cafe auth login --host https://git.cafe/api -``` - -Alternatively, open **Settings → Source control & issues**, expand **GitCafe**, and enter a token. It is -kept in the server's secret store, applies right away, and is used before `CAFE_TOKEN` and the -`cafe` login. Or set `CAFE_TOKEN` in the server's environment and restart it. Both tokens are only -sent to `git.cafe`; `CAFE_TOKEN` follows `CAFE_HOST` if you set it. Repositories on -`staging.git.cafe` need their own login with `--host https://staging.git.cafe/api`. - -Line comments are not available for GitCafe pull requests yet. -Merging a stack lands it through GitCafe, and updating a branch restacks the layers above it. - -### TanStack Source - -TanStack Source is in private beta, so the server shows it only when its environment turns the flag -on: `export T3CODE_FEATURE_FLAGS=tanstack_source` in your shell profile, then restart T3 Code. Separate -several flags with commas. A value already set in the server's own environment, such as a service -definition, is used instead of the profile. Install its CLI and sign in: - -```sh -curl -fsSL https://source.tanstack.com/install | sh -src auth login --web -``` - -Alternatively, open **Settings → Source control & issues**, expand **TanStack Source**, and enter a token -from `https://source.tanstack.com/settings/tokens`. A saved token is used before `SRC_TOKEN`, which is -used before the `src` login. With several `src` logins, pick the account there too. +Install Git and authenticate on the machine running your T3 Code server (for remote environments, do this on the remote machine), then click **Rescan** in **Settings → Source control & issues**. -Pull requests show the runs of TanStack Source CI with their logs, and update live while open. An -agent can open a private pull request on a public repository when you ask for one: its branch goes -to the repository's private companion and never to the repository itself. Issues -can be listed, filed, edited, commented on and closed. Reactions and picking reviewers or assignees -from a list are not available yet. +| Host | Setup | +| ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **GitHub** | 1) Save a token in **Settings → Source control & issues → GitHub**, 2) set `GH_TOKEN` (`GH_ENTERPRISE_TOKEN` + `GH_HOST` for Enterprise), or 3) sign in with [GitHub CLI](https://cli.github.com/) 2.81.0+ (`gh auth login`; use `--hostname` for Enterprise). Pick accounts or disable hosts in Settings when multiple `gh` logins exist. | +| **GitLab** | Install [GitLab CLI](https://gitlab.com/gitlab-org/cli) and run `glab auth login`. | +| **Forgejo / Gitea** | Install [`fj`](https://codeberg.org/forgejo-contrib/forgejo-cli) (`fj --host https://your-server auth add-token`) or [`tea`](https://gitea.com/gitea/tea) 0.16+ (`tea login add`). Prefers `fj`, falls back to `tea` (use `tea` for subpath-hosted servers). Use full URLs when multiple servers exist. | +| **Bitbucket** | Save a repo/project/workspace **Access token** or **Atlassian email + API token** (with repo/PR read-write, `read:user:bitbucket`, `read:workspace:bitbucket`) in **Settings → Source control & issues → Bitbucket**, or set `T3CODE_BITBUCKET_ACCESS_TOKEN` / `T3CODE_BITBUCKET_EMAIL` + `T3CODE_BITBUCKET_API_TOKEN` in the server env (or [`service.env`](./background-service.md#configure-the-service-environment)). | +| **Azure DevOps** | Install [Azure CLI](https://learn.microsoft.com/en-us/cli/azure/), run `az extension add --name azure-devops`, then `az login`. | +| **GitCafe** | Save a token in Settings, set `CAFE_TOKEN` (+ `CAFE_HOST`), or install `@gitcafe/cli` and run `cafe auth login --host https://git.cafe/api`. Line comments are not yet supported; stack merges/updates are native. | +| **Cursor Origin** | Install [Origin CLI](https://cursor.com/docs/origin/cli) and run `origin auth login` (`origin auth setup-git` if push prompts for credentials). Uses private HTTPS repos; GitHub-mirrored PRs stay on GitHub. | +| **TanStack Source** (private beta) | Set `T3CODE_FEATURE_FLAGS=tanstack_source` and restart the server. Save a token in Settings, set `SRC_TOKEN`, or run `src auth login --web`. Supports live CI logs, private PRs on public repos, and issues. | -### Cursor Origin - -Install the [Origin CLI](https://cursor.com/docs/origin/cli) and sign in. Signing in also sets up Git -credentials for `origin.cursor.com`: - -```bash -curl -fsSL https://downloads.cursor.com/origin/install.sh | sh -origin auth login -``` - -If cloning or pushing asks for a username, run `origin auth setup-git` to point Git at the CLI's -credentials again. Origin repositories use HTTPS and are published privately. Repositories mirrored -from GitHub keep their pull requests on GitHub; open those from the GitHub remote. +> Note: Git `push` and `clone` still require Git SSH/HTTPS credentials on the server, separate from API tokens. ## Start, clone, or publish a project -To start from nothing, choose **New project** in the command palette (`Cmd/Ctrl+K`), or -**New project** under **Add Project** on any client, and type a name. T3 Code makes a Git -repository in `~/.t3/projects` (the `projects` folder of your T3 data directory) with a README, -an icon, and a first commit, then opens a new thread in it. Until the project has a thread, new -threads work in its folder, even when your default is a new worktree. The folder is named after the project, -like `pinball-stats` for "Pinball Stats". Turn on **Create private repository on GitHub** to also -publish it. If Git has no name or email on that machine, the project is created without the -first commit. - -Use **Add Project** in the command palette (`Cmd/Ctrl+K`) to clone a repository. Choose a hosting -provider or paste a Git URL, then choose where to save it. Only GitHub is listed at first. To list -another provider here and in **Publish Repository**, turn on its switch under -**Settings → Source control & issues**. A branch or file page copied from GitHub, -GitLab, GitCafe, Codeberg or Bitbucket also works: T3 Code clones that repository's default branch. -On other hosts, paste the repository's clone URL. The project opens right away while the -clone runs in the background: you can write your first prompt, and sending waits until the files -are in place. A toast tracks progress and lets you cancel; if the clone fails, retry it from the -toast or from the banner above the composer. When the host refuses the machine's SSH key, T3 Code -clones over HTTPS with Git's credentials for that host instead, and the project's remote uses the -HTTPS URL. - -To lay clones out like [ghq](https://github.com/x-motemen/ghq), turn on **Clone into host folders** -under **Settings → Threads** (or **Source control** on mobile). Clones then default to -`//` under **Add project starts in**, so set that to `~/ghq` to share ghq's -folders. You can still change the destination before cloning. - -For a local Git repository without a remote, **Publish Repository** creates a hosted repository, -adds it as `origin`, and pushes your commits. If there are no commits yet, it creates the remote; -make your first commit before pushing. - -## Create a pull request - -Use a thread's Git actions to commit, push, and create a pull request. T3 Code can generate commit -messages, review titles, and descriptions from your changes. Descriptions also draw on the work in -the thread, including the checks it ran. - -An existing fork PR can appear beside the branch even if you pushed without setting an upstream. -If its badge is missing because several remotes hold that branch, set the branch's upstream to -the intended remote with `git branch --set-upstream-to=/`. - -Choose how commit messages and pull request titles and descriptions are written in -**Settings → Source control & issues → Commits & pull requests**. **Repository conventions** uses the -project's instructions and recent commit subjects. **Custom instructions** applies your own -instructions to commits and pull requests. - -## Review and merge - -Open **Pull requests** to review changes and comments, request reviewers, check out a branch, -or merge. You can edit review titles and descriptions and your own comments where the host allows it. -Where you can edit a description, you can also tick its checkboxes from the Summary tab -(the Overview tab on mobile). -GitLab calls these merge requests. - -A merge or review applies to the commits you opened the pull request on. When someone pushes -meanwhile, the web and desktop apps offer **Load new commits**; until you do, a merge or review is refused and your -review draft is kept. Merging from a thread's pull request row, or from the list, lands the head that -row had when you confirmed. - -Save a filter setup with **Views → Save current view** on the Pull Requests page. For example, choose -**Reviewing** (**Your review** on mobile) and save it as "PRs Requesting My Review". Choose a saved view to restore its search, -filters, sort order, and server/project scope. After changing filters, use **Update saved view** to -keep the changes, or save another view. You can also rename or delete views from the same menu. -Saved views stay in the browser or app where you created them and do not sync across devices. - -A link to part of a pull request opens that part: a comment or review is marked in the activity, a -changed-line link opens the file at those lines, a checks link opens the checks, and a commit link -opens that commit's changes. On web and desktop, hovering a comment or commit link previews it. - -On mobile, **Pull requests** lists reviews across your connected environments. Open a review -to read its description, activity, commits, and changed files. Line comments stay as drafts -until you submit the review. **Work on PR** opens a chat with the review attached; sending -the first message prepares a worktree from the review's branch. - -Previously loaded lists, review details, guides, and diff pages remain readable on mobile -without a connection, including after restarting the app. Saved content refreshes when the -environment reconnects; submitting changes requires a connection. - -Enable **Remove agent credits when merging** in Settings → Source control & issues to remove recognized -agent co-author and generated-by lines from GitHub merge and squash commit messages. Human -co-authors stay credited. The setting is off by default and projects can override it. It also -applies to auto-merge, but not merge queues or native stack merges. Original commits keep their -messages, so merge and rebase can still retain agent credits in those commits. - -On web and desktop, hold **Shift** in the GitHub pull request list for quick actions. -To close several, press **Close**, drag across the rows in the same group, and release. -Press **Escape** before releasing to cancel. Failed closes stay in the list so you can retry them. +- **New project**: Run **New project** from the command palette (`Cmd/Ctrl+K`) or **Add Project** to initialize a new Git repo in `~/.t3/projects/` with a README, icon, and first commit (optionally creating a private GitHub repo). +- **Clone**: Use **Add Project** to pick a host (enable non-GitHub hosts in **Settings → Source control & issues**) or paste a Git URL or web page URL. Cloning runs in the background so you can draft your first prompt immediately; falls back to HTTPS if SSH auth fails. Enable **Clone into host folders** (**Settings → Threads**, or **Source control** on mobile) for `ghq`-style `//` paths. +- **Publish**: For a local repo without a remote, **Publish Repository** creates the remote, adds `origin`, and pushes commits. -GitHub, GitLab, and Azure DevOps support auto-merge while checks are outstanding. GitHub also -supports approving waiting fork workflows and opening a revert pull request for a merged change. - -Pull request sharing is off by default. In Settings → Environments → Pull request sharing (Pull -request routing under Environments on mobile), choose **Read PRs** or **Read and act** for each -environment you trust to share its source control access. -Enable both the original environment and the environment answering its requests on this client. -**Read and act** can use broader permissions than the original environment's credential; -only enable it for environments you control and trust. Changing a saved endpoint or removing an -environment clears its permission. - -Review details, linked PR status, and permitted review actions can then use another connected -environment signed in to the same account on the same host. Each needs a project on that host. -A connected local environment is preferred for actions and can answer slow or failed reads. -Browsers and mobile clients need a paired environment to use its GitHub credentials. -Credentials stay on their machines. Previously verified credentials remain usable for routing -for ten minutes during a GitHub outage; new credentials must be verified first. An action with -an uncertain result is never automatically retried elsewhere. Listings, diffs, and checkout or -PR creation from Git actions continue to use the project's environment. - -For Azure DevOps, use the host website to change comments. Bitbucket does not support reopening a -declined pull request. - -### Review guides - -Review guides are in beta. Turn on **Review guides** in Settings → Source control & issues to add the -**Guide** tab to pull requests on that server. On mobile, move between stops with **Next** -and the back button; a stale guide offers a rewrite and hides excerpts that no longer match -the current change. - -The **Guide** tab gives you a tour of a pull request without reading it line by line: stops -through the change in reading order. Each stop points at the lines worth reading, and a stop marked -**Look closely** has a call only a maintainer can make. Mechanical changes such as renames and -snapshots are grouped at the end, and every changed file appears somewhere on the tour. -Conversations already resolved in review are left out. For a pull request in a stack, the guide -covers that layer only, and may point out what a lower layer introduced or what a higher one uses. - -Choose **Write guide** to have the review guide model from Settings → Source control & issues read the -change in a temporary checkout; without one set, the source control writer model is used. Nothing -in the checkout is changed, and a large pull request takes a few minutes; you can go elsewhere in -the app. On web, you are told when the guide is ready; on mobile, return to the guide to check -its progress. Claude and Codex can write guides. Claude writes them with your user settings, but -tool approvals in those settings do not apply: it reads files and runs `git diff`, `git log` and -`git show`, nothing else. The guide is -kept for everyone using this server. To write it again, for example after a push or after changing -the model or instructions, choose **Rewrite guide** from the pull request's **⋯** menu. - -On web, while reading a stop, select lines in an excerpt to add a comment to your review or ask an agent -about them; comments wait with the ones from the **Code** tab until you send the review. Choose a -suggested question, or **Ask about this stop**, to open a thread that already knows which stop you -are on. **Finish review** on the last stop opens the review with everything you collected. - -Agents can write guides too: ask one to prepare guides for a set of pull requests, and it starts -them for you. Each is read through the project whose checkout has that repository. - -To shape guides to your taste, write **Review guide instructions** in Settings → Source control & issues, -such as what to show first or what to skip; projects can override them. They change emphasis and -ordering, not the guide's layout or which files it covers. +## Review turn changes -### Mark files as viewed +A turn's diff shows only that turn's own edits, commits, and conflict fixes—excluding unrelated files brought in by a pull, merge, or rebase. Use the branch comparison to view everything changed against your base branch. -Tick a file off in the **Code** tab once you have read it and it collapses; the toolbar keeps a -running count. A tick belongs to the pull request rather than to a commit, so scoping the tab to a -single commit keeps them. A file pushed to after you cleared it comes back marked **Changed**. +- **Commits view** (web/desktop): Switch the Diff pane source picker to **Commits** to inspect the latest 100 local commits one by one. +- **Commit links**: Links to local commits open in the Diff pane (follows **Settings → Diffs → Open pull requests in T3 Code**; `Cmd/Ctrl+Click` opens in browser). +- **Multi-repo projects**: Use the repository picker in the Diff pane and expand per-repo rows in thread details. See [Projects with several repositories](./multi-repo-projects.md). -On GitHub these are GitHub's own viewed marks, so a review carries between T3 Code and github.com -in either direction. Forgejo, GitLab, Bitbucket, Azure DevOps, and Cursor Origin expose no record -T3 Code can read, so the server you are connected to keeps them instead: they follow you across the -apps connected to that server, but the host's own site will not show them, and the count reads **viewed in T3 Code**. +## Create, review, and merge pull requests -On mobile, open a changed file and mark it viewed from its header. Viewed files collapse, -and their marks follow the same rules as on web and desktop. +- **Create**: Commit, push, and open PRs from a thread's Git actions. Configure AI-generated commit/PR writing style in **Settings → Source control & issues → Commits & pull requests** (**Repository conventions** or **Custom instructions**). +- **Review**: Open **Pull requests** to inspect diffs, comments, checks, commits, and request reviewers. Draft line comments stay local until submitted. If new commits are pushed while you review, click **Load new commits** before merging or submitting. +- **Saved views**: Save and update filter/sort setups under **Views → Save current view** (stored per device). +- **Mark files viewed**: Check off files in the **Code** tab to collapse them (reopens as **Changed** on new pushes). Syncs natively with GitHub; stored on your T3 Code server for other hosts. +- **Mobile**: Open **Pull requests** across environments (cached lists, details, guides, and diffs stay readable offline). Tap **Work on PR** to start a worktree thread on the PR's branch. +- **Quick actions & options**: + - Enable **Remove agent credits when merging** in **Settings → Source control & issues** to strip recognized agent co-author/generated-by trailers on GitHub merge/squash commits (keeps human co-authors). + - Hold `Shift` in the GitHub PR list (web/desktop) to drag-close multiple PRs (`Esc` cancels). + - GitHub, GitLab, and Azure DevOps support auto-merge; GitHub also supports approving fork workflows and opening revert PRs. + - Azure DevOps comments must be edited on the host site; Bitbucket cannot reopen declined PRs. -## Troubleshooting +### Review guides (beta) -- **Not authenticated:** run the provider's login command on the server, then rescan. For Bitbucket, - check the credentials saved in Settings → Source control & issues, or confirm the running server received - the environment variables. -- **GitHub sign-in cannot be verified:** update GitHub CLI to at least 2.81.0, or save a token in Settings → Source control & issues. -- **Push fails despite a connected account:** check the Git remote's credentials. SSH and HTTPS - remotes can require separate setup from the hosting provider's API access. -- **A review cannot load:** open it on the host website while resolving connectivity, permissions, - or rate limits. +Turn on **Settings → Source control & issues → Review guides** to add a **Guide** tab to pull requests. Click **Write guide** to have Claude or Codex read the PR in a temporary read-only checkout and produce an ordered tour of the change (highlighting **Look closely** spots and grouping mechanical changes at the end). -## Linked pull requests +- Customize emphasis/ordering via **Review guide instructions** in **Settings → Source control & issues** (project-overridable). +- On web, select lines in any stop to add review comments or ask an agent about that stop. +- Agents can also generate guides for multiple PRs when asked. Choose **Rewrite guide** from the PR's **⋯** menu after new pushes. -A thread can hold several pull requests, including reviews from another repository on the same host. -Use **Link pull request** in the command palette or **Linked items** panel, or right-click a -pull request link in the conversation. Creating a pull request from Git actions links it automatically, -and so does an agent creating one with `gh pr create` or `glab mr create`. Agents can link other -pull requests with the `link_pull_request` tool. +### Pull request sharing across environments -Agents can also read, open, update, reply on, and merge pull requests in the thread's repository -through T3 Code's own tools, which use the same sign-in as the Pull requests page. An agent merges -only the commit it last read: if someone pushed since, the merge is refused. On github.com an -agent can also land a GitHub stack in one merge, like **Merge stack** below. +Disabled by default. In **Settings → Environments → Pull request sharing** (**Pull request routing** on mobile), opt in trusted environments to **Read PRs** or **Read and act** so review reads/actions can route through another connected environment signed into the same account on the same host (credentials never leave their machines). Enable on both source and target environments; only grant **Read and act** to environments you control. -Use **Link pull request to thread** in the command palette to keep a pull request with the thread. From a review -on the Pull requests page, **Link to thread** lets you search for an active thread. The review header -also lists the threads that link to it, including archived threads, so you can return to their context. +## Linked pull requests and watching -Thread badges show a stack's layer count or the current review number with a count of additional -links. Clicking a badge with more than one review opens the **Linked items** panel. On mobile, the Git overview lists linked reviews and their stacks; tap a review to open it. -Linking and unlinking are available in the web and desktop clients. +Threads can link multiple PRs (even across repos on the same host). Creating a PR via Git actions, `gh pr create`, `glab mr create`, or an agent's `link_pull_request` links it automatically; manage links from **Linked items** or the command palette. -The **Linked items** panel lists every review and groups stacks. Unlink a review from its -row menu. An unlinked stack layer stays out of later syncs. Open linked reviews refresh on the server; -closed reviews refresh periodically so reopening one on the host is detected. Merged reviews refresh -when requested. Settling a thread refreshes its open and closed reviews once; after that they stop refreshing until you unsettle it. With **Auto-settle merged threads** enabled, a thread can settle after every linked -review is terminal. An open or unsynced link keeps it active. +- **Agent PR tools**: Agents can read, open, update, comment on, and merge PRs in the thread's repo using your configured sign-in (refusing merges if the head moved since last read). +- **Watch / babysit a PR**: Ask an agent to watch or babysit a PR (or toggle it in **Linked items** / click the eye icon in thread details). The server polls every 2 minutes and wakes the agent on failed checks, passed required checks, new comments/reviews from others, conflicts, merge-queue drops, or merge/close. + - Watched threads stay in the **Working** section while checks run (or until merge/close if the agent is waiting to act) and never auto-settle. + - Watching stops automatically on merge/close, Stop, settle/archive, 10 comment-only wakes in a row, or 8 consecutive read failures. Subagents cannot watch PRs—the parent thread watches instead. -Ask the agent to watch, monitor, or babysit a pull request and it calls `watch_pull_request`. While -the thread is active, the server checks the pull request every two minutes and wakes the agent when a -check fails or waits for a maintainer's approval, the required checks pass, the other checks finish after a failure, someone else comments or reviews, or the branch starts to -conflict. On github.com it also wakes the agent, with GitHub's reason, when the merge queue drops -the pull request without merging it. Threads in a project that watch the same pull request share one check. On GitHub, a check -first asks whether anything changed and reads the pull request only when it did, which keeps -watching inside GitHub's rate limit. Comments from your own account do not wake it. When the pull -request merges or closes, watching ends, and the agent is woken once unless it merged or closed the -pull request itself with the host's CLI. A reopened pull request needs a new watch. Watching also ends after 10 wakes in a row that bring only comments, after 8 -failed reads in a row, or when you press Stop on the thread. A rate limit only pauses watching. -Settling or archiving a thread also ends all its watches. Unsettle the thread before starting a new -watch. Watching a pull request again does not repeat check or conflict news its last -watch already reported; unlinking the pull request clears that. Subagents cannot watch pull requests; the thread that delegated to them does. To start or stop -it yourself, use the row menu in the **Linked items** panel. In the thread details card, a -watched pull request shows an eye; click it to stop watching. +## GitHub stacks -A watched thread counts as working while the pull request still has checks running, so it stays in -the **Working** section, including after the agent pushes a fix. Once every check has finished, -including review bots that report as checks, the thread returns to your inbox: what happens next is -up to a person. That includes a workflow waiting for a maintainer to approve it, which runs only -once someone does. If you ask the agent to act on the pull request itself, such as merging it once -a teammate approves, the thread stays in **Working** until the pull request merges or closes. The -watch stays on and still wakes the agent on new comments, failed checks or conflicts, and a watched -thread never auto-settles. +The Pull requests page displays stack layer positions and navigation: -Cross-repository links use a project on the same host. Azure DevOps reviews require a project checked -out from the matching organization and repository. +- **Merge stack**: Merges the selected PR and every open layer below it together, respecting branch rules and merge queues. +- **Rebase stack**: Updates remote branches bottom-to-top without modifying your local checkout (may rewrite history and restart checks). ## Issues -The Issues page lists the issues of every project whose remote is on GitHub, GitLab, Azure -DevOps or Forgejo, grouped per tracker account. Open it from the sidebar's utility row or with -**Open issues** in the command palette. Filter by open or closed, by your involvement -(assigned, opened by you, mentioning you), and by tracker. Under **Projects**, uncheck the -projects you do not want to see; the list remembers them, and a project you add later shows. -The search box asks the tracker itself where it can search. Press **Load more** at the end of a group to read further back. -The **Views** menu saves and restores a search, filter, and sort setup, as it does for pull -requests. - -To list Linear issues beside a project's, connect Linear with an API key under -Settings → Source control & issues, then pick one or more teams for that project there. Pick -another team at any time to add it; uncheck every team to unbind the project. Each team's -issues appear in the Linear group of the issue list, sorted with the rest by last update, and -each can be loaded further on its own. Agents file new issues in the first team picked unless you name another bound team. To -connect another Linear workspace or user, add another account in the same place; each project -reads its teams through the account you picked them under. - -Select an issue to open it beside the list: description, comments, state changes, linked pull -requests, labels, assignees, and reactions. Linked pull requests open in the same panel. You can -comment, edit the title and description, change labels and assignees, react, and move it to -another state when the tracker and your account allow it. Where a GitHub repository has issue -statuses (Backlog, Todo, In progress, and so on), those are the states you move between, as a -Linear team's workflow states are; elsewhere you close or reopen, with a close reason where the -tracker records one. An issue read through a project that does not own its repository is shown read-only. +Open **Issues** from the sidebar utility row or **Open issues** in the command palette to browse, filter, search, save views, comment, edit, and transition issues across GitHub, GitLab, Azure DevOps, Forgejo, and Linear. -An issue can be kept with a thread the way a pull request can: open it beside the thread (issue -links in the conversation open there) and use **Link to this thread** in its header; **Unlink** -undoes it. Click the issue badge in the thread sidebar to see its issues and pull requests in -**Linked items**. Select an issue there to open it beside the thread. Agents link the issues they -work on with the `link_issue` tool. +- **Linear**: Connect an API key in **Settings → Source control & issues** and bind one or more teams per project (supports multiple Linear accounts). Agents file new issues in the first bound team unless another is named. +- **Link to threads**: Click **Link to this thread** on an issue beside a thread (or let agents call `link_issue`) to track it in **Linked items**. +- Remote issue writes require the `source-control:write` scope. -Writing to a tracker over a remote connection requires the `source-control:write` scope. - -## GitHub stacks - -The Pull requests page shows each PR's position in its GitHub stack. Open the stack badge in a -review to navigate its layers. **Merge stack** submits the selected pull request and every unmerged -layer below it to GitHub together, respecting branch rules and merge queues. The confirmation shows -the scope and merge strategy. GitHub rebases the remaining stack after merging. +## Troubleshooting -**Rebase stack** updates remote branches from bottom to top without changing your local checkout. -It can rewrite history and restart checks. If a layer fails, earlier updates remain; resolve that -layer before retrying. GitHub may require manual conflict resolution after a lower layer is amended, -even when its changes look independent. Stack actions require an environment that supports them. +- **Not authenticated**: Run the host's CLI login on the server and click **Rescan** (for Bitbucket/tokens, verify Settings or server env vars). +- **GitHub verification fails**: Upgrade `gh` to 2.81.0+ or save a token in Settings. +- **Push fails**: Check Git SSH/HTTPS credentials separately from API auth. +- **Fork PR badge missing**: Set upstream with `git branch --set-upstream-to=/`. diff --git a/docs/user/subagents.md b/docs/user/subagents.md new file mode 100644 index 0000000000000..64355ee71e34e --- /dev/null +++ b/docs/user/subagents.md @@ -0,0 +1,21 @@ +# Subagents and delegation + +T3 Code supports running parallel agents—either spawned natively by a provider or delegated through T3 Code's orchestration tools—so a parent thread can split up research, implementation, or reviews across models, worktrees, or machines. + +## Two kinds of subagents + +| Type | How it starts | Interactive? | Where approvals go | +| ---------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------- | -------------------------------------------------------- | +| **T3-delegated subagent** | Agent calls `delegate_task` (supports choosing another provider/model, an isolated git worktree, or a [linked machine](./remote-access.md#link-another-environment)) | Yes—has its own composer | In the child thread (and surfaced via parent) | +| **Provider-native subagent** | Spawned internally by Claude, Codex, Cursor, Antigravity, fx, or Pi | Read-only—message the parent thread instead | Bubbles up to the parent thread with the subagent's name | + +> Tip: Type `@` and part of a model name (such as `@opus` or `@opus:opencode`) in your prompt to tell the agent which model to delegate to without changing the current thread's model. + +## Follow and manage subagents + +- **Inspect**: Click a subagent card in the conversation or open **Agents** in the thread to view its timeline. +- **Side panel vs. main view**: On web and desktop, subagents open as a tab in the right panel by default (`Cmd`/`Ctrl`-click or middle-click opens in the main view). Change the default in **Settings → Chat → Open subagents and side chats in**. +- **Stopping & archiving**: Pressing **Stop** on a parent thread also stops its delegated subagents. Wait for or cancel active delegated tasks before archiving the parent thread. +- **Permissions**: A delegated subagent can never exceed its parent thread's [permission mode](./permission-modes.md). +- **PR watching**: Subagents cannot watch pull requests—the parent thread watches PRs instead. +- **Linked machines**: Delegating to a linked machine runs a regular thread on that host and wakes the parent when done; you can watch it live (read-only) without pairing directly ([Read a linked machine's threads](./remote-access.md#read-a-linked-machines-threads)). diff --git a/docs/user/t3-connect-troubleshooting.md b/docs/user/t3-connect-troubleshooting.md index 6dadd78be3032..6bba732a4342a 100644 --- a/docs/user/t3-connect-troubleshooting.md +++ b/docs/user/t3-connect-troubleshooting.md @@ -1,172 +1,85 @@ # T3 Connect troubleshooting -A T3 Connect connection goes through four parts, in this order: +A T3 Connect connection passes through four stages: 1. **This device** reaches T3 Connect over the internet. -2. **T3 Connect** checks your sign-in and the host's link. -3. **The host's tunnel** (cloudflared on the host) carries the request to the host. +2. **T3 Connect** verifies your sign-in and host link. +3. **The host's tunnel** (`cloudflared`) forwards the request to the host. 4. **T3 Code on the host** answers. -When a connection fails, open **Settings > Environments**, find the environment, -and select **Details**. The first part marked as failed is the cause. Find its -section below. - -To see the host's side, run `t3 connect status` on the host, or open -**Settings > Sharing & access** on the host. Both check the host's T3 Connect -address from the host, and say why it fails. `t3 connect` runs the same check -when it finishes setup. This check cannot test another device's network. For a -problem on one device, use **Details** on that device. +When a connection fails, open **Settings → Environments**, select the environment, and choose **Details**—the first failed stage identifies the cause below. On the host itself, run `t3 connect status` or check **Settings → Sharing & access**. ## The host's tunnel is offline -T3 Connect could not reach the host's tunnel. This means one of these: - -- The host is asleep, turned off, or offline. -- T3 Code is not running on the host. -- The host's network blocks the tunnel. See - [Port 7844 is blocked on the host](#port-7844-is-blocked-on-the-host). - -Fix: +T3 Connect could not reach the host's tunnel (host is asleep/offline, T3 Code isn't running, or outbound port 7844 is blocked). -1. Make sure the host is awake and T3 Code runs on it. -2. On the host, run `t3 connect status`. It names the problem on the host's side. -3. If the host was offline for a long time, T3 Connect removes its tunnel. Start - T3 Code on the host and update it to the latest version. It gets a new tunnel. +1. Confirm the host is awake and running T3 Code. +2. Run `t3 connect status` on the host. +3. If the host was offline for 7+ days on an older version, start and update T3 Code on the host to recreate its tunnel. ## Port 7844 is blocked on the host -The tunnel on the host connects out to Cloudflare on port 7844, with TCP and -UDP. Both tunnel protocols (QUIC and HTTP/2) use this port. When the host's -network blocks it, the tunnel cannot start, but normal web traffic still works. -The host looks online, so this problem is easy to miss. - -Common causes: - -- **A Tailscale exit node on the host.** All of the host's internet traffic goes - through the exit node, and that network blocks port 7844. Turn off the exit - node on the host with `tailscale set --exit-node=`, or allow outbound port - 7844 on the exit node's network. -- **A VPN on the host.** Work VPNs often block unknown ports. Ask for port 7844 - to be allowed, or use a direct route instead (see below). -- **A firewall or strict network.** Allow outbound TCP and UDP port 7844. +`cloudflared` connects outbound to Cloudflare on **TCP and UDP port 7844** (normal web traffic still works when 7844 is blocked). -If you cannot unblock the port, you can connect without T3 Connect. When the -host and this device are on the same Tailscale network, add the host's -Tailscale address as a direct route. See -[Reach one machine several ways](./remote-access.md#reach-one-machine-several-ways). +- **Tailscale exit node**: Run `tailscale set --exit-node=` on the host or allow outbound 7844 on the exit node. +- **Work VPN / firewall**: Allow outbound TCP/UDP 7844, or bypass T3 Connect by adding a direct Tailscale route ([Reach one machine several ways](./remote-access.md#reach-one-machine-several-ways)). ## The tunnel works, but T3 Code does not answer -The host's tunnel is up, but it cannot reach T3 Code on the host. Common causes: +The tunnel is up, but T3 Code didn't respond on `127.0.0.1` (crashed, starting up, port changed, or `T3CODE_HOST` bound only a non-loopback IP). -- T3 Code on the host stopped, crashed, or is still starting. -- T3 Code restarted on a different port, for example after an update, and the - tunnel still points at the old port. -- The server binds only one network address with `T3CODE_HOST`. The tunnel - sends requests to `127.0.0.1`, so the server must also listen there. - -Fix: restart T3 Code on the host. For the background service, run -`t3 service restart`. Then run `t3 connect status` on the host. +Restart T3 Code on the host (`t3 service restart` for a background service) and run `t3 connect status`. ## The T3 Connect address does not resolve or answer -The host's T3 Connect address did not resolve, refused the connection, failed a -secure (TLS) connection, or did not answer in time. - -Fix: +The host's T3 Connect address failed DNS, TLS, connection, or timed out. -1. Make sure the host is awake and online. -2. On the host, run `t3 connect status`. -3. If the check fails only on the host, check the host's DNS, VPN, or proxy. - If it says the host's network has an old cached answer, wait: it usually - clears within about 30 minutes. -4. If it says the address no longer points to this machine's tunnel, the - environment was likely removed from T3 Connect. Link it again: on a desktop - host, turn **T3 Connect** off and on in **Settings > Sharing & access**. On a - command-line host, run `t3 connect link`, then restart T3 Code. +1. Confirm the host is online and run `t3 connect status`. +2. If only the host fails, check DNS/VPN/proxy (stale DNS caches clear in ~30 minutes). +3. If the address no longer points to this host, re-link it: toggle **T3 Connect** off and on in **Settings → Sharing & access**, or run `t3 connect link` and restart the server. ## This device can't reach T3 Connect -The problem is on this device's network, not on the host. This device could -not reach T3 Connect, or it reached T3 Connect but not the host's tunnel -address. +The issue is on the client device's network: -Fix: - -1. Check this device's internet connection. On a captive or dead Wi-Fi network, - the device can look online but cannot reach anything. -2. A VPN, firewall, ad blocker, or DNS filter on this device can block T3 - Connect. Turn it off for a moment to test. -3. On iPhone, Connectivity Assist in the Wi-Fi settings can break T3 Connect. - Turn it off to test. -4. Try another network, or add a direct route to the host, such as its - Tailscale address. See - [Reach one machine several ways](./remote-access.md#reach-one-machine-several-ways). +1. Check for captive portals or dead Wi-Fi. +2. Temporarily disable VPNs, firewalls, ad blockers, or DNS filters (on iPhone, test turning off Wi-Fi **Connectivity Assist**). +3. Try another network or add a direct Tailscale route ([Reach one machine several ways](./remote-access.md#reach-one-machine-several-ways)). ## Sign-in, account, or link problems -This device's T3 Connect sign-in is not ready yet, or T3 Connect does not have -an active link between your account and the host. - -- **The host is linked to a different account.** Sign in to the same T3 Connect - account on this device and on the host. On the host, run `t3 connect logout`, - then `t3 connect`. -- **T3 Connect is off on the host, or the host only publishes agent activity.** - On the host, open **Settings > Sharing & access** and turn **T3 Connect** on, or - run `t3 connect`. -- **The host was linked, but the server did not apply the link yet.** Restart - the server on the host: quit and reopen the T3 Code desktop app, run - `t3 service restart`, or stop `t3 serve` and run it again. -- **This device's sign-in expired, or the host no longer accepts this - device.** Sign out of T3 Connect and sign in again. -- **This device is still loading its T3 Connect sign-in.** Wait a moment; - T3 Code retries on its own. If it keeps waiting, reload or restart T3 Code on - this device. -- **The host is waiting for you to approve this device.** The host requires - approval for new devices. Approve the code this device shows from a device - that is already connected, or run `t3 auth connect-device approve ` on - the host. See [Approve new devices](./remote-access.md#approve-new-devices). -- **Your account reached its tunnel limit.** Remove an environment you do not - use from your T3 account's T3 Connect page, or - [link a paid T3 Chat account](./remote-access.md#more-machines-with-t3-chat) - for a higher limit. Then restart T3 Code on the host. +- **Different account**: Sign in to the same T3 Connect account on both sides (on host: `t3 connect logout && t3 connect`). +- **T3 Connect disabled on host**: Turn on **Settings → Sharing & access → T3 Connect** or run `t3 connect`. +- **Link not yet applied**: Restart T3 Code on the host (`t3 service restart` or restart desktop app). +- **Expired session**: Sign out of T3 Connect and sign back in. +- **Waiting for device approval**: Approve the displayed code from an existing device or run `t3 auth connect-device approve ` on the host ([Approve new devices](./remote-access.md#approve-new-devices)). +- **Machine limit reached**: Deregister an unused host or [link a paid T3 Chat account](./remote-access.md#more-machines-with-t3-chat), then restart the host. ## The clock is off -T3 Connect signs requests with short-lived proofs. When the clock on this -device or the host is a few minutes wrong, T3 Connect rejects them. Turn on -automatic date and time on both devices, then retry. +T3 Connect uses short-lived signed proofs. Enable automatic date and time on both the host and client device, then retry. ## The host runs an older T3 Code -This app needs a newer T3 Code on the host. Update T3 Code on the host. See -[Updating T3 Code](./updating.md). +Update T3 Code on the host machine ([Updating T3 Code](./updating.md)). ## T3 Connect returned an error -| Error | Fix | -| --------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `environment_link_limit_exceeded` or managed tunnel limit | Remove an unused environment or link a paid T3 Chat account, then restart T3 Code on the host. | -| `auth_invalid` or `invalid_bearer` | Run `t3 connect login`. If credentials were revoked, run `t3 connect logout`, then `t3 connect` again. Restart the server after signing in. | -| Expired or invalid link proof | Check the host's date and time, update T3 Code, then restart it. | -| HTTP 403 without a recognized error | If the host requires approval for new devices, update T3 Code on this device and approve it. Otherwise check relay access, proxies, and firewall rules. Keep any Cloudflare Ray ID for a bug report. | -| HTTP 408, 429, or 5xx | Wait a few minutes. T3 Code retries temporary failures on its own. | - -After you fix a permanent rejection, restart the host's server with -`t3 service restart`. For a foreground server, stop it and run `t3 serve` again. +| Error | Fix | +| ------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------- | +| `environment_link_limit_exceeded` / tunnel limit | Deregister an unused host or link a paid T3 Chat account, then restart the host. | +| `auth_invalid` / `invalid_bearer` | Run `t3 connect login` (or `t3 connect logout && t3 connect`), then restart the server. | +| Expired or invalid link proof | Sync system clock, update T3 Code, and restart. | +| HTTP 403 (unrecognized) | If device approval is on, update the client and approve it; otherwise check proxies/firewalls and save any Cloudflare Ray ID. | +| HTTP 408, 429, or 5xx | Temporary—wait a few minutes for automatic retry. | -If T3 Code on the host disappears when SSH closes, see -[background-service troubleshooting](./background-service.md#troubleshooting). +After fixing a permanent error, restart the host (`t3 service restart` or restart `t3 serve`). If T3 Code stops when SSH disconnects, see [background-service troubleshooting](./background-service.md#troubleshooting). ## Report a problem -If none of this helps, open an issue on -[GitHub](https://github.com/pingdotgg/t3code/issues). Include: +Open an issue on [GitHub](https://github.com/pingdotgg/t3code/issues) with: -- The text from **Copy diagnostics** in the environment's **Details**. -- The output of `t3 connect status` on the host. -- The trace ID, if one is shown. -- If the tunnel dropped earlier, the host's tunnel log, `relay-client.ndjson` - in the logs folder (`~/.t3/userdata/logs` by default). It records when the - tunnel connected, warned, exited, and restarted, with the tunnel token - removed. +- **Copy diagnostics** from the environment's **Details** +- Output of `t3 connect status` on the host +- Trace ID (if shown) +- `~/.t3/userdata/logs/relay-client.ndjson` (tunnel tokens are already stripped) diff --git a/docs/user/t3-json.md b/docs/user/t3-json.md new file mode 100644 index 0000000000000..7b17b118ae3f3 --- /dev/null +++ b/docs/user/t3-json.md @@ -0,0 +1,80 @@ +# Project configuration (`t3.json`) and actions + +Check a `t3.json` file into your repository root to share project actions (setup, dev, test, and cleanup scripts), worktree defaults, icons, and multi-repo settings with everyone opening the repo in T3 Code. + +## Inheritance order + +Settings that `t3.json` can declare resolve in this order (first non-inherited value wins): + +1. **Project override** in Settings +2. **Environment setting** in Settings +3. **`t3.json`** in the repository +4. **Built-in default** + +## Schema reference + +Add `"$schema": "https://t3.codes/schema/t3.json"` for editor autocomplete and validation: + +```json +{ + "$schema": "https://t3.codes/schema/t3.json", + "iconPath": "assets/logo.svg", + "defaultThreadEnvMode": "worktree", + "worktreeSubmodules": "top-level", + "worktreeSparsePatternsPath": ".t3/sparse-checkout", + "ignoreRepositories": ["vendor/big"], + "scripts": [ + { + "name": "Setup", + "command": "pnpm install", + "icon": "configure", + "runOnWorktreeCreate": true, + "async": false + }, + { + "name": "Dev", + "command": "pnpm dev", + "icon": "play", + "previewUrl": "http://localhost:3000", + "autoOpenPreview": true, + "stopOnSettle": true + }, + { + "name": "Clean", + "command": "cargo clean", + "icon": "build", + "runOnSettle": true + } + ] +} +``` + +### Top-level fields + +| Field | Values / Description | +| ---------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `iconPath` | Workspace-relative path to a project icon (checked before auto-detected icons). | +| `defaultThreadEnvMode` | `"local"` or `"worktree"` — default workspace mode for new threads. | +| `worktreeSubmodules` | `"recursive"` (default), `"top-level"`, or `"none"`. | +| `worktreeSparsePatternsPath` | Repo-relative path to a Git sparse-checkout pattern file (non-cone syntax; Git 2.35+). | +| `ignoreRepositories` | Repo-relative paths to exclude in [multi-repo projects](./multi-repo-projects.md). | +| `worktreeLayout` | Custom `{ "create": "...", "remove": "..." }` commands for multi-repo or custom worktrees (requires approval; see [Custom worktree layout](./multi-repo-projects.md#custom-worktree-layout)). | +| `scripts` | Up to 50 project actions (see below). | + +## Project actions (`scripts`) + +Import `t3.json` scripts or define local actions in **Settings → Projects → Actions** (run them from the thread details panel, command palette, or [keybindings](./keybindings.md) via `script..run`). + +| Field | Description | +| --------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- | +| `name` | Display name in the actions menu. | +| `command` | Shell command run in a T3 terminal at the project root. | +| `icon` | `"play"` (default), `"test"`, `"lint"`, `"configure"`, `"build"`, or `"debug"`. | +| `runOnWorktreeCreate` | Runs automatically when a new worktree is created. Skipped for agent-initiated worktrees below **Full access**. | +| `async` | For `runOnWorktreeCreate` only: `true` (default) starts the agent immediately; `false` waits for the script to finish first. | +| `stopOnSettle` | Stops this action's terminal and child processes when its thread settles. | +| `runOnSettle` | Runs in the thread's worktree whenever the thread settles (skipped in main checkouts). Terminal closes on success, stays open on failure. | +| `previewUrl` | Opens this URL in the in-app browser when the script runs (desktop only). | +| `autoOpenPreview` | Automatically opens the browser panel at `previewUrl` on script start. | + +> Note: In multi-repo projects, only the project folder's `t3.json` is read—nested repo `t3.json` files are ignored. diff --git a/docs/user/telemetry.md b/docs/user/telemetry.md index 36692af7256eb..0227860d82937 100644 --- a/docs/user/telemetry.md +++ b/docs/user/telemetry.md @@ -1,136 +1,38 @@ -# Product usage data +# Product usage data and diagnostics -The T3 Code server sends product usage events to T3 Code's own endpoint at `ingest.t3.codes`, -associated with a hashed random identifier for the installation. To count how many installations one person -uses, the server also sends a hashed identifier for your T3 Connect account when you are signed in -to one, and a random identifier for each device that connects. Events include the provider, model, reasoning effort, -permission mode, turn and request results, duration, release channel, and token counts when -available. Child-agent token counts are reported separately from the main agent's. Models from a -provider's catalog are reported by name, even when a custom endpoint serves them. Any other -model, such as a local or fine-tuned one, is reported only as a custom model of that provider. +T3 Code sends lightweight product usage events and relay connection traces to keep the app reliable and fast. Prompts, responses, file contents, and credentials are never included (unless you explicitly approve an [agent feedback](#agent-feedback) card with conversation text attached). -Product events do not include prompts, responses, file contents, authentication tokens, conversation IDs, -raw provider events, child-agent output, or identifiers from your provider accounts. The one exception is [agent feedback](#agent-feedback), -which is off unless you turn it on. +## Product usage events -## Agent feedback - -Agent feedback lets agents tell the T3 team about T3 Code: a T3 tool or `t3` command that did not -do what they expected, a confusing instruction, or a missing capability. Choose a mode in -**Agent feedback** in **Settings > Labs**: - -- **Off**, the default: agents do not see the feedback tools, and `t3 feedback` stops with a - message pointing to Labs. -- **When I ask**: agents send a report only when you ask them to, about anything in T3 Code. -- **Automatic**: agents also report T3 Code problems they hit on their own, such as a T3 tool that - failed and made them find another way. These go out without asking you, so they carry only the - kind of problem and the tool or command it concerns, with no agent-written text, outline, or - conversation. `t3 feedback --kind bug --subject "t3 thread send" --expected "…" --actual "…"` - sends one the same way, so it works only in this mode. - -When you ask your agent for a report, in either mode, T3 Code shows it in the thread as a card -with exactly what would leave your machine, and sends it only if you press **Send**. The agent -carries on without waiting and never learns your answer. The card stays open until you answer it, -even after the turn ends or the server restarts; **Don't send** sends nothing, and the agent is -told not to send it another way. Only someone who can run agents on that machine can answer the -card; people on a guest link cannot. - -Each report has the kind of problem, the T3 tool or command it concerns (or `general`), and, when -you send it from a card, up to 300 characters each of expected behavior, actual behavior, and -workaround, written by the agent, which is told not to quote your messages or code. The agent also says how many recent turns the -problem spans. A report you approved carries an outline of those turns, and of at least the last 5, -from when the agent asked: who spoke, how long each message was, and which tools ran, whether they -worked, and how long they took. The outline has no text. Tools from your other MCP servers appear -only as `mcp`. Turn on **Include the conversation** in the card to attach the text of your -messages and the agent's replies in the turns the problem spans, up to 1,000 characters per -message and 16 KB in all, oldest text dropped first; the card shows that text before you send it. -To change a report, such as the turns it covers, ask the agent in the chat: it shows a new card, -and you can decline the old one. Tool inputs and outputs, files, and attachments are never sent. An agent can -show you at most 3 report cards and send 3 reports on its own per turn, and `t3 feedback` can -send at most 10 an hour. - -Before anything is saved, T3 Code removes file paths (when text mentions one, the rest of that line -goes with it), your user name, machine name, project title, branch, and git remote, and anything -that looks like a key, token, email address, or URL with a password. It cannot recognise your code -or a name written in a sentence, so only include the conversation when it holds nothing you would -not send. Reports from agents also name the provider and the model. No thread IDs or project IDs -are sent, and each report goes out under its own random ID, so reports cannot be tied to your -installation or to each other. - -Reports are saved on your machine first, and a declined one is not saved at all; its card keeps -only what you would have sent without the conversation. When product usage -data is turned off, saved reports stay there and are not sent. `t3 feedback list` shows recent -reports, the thread each came from, and a line for each outline; `t3 feedback list --json` shows -exactly what each one holds. +The server sends usage events to `ingest.t3.codes` under a hashed random install ID (plus a hashed T3 Connect account ID when signed in, and random client device IDs). Events contain provider, catalog model name (non-catalog models report as custom), reasoning effort, permission mode, turn/request outcome, duration, release channel, and token counts. -## Relay connection diagnostics +## Disable telemetry -T3 Code sends relay connection traces to Axiom to diagnose T3 Connect connectivity. These are -separate from product events. Traces carry connection timings, request paths, environment and -thread identifiers, and error types. They omit machine addresses, query strings, log lines, -error messages, and stack frames. +- **Server / CLI**: Set `T3CODE_TELEMETRY_ENABLED=false` or `DO_NOT_TRACK=1` before starting (`DO_NOT_TRACK=1` takes precedence). CI environments (`CI`, `GITHUB_ACTIONS`, `GITLAB_CI`, `JENKINS_URL`) disable telemetry by default unless `T3CODE_TELEMETRY_ENABLED=true`. +- **Desktop app**: Export `T3CODE_TELEMETRY_ENABLED=false` or `DO_NOT_TRACK=1` in your shell profile (macOS/Linux) or user environment variables (Windows) and restart. +- **Managed policy**: Administrators can set `"telemetry": false` in [managed policy](./managed-policy.md#other-capabilities) for servers and desktop apps. +- **Mobile app**: Toggle **Send crash reports** and **Send connection traces** separately in **Settings → About T3 Code → Diagnostics**. -To disable product events and relay tracing from the server, set -`T3CODE_TELEMETRY_ENABLED=false` or `DO_NOT_TRACK=1` in its environment before starting it. -`DO_NOT_TRACK=1` wins over `T3CODE_TELEMETRY_ENABLED=true`. Relay tracing also stops -when `T3CODE_OTEL_SDK_DISABLED` or `OTEL_SDK_DISABLED` turns OpenTelemetry export off. +## Relay connection diagnostics -On a CI runner, the server sends no product events or relay traces by default. It treats a run as -CI when a common CI variable is set, such as `CI`, `GITHUB_ACTIONS`, `GITLAB_CI`, or `JENKINS_URL`. -`CI=false` and `CI=0` do not count. To send them from CI anyway, set -`T3CODE_TELEMETRY_ENABLED=true`. +T3 Connect sends connection timings, request paths, environment/thread IDs, and error types (no addresses, logs, or stack frames) to Axiom. Disabled by the server telemetry opt-outs above or by `T3CODE_OTEL_SDK_DISABLED` / `OTEL_SDK_DISABLED`. -An administrator can turn product events and relay tracing off in the server and desktop app with -a [managed policy](./managed-policy.md#other-capabilities). This does not control traces sent by -the hosted web app or mobile clients. +## Agent feedback -The desktop app reads `T3CODE_TELEMETRY_ENABLED` and `DO_NOT_TRACK` from your shell profile (for example `~/.zshrc`) on macOS and -Linux, so export them there and restart the app. On Windows, set them as user environment variables. +Optional tool for agents to report T3 Code bugs or missing capabilities. Configure in **Settings → Labs → Agent feedback**: -A browser opened from a T3 Code server sends relay traces only while connected and allowed by that -server's policy. The hosted web app sends relay traces when configured and has no tracing toggle. +- **Off** (default): Feedback tools and `t3 feedback` are disabled. +- **When I ask**: Agents submit a report only when you ask, shown as an interactive approval card before anything leaves your machine. +- **Automatic**: Also sends minimal automated reports (problem kind + tool/command name only—no text or conversation) when an agent hits a T3 tool failure; enables `t3 feedback` CLI reporting (up to 10/hour). -## Mobile app diagnostics +Approval cards show exact payloads (expected/actual/workaround, turn outline with no text, and optional **Include the conversation** up to 16 KB). File paths, usernames, hostnames, git remotes, and secret-like strings are scrubbed before saving, and reports use one-off random IDs. Inspect local reports with `t3 feedback list [--json]`. -When the iOS or Android app crashes or hits an error, it sends a report to T3 Code: the error -message, the stack trace, the app version, and the device model and OS version. Each launch also -sends startup timings, and every report carries a random ID for the install. Reports go through -the T3 Connect relay to Axiom. They do not include your threads, prompts, or connection details, -but an error message can quote a value the app was handling. +## Agent activity for mobile notifications -To stop sending them, turn off **Send crash reports** in **Settings > About T3 Code > Diagnostics**. +**Settings → Sharing & access → Publish agent activity** sends project/thread titles, model names, and turn status to the T3 Connect relay for [mobile notifications and live activities](./mobile-notifications.md). This is independent of telemetry—turn it off directly on the host if you don't want it. -The mobile app also sends relay connection traces when its build has tracing configured. These -carry an identifier for the current app session. To stop them, turn off **Send connection traces** -in **Settings > About T3 Code > Diagnostics**, or on the T3 Connect setup sheet shown after you -sign in. This is separate from crash reports. Server environment variables and managed policy do -not disable mobile tracing. +## Export diagnostics to your own OpenTelemetry receiver -## Agent activity for mobile notifications +Open **Settings → Maintenance → Diagnostics** (per environment) and enter OTLP HTTP endpoints (e.g. `http://localhost:4318/v1/traces`), save, and restart the server. Use **Test** to verify connectivity. -When **Publish agent activity** is enabled on a host, it sends project and thread titles, model -names, activity status, and environment and thread identifiers to the T3 Connect relay for -[mobile notifications and live activities](./mobile-notifications.md). This is separate from -product events and relay diagnostics. The telemetry opt-out does not disable it. - -To stop publishing, turn off **Publish agent activity** under **Settings > Sharing & access** on -the host. Turning off notifications on a phone controls that phone's alerts, not the host's -publishing setting. - -## Export diagnostics to your own receiver - -To send traces, metrics, or logs to an OpenTelemetry receiver, open -**Settings > Maintenance > Diagnostics**, select an environment, and enter each signal's OTLP HTTP -endpoint under **OpenTelemetry export** (for example `http://localhost:4318/v1/traces`). Save, then -restart that environment's server. The receiver must be reachable from the server's machine. -**Test** sends an empty export from the server to check an endpoint before or after you save it; -saved endpoints are checked when the section opens. Checks send authentication headers only to -the signal's currently running endpoint and do not follow redirects. To check a new endpoint -that requires authentication, save it and restart the server first. - -`T3CODE_OTLP_*_URL` and standard `OTEL_EXPORTER_OTLP_*` environment variables override the saved -settings. An overridden signal shows **Set by environment** and names the variable that set it, and its -**Test** checks the running endpoint instead of the field. For endpoints saved here or set with `T3CODE_OTLP_*_URL`, set `T3CODE_OTLP_HEADERS` for -receivers that need authentication and `T3CODE_OTLP_PROTOCOL=http/protobuf` for receivers that do -not accept JSON. An endpoint set with `OTEL_EXPORTER_OTLP_*` takes its headers and protocol from -`OTEL_EXPORTER_OTLP_HEADERS` and `OTEL_EXPORTER_OTLP_PROTOCOL` instead. +`T3CODE_OTLP_*_URL` and standard `OTEL_EXPORTER_OTLP_*` env vars override saved settings (use `T3CODE_OTLP_HEADERS` / `T3CODE_OTLP_PROTOCOL=http/protobuf` or the standard `OTEL_EXPORTER_OTLP_*` equivalents for auth and protobuf). diff --git a/docs/user/terminal.md b/docs/user/terminal.md index 0ef9420be322e..bd2320e03d82b 100644 --- a/docs/user/terminal.md +++ b/docs/user/terminal.md @@ -1,67 +1,32 @@ # Terminal +T3 Code includes integrated terminals running on the environment's host machine, with persistent scrollback across reconnects. + ## Choose a shell -Set `T3CODE_TERMINAL_SHELL` in the environment that launches the T3 Code server -to choose the executable used for new terminals. Use an executable name or its -full path, without surrounding quotes or command-line arguments. An unset or -blank value keeps the platform default. If the executable cannot be started, -T3 Code tries its usual fallback shells. +Set `T3CODE_TERMINAL_SHELL` in the T3 server's environment to an executable name or full path (no quotes or arguments) to override the platform default shell for new terminals. This does not affect agent commands or project setup/settle scripts. -On Windows, to use Git Bash from a standard Git for Windows installation, run -this in PowerShell: +Example for Git Bash on Windows (PowerShell, then fully quit and reopen T3 Code): ```powershell [Environment]::SetEnvironmentVariable('T3CODE_TERMINAL_SHELL', 'C:\Program Files\Git\bin\bash.exe', 'User') ``` -Fully quit T3 Code, then reopen it from the Start menu and create a new terminal. -If the app still inherits the old environment, sign out of Windows and sign in -again. Git Bash starts as an interactive login shell. Use `bin\bash.exe`, not -`git-bash.exe`, which launches a separate terminal window. - -To restore the default, remove the variable with the same command using `$null` -as its second argument, then restart T3 Code. - -This setting belongs to the machine hosting the server, including when you -connect from another device. It does not change provider-run commands or the -shell used by automatic project setup and settle scripts. - -## Terminal history - -Each terminal keeps up to 5,000 lines and 8 MiB of scrollback on its environment -server. T3 Code removes the oldest output when either limit is reached. A long -line can be shortened at the start. New terminal output is not truncated. - -These limits apply when you reconnect and when T3 Code restores saved terminal -history. A client can show less scrollback than the server keeps. - -On web and desktop, use Shift+PageUp and Shift+PageDown to read scrollback -without leaving terminal input. Ctrl+Shift+Home and Ctrl+Shift+End jump to the -start and latest output; use Cmd instead of Ctrl on macOS. Full-screen terminal -programs keep these navigation keys. +> Note: Use `bin\bash.exe`, not `git-bash.exe`. Remove with `$null` to restore the default. -To copy all retained output, choose Select all in the terminal's context menu, -then copy. Cmd+A on macOS and Ctrl+Shift+A elsewhere select the same output. -Ctrl+A still moves to the beginning of shell input on Windows and Linux. -Jump to latest in the context menu returns to the current output. +## Scrollback and navigation -While a terminal is focused, use `Cmd+Shift+]` for the next terminal and `Cmd+Shift+[` for -the previous one on macOS. On Windows and Linux, use `Ctrl+Alt+]` and `Ctrl+Alt+[`. Cycling -wraps through tabs and split panes in the focused drawer or right panel. Rebind these -shortcuts in Settings > Keybindings. +Each terminal retains up to **5,000 lines** and **8 MiB** of scrollback on the server. -On iPhone and iPad, long-press the terminal to paste or to choose Select Text. -Select Text shows the visible output, where you can copy text or tap a link. +| Action | macOS | Windows / Linux | +| -------------------------- | ---------------------------------- | ------------------------------------------ | +| Scroll page up/down | `Shift+PageUp` / `Shift+PageDown` | `Shift+PageUp` / `Shift+PageDown` | +| Jump to start / latest | `Cmd+Shift+Home` / `Cmd+Shift+End` | `Ctrl+Shift+Home` / `Ctrl+Shift+End` | +| Select all retained output | `Cmd+A` | `Ctrl+Shift+A` (`Ctrl+A` stays shell home) | +| Next / previous terminal | `Cmd+Shift+]` / `Cmd+Shift+[` | `Ctrl+Alt+]` / `Ctrl+Alt+[` | -## fish +On iOS/iPadOS, long-press the terminal to paste or choose **Select Text**. -T3 Code starts fish with `no-query-term`, avoiding startup waits for terminal -replies. This disables optional fish features that depend on those replies. -T3 Code's exported `fish_features` also hides any universal flags you set with -`set -U fish_features`. +## fish shell -To preserve those flags or enable queries with `query-term`, include them in -`fish_features` in the environment that launches T3 Code. A shell export applies -when you launch T3 Code from that shell; it does not configure a desktop app -launched from the Dock or Finder. Enabling queries can restore the startup wait. +T3 Code launches `fish` with `no-query-term` to avoid startup delays, which overrides universal `fish_features`. To keep custom flags or re-enable `query-term`, export `fish_features` in the environment that launches T3 Code. diff --git a/docs/user/text-generation.md b/docs/user/text-generation.md index 25d29e211b0d5..f0f9dec6b2d2f 100644 --- a/docs/user/text-generation.md +++ b/docs/user/text-generation.md @@ -1,42 +1,20 @@ # Text generation models -T3 Code writes some text for you: thread titles, commit messages, pull request titles and -descriptions, branch names, and voice transcript cleanup. Pick the model for this in -**Settings → Threads → Text generation model**. **Settings → Source control & issues** and -**Settings → Voice** can each pick a different one. +T3 Code uses an LLM for lightweight background text tasks: thread titles, branch names, commit messages, PR titles/descriptions, and voice transcript cleanup. Configure the default in **Settings → Threads → Text generation model** (overridable separately in **Settings → Source control & issues** and **Settings → Voice**). -By default, a coding agent such as Codex or Claude writes this text, starting a session for each -request. A **text generator** — a model API that only writes text — is usually faster and cheaper. +By default, a coding agent handles these tasks by starting a session per request. Adding a dedicated **text generator** API is usually much faster and cheaper. ## Add a text generator -Go to **Settings → Providers → Text generators** and choose **Add generator**: +Open **Settings → Providers → Text generators → Add generator** (stored per environment; API keys support [Secrets](./secrets.md)): -- **OpenAI** or **Anthropic** — enter an API key. -- **OpenRouter** — enter an OpenRouter key to use any model it serves. -- **Custom (OpenAI-compatible)** — enter the base URL of any other endpoint, such as Ollama at - `http://localhost:11434/v1` or LM Studio. Local endpoints usually need no key. The environment's - server makes the requests, so on a remote environment `localhost` means that machine, not yours. +- **OpenAI** or **Anthropic**: Enter an API key. +- **OpenRouter**: Enter an OpenRouter API key to use any model it serves. +- **Custom (OpenAI-compatible)**: Enter a base URL (e.g. Ollama at `http://localhost:11434/v1` or LM Studio—`localhost` resolves on the environment's server). -Give it a name if you add more than one from the same service. Your key is stored on the -environment, like other [secrets](./secrets.md), and can come from a secret provider instead of -being typed in. +Click **Test** beside a model picker to verify the key works, or **Show models** to refresh the catalog. Disabling or removing a generator falls back to the environment's default text generation model. -T3 Code lists the service's models to check the connection, then shows the model picker for each -text task so you can switch any of them to the new generator, or keep what they use. **Test** next -to a picker has the chosen model answer a tiny prompt, which proves the key works; some services -list their models without checking it. **Show models** in the generator's menu lists its models -and refreshes the list after the service adds some. +## Limitations -Each request sends the API what the task needs, such as the staged diff for a commit message. - -Turning a generator off or removing it sends its work back to the environment's text generation -model. - -## What text generators can't do - -Review guides read the checkout over many steps, so they always use a coding agent. If your source -control writer model is a text generator, review guides use Codex or Claude instead, and fail if -neither is set up. To choose which, pick one in **Settings → Source control & issues → Review guide model**. - -A [managed policy](./managed-policy.md) that limits providers also turns off text generators. +- **Review guides** always require a coding agent (Codex or Claude), not a text generator—choose one under **Settings → Source control & issues → Review guide model**. +- A [managed policy](./managed-policy.md) that restricts providers also disables text generators. diff --git a/docs/user/thread-migration.md b/docs/user/thread-migration.md index b9da85f03bd57..d09d6e07419a3 100644 --- a/docs/user/thread-migration.md +++ b/docs/user/thread-migration.md @@ -1,74 +1,38 @@ # Threads from older T3 Code versions -On your first V2 launch, T3 Code copies the V1 database, `state.sqlite`, into `statev2.sqlite` -in the same data directory and migrates the copy. Your threads appear automatically, with full -transcripts imported as needed. You do not need to run an import command. +On your first V2 launch, T3 Code automatically copies your V1 database (`state.sqlite`) to `statev2.sqlite` in the same data directory and migrates it. V1 and V2 stay independent afterward (changes in one do not sync to the other), while settings, attachments, and workspace files remain shared. -V1 continues using its original database while V2 uses the copy. The database import can run while -V1 is open. Opening V2 again resumes your V2 history. The copy happens only once: later conversations -and changes in either version do not sync to the other. Settings, attachments, and workspace files -remain shared. +## What migrates -The V2 desktop app uses a separate browser profile, so browser cookies and caches do not carry -over from V1. You may need to sign in again to websites opened inside the app. On its first launch, -the V2 desktop app copies stashed prompts, unsent drafts, layout, and theme from V1. Anything you -change in V2 afterwards stays in V2. - -The migrated thread keeps its title, project, provider and model selection, permission and -interaction modes, branch or worktree, archive state, settlement state, snooze and pin state, and -linked pull request. T3 Code also brings over user and assistant messages, their timestamps, and -supported attachments. Large histories may appear in stages while the server imports transcripts. - -The migration does not recreate the old provider's live session. It also does not convert old run -records, checkpoints and diffs, tool activity, approval history, or proposed plan history into the -new format. These items may be absent from a migrated timeline even though the conversation text is -present. +- **Included**: Thread metadata (title, project, provider/model, modes, branch/worktree, archive/settle/snooze/pin state, linked PR), user/assistant messages, timestamps, and supported attachments. On desktop, first launch also copies V1 stashed prompts, drafts, layout, and theme (browser cookies/caches do not carry over). +- **Not included**: Live provider sessions, old run records, checkpoints/diffs, tool activity, approvals, and proposed plan history. ## Continuing a migrated thread -The first new message starts a fresh provider session. T3 Code selects intact user and assistant -messages using the same [handoff budget](./portable-handoffs.md) as a provider switch. Omitted text -remains in the thread and can be retrieved by the agent. The migration retains its separate -32,000-character recovery excerpt; neither that excerpt nor the handoff replaces the full imported -transcript. - -Before continuing a long or important thread, read the recent transcript and include any older -requirements the agent still needs in your next message. Starting a new thread and pasting a short -handoff is also a good choice when the old conversation contains conflicting instructions. +Sending your first message starts a fresh provider session using the [portable handoff budget](./portable-handoffs.md). Omitted text remains saved in the thread and readable by the agent, though for long or critical threads it's worth restating key constraints—or starting a fresh thread with a short summary. ## Keeping a recovery copy -T3 Code does not currently have a whole-thread export command. Before a major server update, stop -the server and copy its `userdata` directory to a safe location. The default is -`~/.t3/userdata`; a server started with `--base-dir ` uses `/userdata`. +T3 Code does not have a whole-thread export command. Before a major server update, stop the server and back up your `userdata` directory (`~/.t3/userdata` by default, or `/userdata`). -If a migrated transcript is missing from the app, keep that copy unchanged. You can inspect the -old transcript without starting a server against it: +If a migrated transcript is missing, inspect your backup read-only without pointing a server at it: ```sh sqlite3 -readonly /path/to/recovery-copy/state.sqlite ``` -At the SQLite prompt, list recent legacy threads: - ```sql +-- List legacy threads .headers on .mode tabs SELECT thread_id, title, updated_at FROM projection_threads ORDER BY updated_at DESC; -``` - -Then print one transcript, replacing `` with the value from the first query: -```sql +-- Print one transcript SELECT role, text, created_at FROM projection_thread_messages WHERE thread_id = '' AND role IN ('user', 'assistant') ORDER BY created_at, message_id; ``` - -Open only the copied database. Do not edit it or point a newer or older server at your recovery -copy. If the affected environment is remote, make and inspect the copy on the machine that runs -that environment. diff --git a/docs/user/thread-sidebar.md b/docs/user/thread-sidebar.md index 00ee74cd704f9..b739242ea5c42 100644 --- a/docs/user/thread-sidebar.md +++ b/docs/user/thread-sidebar.md @@ -1,410 +1,96 @@ # Working with threads -Use a new thread for a separate task. Choose **New worktree** when its code changes -need a separate branch and working directory. Threads in the same checkout share its -branch, so T3 Code refuses a branch switch there while one of them is working. +Use a separate thread for each task. Choose **New worktree** when a task needs its own Git branch and working directory; threads sharing a checkout share its branch, so T3 Code blocks branch switches while one is running. -## Resize or hide the sidebar +## Start a thread -On web and desktop, drag the sidebar's right edge to resize it. Continue left past its minimum -width to preview hiding it, then release to keep it hidden. Dragging back right before releasing -shows it again and continues resizing. +- **Web and desktop**: **New thread** opens the project picker when you have multiple open projects (unless the sidebar is filtered to one project). `Shift`-click to start in the current project. To reuse an existing worktree, choose **New thread in this worktree** from the branch toolbar. +- **Mobile**: **New thread** uses the current, filtered, or last-opened project. Disable **Settings → General → Use last project** to pick every time. +- **Defaults**: New threads inherit your last model and mode unless the project sets its own model default. -Move the mouse to the middle of the left window edge to find a handle. Drag it right or click -it to show the sidebar again. Dragging back to the edge before releasing hides the preview -and leaves it hidden. The sidebar toggle and shortcut still keep it open. +### Start without a project -## Start a thread +Threads don't require a project. Pick **No project** (or press `mod+alt+n` on web/desktop) to start a scratch thread in `~/.t3/scratch/--`. -On web and desktop, **New thread** opens the project picker when you have more than one -open project in the default or project-grouped sidebar. Archived projects don't count. **Shift-click** to start in -the current project, or use a project's own new-thread action. A new thread carries -your model and mode selections, unless the destination project has its own model default. -Its branch and workspace mode come from your configured defaults. To continue in -an existing worktree, use **New thread in this worktree** from the branch toolbar. -While the sidebar is filtered to one project, the sidebar's **New thread** button -starts the thread in that project instead of asking which project to use. - -On mobile, **New thread** starts in the current thread's project, or else in the -project the thread list is filtered to, or else in the last project you opened -or chose on that device. If none is available, the project picker opens. Turn -off **Settings → General → Use last project** to choose a project every time. -When you pick a project that is on more than one machine, the thread starts on -a connected one if any is connected. - -When you change a new thread's project, T3 Code stays in the current environment -if that project exists there. Otherwise it selects an environment that has it. +- Deleting a scratch thread leaves its folder on disk. +- Git branch, worktree, and diff controls are hidden (and scratch threads are unavailable if your T3 data directory itself is inside a Git repo). +- Choose **Turn into project** from the thread menu to promote the folder into a real project in place, then **Initialize Git** if needed. -### Start without a project +### Start in the background and multi-model runs + +- **Background start** (web/desktop): Press `Cmd+Enter` (macOS) or `Ctrl+Enter` (Windows/Linux) in a new thread to submit it and immediately open another draft with the same workspace mode and base branch. +- **Same prompt, multiple models** (web/desktop, Git projects): `Shift`-click models in a new thread's model picker to select several. Sending starts a separate thread and worktree for each model. + +## Sidebar layout and organization -A thread does not need a project. To start one without a project, click **or -start without a project** under a new thread's heading, pick **No project** from -the project menu in that heading or from **New thread in...** in the command -palette, or press `mod+alt+n`. On mobile, pick **No project** from the project -list. It starts on your current machine; before sending, pick another machine -from the machine menu to move it there. To move a draft into a project, pick the -project in the heading. - -Each thread without a project works in its own folder under `~/.t3/scratch` (the -`scratch` folder of your T3 data directory), named after its date, the first words -of its first message, and a short id, like -`2026-09-25-convert-these-pngs-to-webp-a1b2c3d4`. Deleting a thread keeps its -folder, so the files the agent wrote stay until you delete them. Branch, worktree, and diff controls stay hidden because -these folders are not Git repositories. This is unavailable when the data -directory itself sits inside a Git checkout. - -When the work grows into something real, pick **Turn into project** from the -thread's menu. The thread's folder becomes a project where it is, so nothing -moves and the agent keeps working in the same place. Other threads in that folder -move with it. Rename the project in its settings, and use **Initialize Git** to -get branch and diff controls. - -### Start in the background - -In a desktop browser or the desktop app, press `Cmd+Enter` on macOS or `Ctrl+Enter` -on Windows and Linux to start a new thread and immediately open another draft. The -next draft keeps the workspace mode and base branch you selected. With **New -worktree**, each background submission creates its own worktree. - -To send the same prompt to several models on web or desktop, **Shift-click** models -in a new thread's model picker to add or remove them. A regular click returns to a -single model. Choose a base branch and send. Each selection starts a separate thread -and worktree while you stay in the new thread composer. This requires a Git project. - -## Pin and reorder threads - -Pin a thread from its menu to keep it above your active work. - -On web and desktop, unpinning, settling, snoozing, and archiving a thread each show -a notification with **Undo** for five seconds. Undo restores the thread's previous -state, including its pinned position, and reopens an archived thread you were -viewing. Discarding an unsent draft from the sidebar works the same way: Undo brings -back its text and attachments. `mod+z` triggers the most recent Undo, even from the composer; see -[Keybindings](./keybindings.md#commands-with-special-behavior). - -On web and desktop, you can also drag files from your computer onto any thread row: -the thread opens and the files are attached in its composer, ready for -your next message. The same per-message file limits apply as when attaching -files directly; see [Attach files](./composer.md#attach-files). - -On web and desktop, pinning or unpinning a thread keeps the sidebar at your current -scroll position instead of following the thread to its new place in the list. - -Pinning does not prevent automatic settlement. Settling a thread removes its pin. - -On web and desktop, drag a thread between sections to change its state. Drag a thread up into -the pinned section to pin it at the spot you drop it; drag a pinned thread down into the active -list to unpin it. Dragging a thread onto the **Settled** header settles it, and dragging a settled -thread into the active list un-settles it. A snoozed thread can be dragged out of the snoozed -shelf, which wakes it, but threads cannot be dragged into the shelf because snoozing needs a wake -time. Dragging a pinned thread out of the pinned section does not ask for unpin confirmation. -Pinned and active boundary labels appear only while dragging, without moving the rows. The -other rows slide aside to show where the thread will land. When you cross into another section, -the dragged thread shows the action the drop performs, with its icon: **Pin**, **Unpin**, -**Settle**, **Un-settle**, or **Wake**. Its status and hover actions hide during the drag. A pinned -thread keeps its pin only while it stays in the pinned section; once it leaves, the badge takes -over. Reordering within the same section shows no badge. When there are no pins, drag to the top -edge to pin a thread. Section labels stay readable for the whole drag, and the section the -thread is over takes the accent color. Section labels also -identify empty sections and a collapsed settled shelf. - -Drag within the pinned or active section to change its order. Other rows slide aside to show the -spot where the thread will land. Drops into either section keep the position you choose. On -mobile, open a thread's menu and choose **Arrange threads**. Drag a handle within or between -**Pinned** and **Active** to reorder, pin, or unpin. Drop onto the **Settled** divider to -settle a thread. The dragged card shows the action before you release it. Expand **Snoozed** -or **Settled** to drag a parked thread back into either live section. Each drop saves; close the sheet to return to the thread list. -**Move up** and **Move down** are also available in the thread menu. The server -saves the order, so it survives a refresh and appears on your other connected devices. - -On web and desktop, the list also animates section changes made with thread actions such as -**Pin**, **Settle**, and **Snooze**. These transitions respect your system's reduced-motion -preference. While dragging, rows follow the insertion gap without replaying a second transition -after the drop. - -New threads appear above the active threads you have arranged. Settling clears a thread's active -position, so using **Un-settle** returns it to the top. Pinning and snoozing preserve its active -position until you move it again. Thread activity does not change the order. The settled shelf -continues to use settlement time. - -If dragging is unavailable for one environment, update the T3 Code server running in that -environment. Pinned and active reordering require server support. Threads from older servers keep -their default order until the server is updated. - -To generate a fresh title from the conversation, open a thread's menu and choose -**Regenerate title**. The action is unavailable while title generation is in progress -or when the connected environment needs a server update. - -To change how titles are written, add **Thread title instructions** in **Settings → Threads → -Text generation**, under Advanced, such as a length limit or an identifier to put first. They apply to new and -regenerated titles. Select a project to give it its own instructions. - -Agents connected through T3 Code can use the same server-owned metadata workflow to -rename a thread, regenerate its title, or link and unlink a pull request. These changes -appear on web, desktop, and mobile without requiring the originating browser to remain -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. -That includes subagents, watched pull requests with checks still running, Claude monitors and -`sleep` timers, 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 -answer. The Working section lists the thread you last sent work to first. Pinned threads stay in -the pinned section. - -This is on by default. Turn it off with **Settings → General → Working section** on web and desktop, -or **Settings → General → Working section** on iOS and Android. Each device keeps its own -choice. - -While this is on, the active list is ordered by when each thread last came back to you, so you -cannot drag or move threads within it. Your saved order returns when you turn it off. +- **Resize or hide** (web/desktop): Drag the sidebar's right edge past its minimum width to hide it; hover the left window edge and click or drag the handle to bring it back. +- **Drop files onto a thread** (web/desktop): Drag files from your computer onto any thread row to open it and attach them to its composer. +- **Pin and reorder**: Pin a thread from its menu or drag threads between **Pinned**, **Active**, and **Settled** (or drag out of **Snoozed** to wake). On mobile, use **Arrange threads** or **Move up / Move down** in the thread menu. Custom order syncs across devices (requires an up-to-date server). +- **Undo** (web/desktop): Unpinning, settling, snoozing, archiving, or discarding a draft shows a 5-second **Undo** toast (`mod+z`). +- **Titles**: Choose **Regenerate title** from a thread's menu, or customize title style in **Settings → Threads → Text generation → Thread title instructions** (global or per-project). + +### Working section (beta) + +Enabled by default (**Settings → General → Working section**, per device). Unpinned threads that are actively running—or waiting on subagents, watched PRs, or monitors—collapse into a **Working** section below Active, and return to the top of Active when they finish, fail, or need input. + +While enabled, Active is sorted by most recent return (manual reordering is paused until you turn it off). ### Group threads by project (beta) -Turn on **Settings → Labs → Boring sidebar (group by project)** on web and desktop to put active -threads in a folder for each project. Pinned projects come first. A project with no active -threads has no folder unless it is pinned or you pick it in the project filter. An archived -project's folder comes last and shows only while it has active threads. Click a folder to open or -close it. A closed folder shows how many threads it holds, and a dot when one of them -needs you. Use the pen button on a folder, or right-click it, to start a thread in that project. -Pinned threads stay above the folders, and Snoozed and Settled stay below them. In this mode you -can drag a thread onto the composer to mention it, but not within the sidebar, and the Working -section is off. Each device keeps its own choice. - -## Settle finished work - -Choose **Settle thread** from its menu to move finished work out of the active list -without deleting the conversation. **Un-settle thread** restores it to active work -and prevents automatic settlement until new activity resumes the usual rules. -Manually settling an idle thread dismisses unanswered async questions without -sending an answer or restarting the agent. Settling also closes the thread's -terminals that wait at an idle prompt, and keeps their output. A terminal that -runs a command, such as a dev server, stays open unless its action has **Stop this action -when the thread settles** enabled in Settings > Projects > Actions. You can also set -`"stopOnSettle": true` on a `t3.json` action and import it there. Start the command through -that action so T3 can stop its terminal and child processes. Commands started through an -agent's own shell tools are managed by the provider. - -You can settle or snooze a thread while its environment is offline. The thread shows -**Pending** (**Waiting to sync** on mobile), and the change is sent when the environment -reconnects. Undo, Un-settle, or Wake before then cancels it. If the thread changed there in -the meantime, the environment's state wins and your change is dropped. A thread with a -pending settle cannot be snoozed until it syncs. - -To reclaim disk space from settled work, turn on **Run in the thread's worktree when the -thread settles** for one of the project's actions, or set `"runOnSettle": true` on a -`t3.json` script, for example `cargo clean`. It runs each time a thread in its own -worktree settles, manually or automatically, even if a terminal there still runs a -command such as a dev server. Threads in the project's main checkout skip it. Its terminal -closes when the command succeeds and stays open when it fails. - -On web and desktop, press a thread's **Settle** button and drag up or down to -settle every thread in that section between it and the one you release on. -The **Un-settle** and **Wake** buttons work the same way in their sections. -Press `Escape` while dragging to cancel. - -By default, environments settle inactive threads after seven days and settle -threads whose pull request merged. A closed pull request can also settle an idle -thread. An empty thread's inactivity counts from when it was created. -Work in progress, pending questions or approvals, and background work the agent -is waiting on prevent automatic settlement. An open pull request does not prevent inactivity -settlement unless you turn on **Keep threads with a PR** in **Settings → Threads**, -but an old closed or merged pull request does not settle work you -resumed after it closed. Your own messages count as resuming, and so does a -message an agent sends with `t3_thread_send` or `t3 thread send`. A turn that finished -background work or a pull request watch starts on its own does not. - -To keep one thread out of the settled shelf no matter how long it sits idle, open its menu, -choose **Auto-settle behavior**, and pick **Never**. The current option is checked. Pick -**Follow settings** to return to the rules in **Settings → Threads**. While those rules are off, -a thread on **Follow settings** does not settle automatically either. Manual settle, snooze, and -archive still work while it is set to **Never**. - -Change these rules in **Settings → Threads**. -They continue to run when your apps are closed. On web and desktop, choose an environment at the -top to change only its rules, or **All environments** to update connected environments together. -Mixed values show where the selected environments disagree. Mobile applies these -rules to connected environments that support shared settings. Offline environments -and older servers keep their previous values. Changing a rule does not reopen -already settled threads. - -### Settle or archive - -Settle is for work that is done for now. A settled thread stays in the sidebar's Settled -section and in search, and a message to it, from you, an agent, or a scheduled task, makes it -active again. Archive is for work you want out of the way. An archived thread leaves the -sidebar and search and shows only in **Settings → Archive**, where you can unarchive or -delete it. It refuses new messages, including ones from agents and scheduled tasks, until you -unarchive it. Removing a project deletes its threads either way. - -A scheduled task that posts into one thread keeps running after you archive that thread, and -each run fails. Settle the thread instead, or move or pause the task in **Settings → Scheduled -tasks**. +Enable **Settings → Labs → Boring sidebar (group by project)** on web/desktop (per device) to group active threads into collapsible project folders. Pinned threads stay above; Snoozed and Settled stay below. In this mode, the Working section and sidebar drag-reordering are disabled (dragging a thread onto the composer still works). -## Link a pull request +## Settle, snooze, and archive -The server finds the PR for each unsettled thread's saved branch, even when your -apps are closed. Settled threads keep their saved links. Update the server if -automatic branch links do not appear. +| Action | When to use | Effect | +| ----------- | -------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | +| **Settle** | Task is done for now | Moves to **Settled**; stays searchable; any new message reactivates it. Closes idle terminals (and stops actions with `stopOnSettle: true`). | +| **Snooze** | Defer until later | Hides until wake time (thread keeps working in the background). Wakes early on approvals, questions, errors, or new messages. | +| **Archive** | Out of the way | Leaves sidebar and search; lives in **Settings → Archive**. Refuses new messages (including from agents and scheduled tasks) until unarchived. | -On web and desktop, right-click a pull request link in a thread and choose -**Link to thread** to select a different PR. Use **Unlink from thread** on the -same link to return to the branch PR, if one exists. -The linked pull request participates in automatic settlement. +> Tip: If a scheduled task targets a thread, settle it instead of archiving—archiving causes scheduled runs to fail. -## Find and reference work +### Settlement rules and hooks -On web and desktop, open the command palette with `Cmd/Ctrl+K` to search threads -across connected environments by title, branch, pull request, or project. -Threads you open often or recently rank higher, and for three weeks the thread -you last picked for a query ranks higher when you type that query again. -Threads whose messages contain all your words appear below, under **In -messages**, and open at the matching message. Message search needs at least -one word of three or more letters, or two for Chinese, Japanese, and Korean. -Put a search in double quotes, such as `"missing position files"`, to find only -titles and messages that hold those words together, exactly as typed. -On mobile, the thread list search also lists message matches and opens them at -the matching message; on an iPad with a keyboard, `Cmd+K` opens the same -palette. - -Use **Settings → Keybindings** to find or customize shortcuts for searching files -and copying a thread reference. A copied reference uses the thread's pull request -link when available, otherwise a link to the thread, which opens it from anywhere -you paste it and pastes into a composer as a thread chip (see -[sharing a thread](./prompt-links.md#share-a-thread)). To copy the thread even -when it has a PR, choose **Copy → Thread** from its context menu, or **Copy -thread** from its long-press menu on mobile. -**Thread ID** copies the bare ID for scripts and the `t3` CLI. See -[keybindings](./keybindings.md) for custom configuration. - -## Inspect agent work - -**Limited** means the provider stopped on a usage or rate limit. The conversation -keeps the provider's explanation. Retry after the limit resets, or switch to -another provider instance. -Press **Resume** in an empty composer to continue a limited or interrupted turn -manually when the provider supports native continuation, or send a message to continue. -Do this when the provider reports no reset time, because nothing continues the turn on its own. -Queued messages stay saved while the limit blocks the thread. They run after -the continuation finishes. If the queue was held by a restart, resume it then. - -When the provider reports a reset time, choose **Resume at reset** to schedule a -continuation. You can cancel it from the thread. Enable **Resume after -usage limits** in **Settings → Threads** to schedule limit stops by default. -The environment must be running when the reset arrives; it resumes overdue -continuations after a restart. Stopping the thread, sending a new message, -archiving, or settling it prevents a pending continuation from starting. - -Choose **Snooze until reset** to hide the thread until its allowance returns. -Snooze and auto-resume are independent: snooze alone wakes the thread without -sending a message; enabling both wakes and continues it. **Wake now** cancels -the snooze. Enable **Snooze until limits reset** in thread behavior settings to -snooze limit stops by default. Providers without a reset time offer manual -retry and the normal snooze choices. - -On web and desktop, use **Agents** to follow work delegated to subagents. Click -a subagent there or on its conversation card to open it in the right panel, -beside the thread you are in. See -[Open a thread beside the one you are in](#open-a-thread-beside-the-one-you-are-in). -On mobile, open a subagent from its conversation card or **Agents**. On iOS -layouts with an inspector, its thread opens beside the parent. Maximize it to -fill the screen; close the full-screen view to return to the parent and inspector. -Stop on a thread also stops the subagents it delegated to. -Before archiving the parent, wait for its delegated tasks to finish or cancel them. - -Subagent threads started by the agent can't take messages; message the parent -thread instead. When such a subagent needs an approval or an answer, the parent -thread asks for it. - -Expand a tool call in the conversation to see its full command and output. -Summaries shorten shell wrappers and can still describe the latest call after it -finishes; the call's own result shows its status. - -On web and desktop, the thread details card lists the local servers that the -thread's terminals or its Claude agent started, with their ports. Not every one -serves a web page. A server the agent started stays listed after the agent's -turn ends. -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. - -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 -back the standard rows. +- **Automatic settlement**: By default, environments settle threads after 7 days of inactivity or when their linked PR merges/closes (even while your apps are closed). Active work, pending questions/approvals, and waited-on background work block auto-settlement. Configure rules in **Settings → Threads** (per environment or **All environments**), including **Keep threads with a PR**. +- **Per-thread override**: Open a thread's menu → **Auto-settle behavior → Never** to exempt a single thread. +- **Drag-to-settle** (web/desktop): Press and drag down/up from a thread's **Settle**, **Un-settle**, or **Wake** button to act on a contiguous range (`Esc` cancels). +- **Offline settle/snooze**: Queues locally (**Pending** / **Waiting to sync**) and syncs on reconnect; remote changes take precedence if the thread changed in the meantime. +- **Worktree cleanup on settle**: Enable **Run in the thread's worktree when the thread settles** on a project action (or `"runOnSettle": true` in `t3.json`), e.g. `cargo clean`, to reclaim disk space automatically in worktree threads. -## Open a thread beside the one you are in +### Snooze options + +Customize presets in **Settings → Threads → Snooze options** (durations like `3 hours` or times like `9:00 PM tomorrow`), or pick **Snooze → Custom…** for an exact date/time or duration. Choose **Wake thread** to bring a thread back early. + +## Link a pull request + +The server automatically links open PRs matching an unsettled thread's branch. On web/desktop, right-click any PR link in a thread and choose **Link to thread** or **Unlink from thread** to override it. Linked PRs participate in auto-settlement. -On web and desktop, a subagent, a side chat, and a -[thread on a linked machine](remote-access.md#read-a-linked-machines-threads) -all open the same way. Click one to open it as a tab in the right panel, so the -thread you are in stays in view. Hold ⌘ (Ctrl on Windows and Linux) while you -click, or middle-click, to open it in the main view instead. With the keyboard, -Enter and ⌘/Ctrl + Enter do the same. Right-click for **Open in side panel** and -**Open in main view**. +## Find and reference work + +- **Command palette** (`Cmd/Ctrl+K`): Searches threads across connected environments by title, branch, PR, project, and message contents (use `"exact phrase"` for exact matches). On mobile, use the thread list search (or `Cmd+K` on iPad with a keyboard). +- **Copy reference**: Copies the linked PR URL if one exists, otherwise a thread link that pastes into any composer as a thread chip. Use **Copy → Thread** (or **Copy thread** on mobile) to force a thread link, or **Thread ID** for scripts and the `t3` CLI. -To make the main view the place a plain click opens them, set **Settings → Chat → -Open subagents and side chats in** to **Main view**. The modifier then opens -the side panel. +## Usage limits, subagents, and thread details -From a tab, **Open in main view** at the top of the tab, or in the tab's -right-click menu, moves it to the main view. The bottom of the view depends on -the thread: a side chat or a subagent you delegated has a composer, a subagent -the agent started is read-only, and a thread on a linked machine is read-only -with **Connect to interact**. +- **Usage limits**: When a provider hits a rate/usage limit (**Limited**), press **Resume** in an empty composer after reset (or send a message). If the provider reports a reset time, choose **Resume at reset** or **Snooze until reset**—or enable defaults in **Settings → Threads** (**Resume after usage limits** / **Snooze until limits reset**). +- **Subagents**: Follow delegated work from the conversation card or **Agents**. Stopping a parent thread also stops its delegated subagents. Subagents started internally by the provider are read-only; message the parent thread instead. +- **Running dev servers** (web/desktop): The thread details card lists local servers started by the thread's terminals or Claude agent with their ports. Click one to open it in the browser panel, or **Stop** to end it (macOS/Linux only). +- **Customize thread details**: Right-click the thread details card or open **Settings → Appearance → Thread details** to show/hide rows. -Other thread links open in the main view as before. +## Open a thread beside the one you are in -On mobile these threads open in the inspector on layouts that have one, where -Maximize fills the screen, and full screen everywhere else. +On web and desktop, subagents, side chats, and [threads on linked machines](./remote-access.md#read-a-linked-machines-threads) open as a tab in the right panel by default so your main thread stays visible. + +- Hold `Cmd`/`Ctrl` while clicking (or middle-click) to open in the main view instead. +- Change the default in **Settings → Chat → Open subagents and side chats in**. +- From a right-panel tab, choose **Open in main view** to promote it. +- On mobile, they open in the inspector where available, or full screen otherwise. ## Side chats -A side chat lets you ask a question about a thread without adding to it. It starts -with what the thread knows, and the thread keeps working while you ask. - -On web and desktop, start a message with `/side` or `/btw`, then your question. -You can also choose **Side chat** from the **+** menu in the right panel. The side -chat opens as a tab there, with its own composer. Side chats do not show in the -sidebar. Find one again under **Side chats** in thread details, where it opens -[like a subagent does](#open-a-thread-beside-the-one-you-are-in). - -A side chat works in the same folder as the thread and starts with the permissions, -model, and reasoning level shown in the thread's composer, including for its first -reply. Change them for an individual side chat in its composer. Later changes to the -parent do not change existing side chats. - -To use what you learned, choose **Add to chat** at the top of the side chat, or type -`@` and a word from its title in the thread's composer. The thread's message gets a -link to the side chat, and the agent reads as much of it as it needs. This works -while the thread is busy, once you have sent a message in the side chat. An agent on -an external OpenCode server cannot read the link, so put the details in your message -instead. - -Closing a side chat you never sent a message in deletes it. To delete one you used, -choose **Delete** at the top of the side chat. Deleting a thread also deletes its -side chats. Archiving a thread also archives its side chats and stops their work, and -unarchiving the thread brings them back. - -On mobile, a thread lists its side chats above the composer. Tap one to open it and -answer its questions. - -## Snooze until later - -To change the choices in the snooze menu, open **Settings → Threads → Snooze options**. -Each option is a duration, such as 3 hours, or a time on a day, such as 9:00 PM -tomorrow. A weekday means the next one after today. Menus list the options soonest -first and hide a today option after its time passes. Saved with **All environments** -selected, the options apply to every connected environment, and the mobile app uses them too. - -Choose **Snooze → Custom…** from a thread's menu to pick a date and time in your -local time zone, or a duration in minutes, hours, or days. Durations start when -you confirm; one day means 24 hours. On web and desktop, you can also snooze -several selected threads together. Choose **Wake thread** to bring a thread back early. - -A snoozed thread keeps working and stays hidden until its wake time, even while -its agent wakes itself for background work. It comes back early for an approval, -a new question, a failed run, or a message or answer you send. You can snooze an existing -question and answer when the thread wakes; the question stays unanswered. +Ask a quick side question about a thread without polluting its history. A side chat starts with the parent thread's context, folder, model, and permissions while the parent keeps working. + +- **Start** (web/desktop): Send `/side ` or `/btw `, or choose **Side chat** from the right panel's **+** menu. +- **Find later**: Listed under **Side chats** in thread details (web/desktop) or above the composer (mobile); hidden from the main sidebar. +- **Bring results back**: Click **Add to chat** in the side chat, or `@`-mention its title in the parent composer (not readable by external OpenCode servers). +- **Lifecycle**: Closing an unused side chat deletes it. Deleting or archiving the parent thread deletes or archives its side chats. diff --git a/docs/user/triage.md b/docs/user/triage.md index ae2d453d81992..1642faf547191 100644 --- a/docs/user/triage.md +++ b/docs/user/triage.md @@ -1,42 +1,20 @@ # Triage an issue -Triage lets your own coding agent investigate a T3 Code problem. The agent -reads the logs and state of the machine, checks the T3 Code source for that -version, finds known issues, and can help you write a good GitHub issue. It asks -before it applies a fix or posts anything. +Let your own coding agent investigate a T3 Code problem—reading local logs/state, inspecting the source for your installed version, checking known issues, and helping draft a GitHub issue. The agent always asks before applying fixes or posting anything. ## In the app -Open the command palette and choose **Triage an issue**. A new thread with no -project opens, with the triage playbook linked in the message. Choose any -provider, describe what went wrong after the link, and send. T3 Code gets the -source for the server's version while you write. - -Triage runs on the machine of the thread or draft that you have open. With -nothing open, it uses your primary machine if that supports triage, or else the -first connected machine that does. The new thread shows the machine name, and on -mobile the palette row shows it before you start. If you change the machine -before you send, triage moves to that machine. The agent runs inside that T3 -Code server, so it gives you any restart steps and does not do them itself. +Open the command palette (`Cmd/Ctrl+K`) and run **Triage an issue**. A no-project thread opens on the active machine with the triage playbook attached—pick any provider, describe the problem, and send. ## In a terminal -If the app does not start, or triage does not work in the app, run: +If the app won't start or in-app triage fails, run: ```sh npx t3 triage -``` - -It starts Claude Code, Codex, or Antigravity in your terminal with the same -instructions. If more than one is installed, it asks which to use. You can also -choose explicitly: - -```sh +# Or choose a specific CLI agent and model: +npx t3 triage --agent codex --model npx t3 triage --agent antigravity -npx t3 triage --agent codex ``` -Antigravity needs Google's standalone `agy` CLI on your `PATH` and its own sign-in. -The ACP runtime installed through T3 Code does not include this terminal CLI. -Install it using [Google's CLI setup guide](https://antigravity.google/docs/cli-getting-started). -Pass `--model ` to choose a model, or leave it out to use the CLI's default. +Supports Claude Code, Codex, and standalone Antigravity (`agy` on `PATH` with its own sign-in; T3's managed ACP runtime does not include the standalone terminal CLI). diff --git a/docs/user/updating.md b/docs/user/updating.md index cbb25110857b8..ce75bdfc45b82 100644 --- a/docs/user/updating.md +++ b/docs/user/updating.md @@ -1,214 +1,53 @@ # Updating T3 Code -The app you use and the server running your agents can be on different machines. -When a server is behind your web or desktop app, the update button at the bottom -of the sidebar and **Settings → Environments** offer to update it. +T3 Code clients and servers can run on different machines and must share a compatible orchestration protocol. When a server or provider is behind, the sidebar update button and **Settings → Environments** handle updates. ## Update everything at once -The update button at the bottom of the sidebar updates every connected machine -in one step. It updates outdated providers, then servers that are behind, then -the desktop app you are using. Servers move to the -version your desktop app is installing, or to your web app's version. A -background service stays on its current release channel. A remote desktop app -installs the latest release from its own channel. Hover the button to see what -it will update. - -While it runs, the button widens to show progress. It names a machine that is -taking longer than usual, and offers **Retry** for a server that failed. Click -it to see every machine. The desktop app restarts once each server has started -its own restart, after a short countdown. Choose **Later** to keep working and -restart from the update button when you are ready. A server still restarting -finishes on its own, and the button keeps showing it after the desktop app -restarts. - -Each server checks that it can install the release before it restarts. If the -release is not available to a server yet, its update fails, the server keeps -running, and you can retry. The confirmation lists each machine it skips and -why, such as a machine that is offline or needs a manual update. Use -**Settings → Environments** for those. - -If a desktop app restarts on its old version, T3 Code tells you the update did -not apply. It does not install that version again on its own, even when another -device asks. Use the update button on that machine to retry. - -The confirmation counts the running threads that the restarts will interrupt, -and how many can resume afterwards. See **Continue threads after restarts** -below. +Click the **Update** button at the bottom of the sidebar (web or desktop) to update outdated providers, behind servers, and the desktop app in one step. -## Switch between Stable and Nightly - -In the desktop app, change **Settings → About → Update track**. T3 Code shows each -connected machine it will move and each one it skips, then moves them in one -step. Remote servers install the latest release on the new track. Remote desktop -apps reinstall on the new track. This app reinstalls last. Your threads, -settings, and data stay. - -A background service cannot move to an older release remotely. When Stable is -older than its Nightly, run `t3 update --channel stable --allow-downgrade` on -that machine. - -A switch is blocked for a machine whose database already has changes the -target release does not support, or when T3 Code cannot confirm that it does. -The dialog says why: update a machine on its current track first when its -release is too old to check, or wait until the target track includes the -changes. A Mac running the desktop app must switch on that Mac. - -Each machine keeps the new track even if its switch did not finish, but it -moves to that track only through a switch. **Update track** shows how many -machines still run the other track. **Review** opens the same dialog with fresh -checks. - -## Before you update - -Server updates restart the connection and can interrupt active agents and -terminal commands. Saved threads, settings, and project files remain. - -**Settings → Maintenance → Continue threads after restarts** is on by default. -It resumes supported active threads after an update, crash, or machine -restart. Changes are saved to connected environments that support this setting; -update older servers first. If a supported environment was offline or has a -different value, use **Apply to all** in Settings after it connects. -T3 Code must start again on that machine; -the setting does not enable automatic startup. Terminal commands may still be -interrupted, and threads without saved provider resume state need a new message. -A thread that finished its turn to wait on a subagent, a background task, a Claude -monitor or `sleep` timer, or a command or other monitor the agent said it was waiting on is woken and told that this work -stopped. Other background shells and monitors, such as a dev server and its -watchdog, do not wake it; the thread learns about them with your next message. -A thread is not resumed while it waits for your approval, answer, or secret, or -while it is archived, snoozed, or settled. After three consecutive crash recoveries -of an unfinished turn, the thread waits for your next message, even when crashes -are more than five minutes apart. A completed turn or a planned shutdown resets -that limit. - -Updates from the previous orchestration system preserve conversation transcripts but cannot carry -every kind of runtime history forward. Read [Threads from older T3 Code versions](./thread-migration.md) -before continuing an important older thread. - -## When versions don't match - -A client and server must speak the same orchestration protocol. If they do not, the connection is -refused rather than running half-upgraded: - -- An app newer than the server is blocked before connecting, with a notice telling you to update - T3 Code on the machine named in the notice. -- A server newer than your app refuses the connection with an update message. - -Update the side the notice names, then reconnect. - -## Update a connected server +- Hover to preview what will update; click while running to view per-machine progress or retry failures. +- Confirmation dialogs show which machines are skipped (offline or manual-only) and how many active threads will pause/resume. +- Choose **Later** on the desktop restart countdown to restart when ready. -The offered action depends on how the server runs: - -| Action | What to do | -| -------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| **Update server** | Keep the client open while it installs and reconnects. Supported background services update remotely. For a desktop-hosted server, this also closes and relaunches the desktop app on the host. | -| **Update the desktop app** | Update the desktop app on the machine running the server, then reopen it if needed. | -| **Copy update command** | Run the command on the named host to update the detected global npm install or installed `t3` command, then restart the server with your usual options. | -| **Copy relaunch command** | Stop the command-line server on its host and relaunch with the copied command, keeping your usual subcommand and options. This does not update an installed `t3` command. | - -On the host, run: - -```sh -t3 update -``` - -Replace `` with the version shown in the notice. The command -asks before restarting the background service; if you decline, run -`t3 service restart` when you are ready. For a server you started by hand, -stop it and start it again afterwards with your usual options such as `--host` -or `--tailscale-serve`. - -If you decline the restart for a background service installed by an older -release, the service can stay down after a crash or reboot until you run -`t3 service restart`. - -If you run the server with `npx` rather than an installed `t3`, there is -nothing to update on the host: stop the server and relaunch it as -`npx t3@` with the same subcommand and options. - -## If an update fails - -Keep the client open until it reconnects or reports a failure. A failed service -update can roll back to the previous version. If the update still fails: - -1. Retry the offered action once. -2. Check that you updated the server's machine, not only the device you are using. -3. For a command-line server, stop it and relaunch the exact version shown in the notice. +## Switch between Stable and Nightly -Only one server can use a T3 home directory at a time. If startup reports that -another server owns it, stop that server before retrying, or use a separate home -directory and pair with the running server. - -### macOS app does not reopen after an Alpha update +In the desktop app, change **Settings → About → Update track** to switch connected machines together. -Updating an older **T3 Code (Alpha)** installation can replace it with -**T3 Code (Beta)** without reopening the app. Open **T3 Code (Beta)** from -Applications, or run: +- Moving a background service to an older Stable release requires running `t3 update --channel stable --allow-downgrade` on that host. +- A switch is blocked if the machine's database has schema changes the target track doesn't support yet. macOS desktop apps must switch on that Mac. -```sh -open "/Applications/T3 Code (Beta).app" -``` +## Continue threads after restarts -If an old Dock shortcut no longer opens the app, remove it and add the Beta app -from Applications again. +**Settings → Maintenance → Continue threads after restarts** is enabled by default. After an update, crash, or reboot (once T3 Code starts again), supported active threads automatically resume—and threads waiting on subagents or monitors are woken and notified that background work stopped. -## If the desktop app does not start +- Threads waiting for your approval/answer/secret—or archived, snoozed, or settled—are not auto-resumed. +- After 3 consecutive crash recoveries of an unfinished turn, the thread waits for your next message. +- Updating from V1? Read [Threads from older T3 Code versions](./thread-migration.md). -If the desktop app's server keeps failing at startup, T3 Code shows a "T3 Code -could not start" window instead of the app. If a newer version is available, -choose **Update** to install it. If not, the window links to the last version -that started on your computer. Download and install it to go back. Use **Copy -details** to include the error in a bug report. +## Update a connected server manually -## Registries and proxies +| Situation | Action | +| ----------------------------------- | ----------------------------------------------------------------------------------------------------- | +| Background service / desktop server | Click **Update server** in **Settings → Environments** (desktop hosts relaunch automatically). | +| Installed `t3` CLI | Run `t3 update ` on the host (then `t3 service restart` if you declined the restart prompt). | +| `npx` server | Stop the server and relaunch with `npx t3@` and your usual flags. | +| Package manager (Nix, AUR) | Update via your package manager. | -Each server checks T3 Code releases, and providers installed with npm, through -its own npm, so the checks use npm's configured registry, authentication, and -proxy settings. Providers installed with Homebrew or pnpm check through those -tools. -Configure npm on the server's machine. If that registry cannot be reached, the -release shows as unavailable; T3 Code does not try the public registry instead. -Machines without npm check the public npm registry directly. +Each server checks npm/Homebrew/pnpm using its own local registry and proxy settings. ## Update providers -**Settings → Providers** shows provider updates for the selected environment. -**Update all** updates every outdated provider on every connected environment -at once. Hover it to see which providers it will update. A provider is left out -when any of its enabled, outdated instances offers only a manual update command, -or when its instances use different update commands, such as two instances that -run different CLI installs. Update those by hand, or point every instance of the -provider at the same CLI. +Open **Settings → Providers** and click **Update now** on individual providers or **Update all** across connected environments. Running chats keep using their current CLI until they end; new sessions and model catalogs refresh automatically. (Provider update checks in **Settings → Maintenance** must be enabled to fetch model catalog updates.) -After a successful provider CLI update, T3 Code refreshes model discovery for -every enabled instance of that provider using its own configuration. Connected -clients receive the refreshed catalogs automatically. Provider update checks -must be enabled to download the latest T3 Code model catalog. +## Mobile updates -Provider updates do not restart running chats. An existing session can keep -using the previous CLI until it ends. If discovery fails, check the provider -status and refresh it again. +- Update connected environments and providers from **Settings → Environments** on mobile. +- Update the mobile app via the App Store or Google Play (background over-the-air updates apply on next app switch and preserve drafts/queued messages). -## Mobile updates +## Troubleshooting -To update an environment from your phone, open **Settings → Environments** and -select it. **Check for updates** finds the latest release on that environment's -current release channel. Keep the app open while the environment updates and -reconnects. Hosts that cannot update remotely show instructions for updating on -the machine instead. - -The same page lets you refresh provider status and update supported providers. -These controls require a connected environment and permission to operate it. -Provider update checks and restart continuation preferences are in -**Settings → Maintenance**. If provider update checks are disabled, enable them -there before refreshing to find newer versions. The same setting controls whether -T3 Code downloads model catalog updates, so with it off new models may not appear -until you enable it and refresh provider status. - -Install App Store or Google Play releases as usual. The mobile app can also -download updates in the background and apply them when you next leave the app. -It saves drafts and queued messages before restarting. If you keep the app open -for a long time, it may ask to install immediately; choosing **Later** leaves the -update queued for the next suitable moment. +- **Version mismatch**: Update whichever side (app or server) the connection notice names. +- **Failed update**: Retry once; confirm you updated the host machine (not just the client) and that only one server owns the T3 home directory. +- **macOS Alpha → Beta**: Open `/Applications/T3 Code (Beta).app` manually and re-pin it to the Dock. +- **Desktop won't start**: Use the recovery window's **Update** button, install the linked last-working version, or **Copy details** for a bug report. diff --git a/docs/user/usage.md b/docs/user/usage.md index 6681bd34ea402..14b4c1b6aa567 100644 --- a/docs/user/usage.md +++ b/docs/user/usage.md @@ -1,100 +1,22 @@ # Usage and limits -Open **Usage** from the sidebar or the command palette, or press `mod+u` on web and -desktop when the terminal is not focused. Press it again to close Usage. Customize **Usage: Toggle** in -**Settings → Keybindings**. +Track token usage, cache hit rates, estimated API-equivalent costs, and pooled subscription quotas across all connected environments. -On mobile, choose **Usage** in the workspace navigation. +- **Open Usage**: Click **Usage** in the sidebar, press `mod+u` (web/desktop outside terminals), or pick **Usage** on mobile. +- **Quick shortcuts** (web/desktop on Usage): `C` (Cost), `T` (Tokens), `L` (Limits), `mod+Shift+1/2/3/4` (24h / 7d / 30d / 90d), `Esc` (back). ## Understand your usage -**Usage** combines Codex, Claude Code, Grok Build, OpenCode, Antigravity, Pi, Muse Code, and Cursor history -from your connected environments. It shows token use, cache savings, model breakdowns, and estimated API-equivalent -cost, split by token type and by speed. These estimates are not your subscription bill. -**Premium** is what Fast and Ultrafast requests cost above standard rates. Cost that cannot be -split, such as a provider-reported cost for a model without public rates, shows as **Other**. -Select a model under **Breakdown** to see its trend, cache hit rate, and cost per million tokens. - -Totals depend on the history available on each server. Grok turns without a saved completed-turn -record are missing from the totals. -Text generation (thread titles, commit messages, PR text, branch names and review guides) is not in -the totals for Codex or Claude Code 2.0.63 and newer, because those runs save no session history. - -The server keeps scanned usage history for 92 days by default. Claude Code deletes its own -transcripts after 30 days, so for older Claude usage this history is the only record left. To keep -it longer, set `usageHistoryRetentionDays` in `/userdata/settings.json` to a number of days -such as `365`, or to `"unlimited"`. Usage views still show at most 90 days. Lowering the value -prunes older history on the next refresh, and raising it again does not bring pruned history back. -While `settings.json` cannot be read, nothing is pruned. - -OpenCode reads its SQLite database and older JSON history. Antigravity reads local conversation -databases, including T3-managed profiles. Set `OPENCODE_DATA_DIR` or `ANTIGRAVITY_DATA_DIR` on the -server to read a different data directory; comma-separated paths read multiple directories. - -Cursor reads account usage from Cursor's API for the account you signed in with in T3 or set as -`CURSOR_API_KEY`. This includes headless T3 sessions and desktop usage across machines; the same -account counts once across connected environments. T3 does not estimate missing tokens from -conversation text. - -Usage includes each configured account's history, including disabled accounts. Custom homes follow -the account's home setting or its `CODEX_HOME`, `CLAUDE_CONFIG_DIR`, or `GROK_HOME` environment -variable. Pi reads `~/.pi/agent/sessions`, or the `sessions` directory under -`PI_CODING_AGENT_DIR`. Set `PI_CODING_AGENT_SESSION_DIR` to read a different session directory. -To include sessions saved through `--session-dir` or Pi's `sessionDir` setting, set this environment -variable to the same directory. Pi includes recorded tool and summary costs under `Tools/summaries`. -Muse Code reads native session history, including child sessions, from the home reported by the -configured Muse CLI. Its environment settings, including `XDG_DATA_HOME`, apply. Models without -known prices still contribute tokens and appear as unpriced; set custom prices to estimate their cost. -Use absolute paths or `~/` paths in the account's environment settings; relative environment paths -depend on each project's working directory and cannot be reliably discovered by Usage. Accounts -sharing a history directory count once. - -The server saves its first hostname in `/usage-host-id`, so a recreated container keeps -its usage identity when T3 home is persisted. Set `T3CODE_HOST_ID` to choose the identity -explicitly. - -When your app and server support different providers, usage totals may cover only the providers -your app understands. Update the app to include newly supported providers. - -On web and desktop, use the environment dropdown to filter costs, tokens, and limits. All -environments are selected by default. The dropdown shows which environments are still scanning; -results appear as each one responds, and figures still updating are dimmed. Cursor shows its last -saved totals first, then updates them when Cursor's API responds. - -If recent work is missing or a new model shows no cost, refresh to rescan session history and -update model pricing. - -## Set custom model prices - -On web or desktop, open the environment dropdown on **Usage**, then choose **Model prices** to add, -edit, or reset a model's estimated price. **Apply to** starts with your current Usage filter; -choose all environments or select individual destinations. Enter the exact model ID and USD -rates per million input and output tokens. You can enter any model ID, including models -without public pricing. When a model on **Usage** has no known price, select it under -**Breakdown** and choose **Set price** to open this table with that model added. - -Cache read and cache write rates are optional and use the input rate when blank. Enter `0` for -tokens that are free. Saved prices replace automatic pricing for all of that environment's -history and are shared with clients connected to it. When environments have different prices, -cells show **Mixed**. Edit rates directly in the table, then choose **Save changes** to apply all -edited rows. Untouched cells keep each environment's rate. Select one environment to inspect its -prices. **Reset to automatic** marks a model's override for removal when you save; you can undo -it before saving. - -To count one model as another, such as a preview model under its released name, enter the target -model ID under **Map to**. The mapped model no longer appears on **Usage**: its tokens and cost -move to the target model and use the target's price. Clear **Map to** or reset the row to show -the model on its own again. - -Each destination reports whether the change saved. Offline or unavailable environments are -marked **Not saved**. Reconnect them and choose **Retry failed saves** to finish the same change -without writing again to environments that already saved. Changes are not queued after you close -the dialog. - -## Show only some models - -To count only some models, or to leave some out, add `usageModelFilter` to the server's -`settings.json` in its `userdata` directory, such as `~/.t3/userdata/settings.json`: +Usage aggregates history across Codex, Claude Code, Grok Build, OpenCode, Antigravity, Pi, Muse Code, and Cursor from your selected environments. Estimates reflect API-equivalent rates (not your subscription bill); **Premium** shows Fast/Ultrafast surcharge, and **Other** shows unsplit provider-reported costs. + +- **Retention**: Servers keep scanned usage history for **92 days** by default (preserving Claude history after Claude's 30-day cleanup). Change `usageHistoryRetentionDays` in `/userdata/settings.json` (e.g. `365` or `"unlimited"`; views show up to 90 days). +- **Custom data directories**: Honors `CODEX_HOME`, `CLAUDE_CONFIG_DIR`, `GROK_HOME`, `PI_CODING_AGENT_DIR` / `PI_CODING_AGENT_SESSION_DIR`, `OPENCODE_DATA_DIR`, `ANTIGRAVITY_DATA_DIR`, and `XDG_DATA_HOME` (Muse). Use absolute or `~/` paths. Set `T3CODE_HOST_ID` to pin a container's host identity. +- **Exclusions**: Codex and Claude Code 2.0.63+ text-generation runs (titles, commits, PR text, review guides) and Grok turns without a saved completed-turn record are not included. + +## Custom model prices and filtering + +- **Custom prices & model mapping**: Open the environment dropdown on **Usage → Model prices** (or click **Set price** on an unpriced model) to set USD per million input/output/cache tokens, or set **Map to** to merge a preview/alias model ID into a target model's totals. +- **Filter models**: Add `usageModelFilter` to `/userdata/settings.json` (applied before **Map to**): ```json { @@ -105,102 +27,27 @@ To count only some models, or to leave some out, add `usageModelFilter` to the s } ``` -`include` keeps only the listed models and `exclude` leaves the listed models out. `provider` is -one of `claude`, `codex`, `cursor`, `grok`, `opencode`, `antigravity`, `pi`, or `muse`; omit it -to match a model ID from any provider. Use the model ID that Usage shows without **Map to**, such -as a provider-prefixed ID for Pi. Filters apply before **Map to**, so a model you leave out is not -counted under its mapped name. Usage applies each environment's own filter. Remove the setting to -show every model again. - -If the setting is invalid, Usage ignores it and shows every model, and the next save of any other -setting removes it from `settings.json`. - -## Track subscription limits - -**Usage → Limits** pools every subscription account it can see per provider, so with several Codex -or Claude accounts across your enabled environments and hubs you read one number per window rather than a -list. Each window card shows how much of the pool is left and a bar with one segment per account, -kept in the same column across windows. Accounts are ordered by their next 5-hour refill, soonest -first. For an account with no weekly quota left, this is when its session becomes usable again. -The first available window is used when no account reports a 5-hour limit. A gap means the -account does not report that window. When the provider reports reset times, the card also says -when the next reset lands and how much it hands back. The hatched -part of a segment is what that reset restores. Tap a segment or account row for the account's plan, -where it is signed in, and its reset time. On web, you can hover too. Codex and Claude accounts -with banked reset credits show a ticket count and the **Use reset** action in the account details. -Claude resets are not available when the server runs on macOS, where Claude keeps its login in the -Keychain. On narrow screens, numbered rows below -the bar show each account's quota, countdown, and credits. Tap a row to open its details. - -The same account signed in on more than one environment, or reported by a hub as well, counts once. -Filter with the environment dropdown to see what a single machine has. - -When a Claude or Codex account has no overall weekly quota left, its pooled session contribution -shows 0% left. The next refill depends on both reset times: an exhausted session must also reset, -and a partly spent session may only regain its unused portion when the week resets. Missing or -stale reset times have no refill estimate; refresh Limits for a new reading. Claude's -model-specific weekly allowances keep their reported values. - -Opening Limits checks the selected connected environments automatically. Each client waits at -least five minutes between automatic checks of an environment, including after a failed check. -If a window still looks stale, refresh Limits to re-check every provider and hub. - -Pick `/usage-limits` from the composer's command menu, or send it as a message, to check the -current model's limits without leaving the conversation. The result opens above the composer and -closes when you dismiss it or send your next message. It uses the same snapshot as **Usage → Limits**, so it does not run the agent or refresh -anything. The command is offered only for providers that appear under **Usage → Limits**. - -To keep them in view on web and desktop, turn on **Usage limits** in **Settings → Appearance → Thread details**, or right-click the thread details card. -The bottom of the thread details card then shows how much is left in each limit window of the -current provider account. Some windows, such as a weekly Opus limit, count only one model. Hover a -row to see when it resets and your pace. Turn on **Context window** to also show the thread's -context use against the model's limit. A tick on the bar marks where the provider compacts -automatically, when it reports that point. - -OpenCode Go reports its session, weekly, and monthly allowance when OpenCode runs locally in -the environment. T3 cannot report limits for external OpenCode servers because their credentials -belong to the remote server. Limits need an OpenCode Go API key, or an OpenCode Console connected -in OpenCode with an API key. A Console browser sign-in alone does not report them. You can also add -your Go API key as `OPENCODE_API_KEY` in the OpenCode instance's **Environment variables**, then -refresh provider status. Cursor reports -its monthly allowance, including separate Auto and API usage, for `CURSOR_AUTH_TOKEN` when it is set, -otherwise for the account you signed in with in T3 or set as `CURSOR_API_KEY`. -Sign-in and API keys report limits only with Cursor's default API endpoint. If you configure a custom -Cursor endpoint, use an explicit `CURSOR_AUTH_TOKEN` for limits. - -Grok reports the remaining subscription allowance and reset time for its current billing period -after signing in with `grok login`. Explicit `XAI_API_KEY` connections and custom authentication -or endpoint configurations do not report subscription limits. - -Muse Code reports its session and weekly windows and its tier once the Muse CLI has run in a thread. -Until then it shows no limits. Readings are not kept across a server restart. - -API-key accounts may not report subscription limits. This also applies to Claude connections -using a proxy through `ANTHROPIC_AUTH_TOKEN`. +## Subscription limits -## Connect a CLIProxyAPI hub +**Usage → Limits** pools subscription quotas per provider across connected environments and hubs (deduplicating the same account signed in on multiple machines). -To see pooled accounts, open **Settings → Providers → Usage providers → Add hub**. Choose the -environment that will connect to the hub and enter its URL and management key. +- **In chat**: Run `/usage-limits` in the composer to view the current model's snapshot without running the agent, or enable **Settings → Appearance → Thread details → Usage limits** (web/desktop). +- **Reset credits**: Click an account segment/row to inspect plan details and redeem banked Codex/Claude reset credits via **Use reset** (Claude resets unavailable on macOS Keychain logins). +- **Provider notes**: + - **OpenCode**: Reports OpenCode Go / Console API-key quotas for local servers (`OPENCODE_API_KEY`). + - **Cursor**: Reports monthly Auto + API quotas via `CURSOR_AUTH_TOKEN` or default-endpoint sign-in/`CURSOR_API_KEY`. + - **Grok**: Reports billing-period quotas for `grok login` (not `XAI_API_KEY`). + - **Muse Code**: Reports session/weekly limits after running in a thread (not persisted across restarts). + - Pure API-key accounts generally do not report subscription limits. +- **Mobile widget**: Add the **Subscription usage** widget on iOS or Android to monitor Codex and Claude quotas from your home screen. -The hub's Codex, Claude and xAI (shown as Grok) accounts appear under **Usage → Limits**; -accounts for other providers, including Antigravity, are not read. Codex accounts show banked reset credits; select an -account and choose **Use reset** to redeem one. No hub plugin is required. +## Connect a CLIProxyAPI hub -This connection supplies usage information; configure -the provider separately to send agent requests through the hub. A thread uses the hub's limits and -reset times only when its provider's endpoint has the same address as the hub, for example -`http://127.0.0.1:8317` for both. Remove the hub from the same settings section when you no longer -need it. +Open **Settings → Providers → Usage providers → Add hub**, choose the environment, and enter the hub URL and management key. Pools Codex, Claude, and Grok accounts under **Usage → Limits** (including Codex **Use reset**). Configure the provider's endpoint to the same URL if you want threads to display that hub's limits. ## Connect an HTTP quota source -In **Settings → Providers → Usage providers → Add HTTP source**, choose the environment that can -reach your quota server and enter the full endpoint URL. If the endpoint requires authentication, -supply a bearer token. The selected T3 environment sends a read-only GET with -`Accept: application/json` and shows the result in **Usage → Limits**. - -Return JSON in this format, with stable IDs for accounts and their windows. +Open **Settings → Providers → Usage providers → Add HTTP source** with a GET endpoint (and optional bearer token) returning: ```json { @@ -224,25 +71,4 @@ Return JSON in this format, with stable IDs for accounts and their windows. } ``` -Set `kind` to `session`, `weekly`, `monthly`, or `other`. Use a percentage from 0 to 100 and -omit `resetsAt` when the reset time is unknown. Your quota server handles the upstream provider -credentials and APIs. Set the optional `providerInstanceId` to the exact instance ID configured for that environment -in **Settings → Providers**. The account’s quota windows then appear in the -thread details usage card on web and desktop when that instance is selected. Accounts without -a binding still appear in **Usage → Limits**. - -## Subscription usage widget - -Add **Subscription usage** from your iOS or Android widget gallery to see remaining Codex and -Claude quotas. Tap it to open **Usage → Limits**; on Android this works while T3 is running in -the background, otherwise open the app from the launcher. On iOS, use **Edit Widget** to choose -Session, Weekly, or both for each provider. Reopen T3 to refresh expired readings. - -## Keyboard shortcuts - -On web and desktop, open Usage from the command palette. While on Usage, -press `C`, `T`, or `L` for Cost, Tokens, or Limits while not typing in a field. -Use `Ctrl+Shift+1/2/3/4` (`Cmd+Shift+1/2/3/4` on macOS) for the past -24 hours, 7 days, 30 days, or 90 days. Period shortcuts do nothing on Limits. -Press `Escape` to return to the previous page. Customize these shortcuts in -**Settings → Keybindings**. +`kind` is `session`, `weekly`, `monthly`, or `other`. Setting `providerInstanceId` binds the quota windows to that instance's thread details card. diff --git a/docs/user/voice-input.md b/docs/user/voice-input.md index 9831eeafd49f8..37923645c0de5 100644 --- a/docs/user/voice-input.md +++ b/docs/user/voice-input.md @@ -1,172 +1,36 @@ # Voice input -Dictate into the composer instead of typing. The transcript lands in your draft -for review, and only sending the message sends anything to an agent. Dictation -also works in citation comments, diff and file annotations, pull request -comments, replies, and review summaries, and in the desktop app's browser -annotation editor. - -On iPhone and Android, voice input transcribes on the device by default. To opt in -to a named environment on that phone, open **Settings → Voice → Transcribe on**. See -[Voice input on mobile](./composer.md#voice-input-on-mobile). +Dictate into the composer, citation comments, diff/file annotations, PR comments, and desktop browser annotations. Transcripts land in your draft for review—nothing is sent to an agent until you submit. ## Choose where audio goes -On web and desktop, you choose where transcription runs. -Nothing is sent until you choose one: open **Settings → Voice** and set -**Transcribe with** to the environment that should transcribe for you. -On a new device, the microphone or dictation shortcut opens that setting from the composer. -Microphone audio recorded on this device is sent to that environment over your -authenticated connection, transcribed there, and discarded. The choice is saved -on this device only, so every computer and browser you use asks for it once. -Set it back to **Off** at any time; a recording in progress is discarded. - -If the chosen environment goes offline, voice input waits for it. T3 Code never -substitutes another environment. - -In the desktop app on macOS 26 or later, you can instead choose **Apple Speech** -under **On this Mac**. Audio stays on the Mac and macOS transcribes it. The first -recording in a language can take longer while macOS downloads its speech model. -**Language** set to automatic uses your Mac's language. Silence filtering and -filler-word removal are not available; the dictionary applies only when transcript -cleanup is on. - -For cloud dictation, choose **OpenAI** or **Grok Voice Transcribe** via the environment -you want to use. If it needs a key, enter one and choose **Save and enable**. -You can also choose a [secret provider](secrets.md) instead of **Value** and enter a -reference. Unlock the vault on that environment before dictating. Anyone with -dictation access to the environment can use the key, but only this device opts in. -If a key is already saved, just confirm the provider. After -you stop, the environment forwards your recording and any vocabulary hints to -the selected provider, which bills its API account. No local model download or chat -subscription is needed. Switch back to **This device** on mobile or **Off** on -web and desktop to stop sharing. Removing the key stops that provider for everyone -on the environment. - -**OpenRouter** works the same way but has no default model: pick one from its live -speech-to-text catalog when you enable it, or later under **Manage OpenRouter**. -The model choice is yours alone and needs no settings access, so anyone with -dictation access can pick a different model without touching the saved key. -OpenRouter chooses who runs the model. T3 requests zero data retention; your -OpenRouter account can also allow safety retention. If no endpoint qualifies, -dictation fails instead of switching models. -Vocabulary hints are not sent to OpenRouter; dictionary spellings are applied -after transcription. If OpenRouter stops listing your model, dictation stops -until you choose another. - -## Set up a model - -In **Settings → Voice → Transcription**, download a model and choose **Use model** if it -isn’t already selected. **Test model** lets you try it without sending a message. -If you use the composer microphone before a model is installed, it offers to download one. -The recommendation uses your Voice language, or your system’s preferred languages with **Auto-detect**. - -If another app already downloaded one of these models, you don’t need a second copy. -**Download** first looks in Handy’s model folder and the Hugging Face cache on that -environment and uses a copy it finds there instead of downloading. For a copy anywhere -else, on web or desktop, paste the path of the model file or its folder under the model -list and choose **Use existing**. The path is on the environment -that transcribes, not on the device you are using. T3 Code checks that the file is exactly a -model from its list and then uses it in place. Removing the model in T3 Code leaves your file -alone; if the other app deletes it, download or link the model again. Files in another -format, such as Core ML, ONNX, or MLX builds of the same model, can’t be used. - -Select the languages you dictate in to compare models that support all of them. -Accuracy shows how often the model got words or characters wrong in each -language; speed is the time to transcribe 30 seconds on a reference CPU or GPU, -matching the selected environment's transcription backend. Recommendations use -the same reference tier for every selected language. Choose **All languages** to -browse without a language preference. Filtering does not switch your model. - -**Advanced** controls GPU or CPU use and when an idle model is unloaded. With hardware set to -**Auto**, a recording that fails on the GPU is retried once on that same -environment's CPU; a GPU you picked yourself reports the error instead. Nothing -is ever retried on another environment. Models marked **Live preview** show -text while you speak. On web and desktop, turn off **Advanced → Streaming transcription** -to transcribe with the same model after stopping instead. This may help when live -transcription falls behind. The preference is saved on this device and only applies -to models that support native streaming. Other models can process long recordings in chunks at pauses -while you record; models with built-in long-form support transcribe when you stop. - -## Dictate - -Press the microphone in the composer, or `mod+shift+d` (`mod` is Command on -macOS and Ctrl elsewhere). Press again, or the check mark, to finish; `Esc` -discards the recording and leaves your draft unchanged. Recordings last up to -five minutes. Text is inserted at the cursor or replaces the selection you had -when recording started, and the editor is read-only while dictation runs. -Changes that reach the draft meanwhile, such as a cited message, are kept; -the text then goes after your selection instead of replacing it. -A file or thread you paste or drop in meanwhile can be removed by focusing its -chip and pressing Backspace or Delete. - -Pressing Send while dictating finishes the recording and sends the draft once -the transcript has been inserted. Cancelling also cancels that queued send. In -the other editors, Save, Comment, Reply, Submit review, or Attach works the -same way, and the shortcut targets the editor that has focus, or the composer -when none does. In the desktop browser's annotation editor, the microphone and -the shortcut work while the page has focus; the page you are annotating never -sees the recording, which runs in T3 Code itself. - -**Dictation shortcut** in Voice settings picks how the keybinding behaves: -**Auto** tap-toggles or records while held, **Hold** records only while the keys -are down, and **Toggle** always needs a second press. Change the chord itself in -[Keybindings settings](./keybindings.md). - -## Improve recognition +- **Web and desktop**: Nothing is recorded or sent until you choose a destination in **Settings → Voice → Transcribe with**: + - **On this Mac (Apple Speech)** (macOS 26+ desktop): Transcribes locally on your Mac (silence filtering and filler removal unavailable; dictionary applies only with cleanup enabled). + - **A connected environment**: Sends audio over your authenticated connection to transcribe locally on that host and discards the audio. Never silently fails over to another host. + - **Cloud providers (OpenAI, Grok Voice Transcribe, OpenRouter)**: Configure an API key (or [secret reference](./secrets.md)) on an environment to forward recordings to that provider. OpenRouter lets each user pick a model from its live STT catalog and requests zero data retention. +- **Mobile (iOS and Android)**: Transcribes on-device by default (iOS 26+ or Android 12+ with compatible Google speech services; first use may download a speech model, then works offline). To transcribe on a paired environment or cloud provider instead, configure **Settings → Voice → Transcribe on**. Keep T3 Code open while dictating on Android. -- **Language** picks what you speak. **Auto** lets a multilingual model detect - it. Models that translate offer **Translate to English**. -- **Dictionary** holds names and terms the model should get right. Add an alias - under a term when transcription keeps producing a particular misspelling. - Your dictionary is saved on this device. The name of the project you dictate - in is sent along as a hint. -- **Project dictionary** is vocabulary saved with a project on its environment, - so everyone who dictates in that project gets the same spellings. Pick the - project at the top of Settings to edit it; with an environment selected, the - entries apply to every project there. Project spellings win when they overlap - your personal dictionary. Each recording carries up to 100 entries from the - two combined. -- **Silence filtering** is on by default. Your chosen environment skips non-speech - audio before transcription. Turn it off to keep those sections. Filtering happens - after upload: it does not grant permission to send audio or reduce how much is sent. -- **Remove filler words** drops hesitation sounds from finished transcripts. +## Set up a local transcription model -Language and these preferences travel with each recording to the chosen -environment; nothing else about the project is sent. +In **Settings → Voice → Transcription**, filter by language, download a model, and select **Use model** (reuses matching files from Handy or the Hugging Face cache, or link an existing file via **Use existing**—Core ML/ONNX/MLX builds aren't supported). -## Clean up transcripts +- **Advanced**: Configure GPU/CPU (**Auto** falls back to CPU once on GPU error), idle unload timeout, and **Streaming transcription** (disable if live preview lags). -**Transcript cleanup** is a separate choice and is off by default. When on, the -finished transcript and up to 1,024 characters each from before, inside, and -after your selection are sent to the cleanup model on the draft's environment, -which fixes punctuation, numbers, and spoken corrections such as "make it 42, -sorry, 24". Depending on the model, that can involve an external service. Audio is never -sent to it. Use the built-in instructions or write your own, press **Skip** -while cleanup runs to insert the raw transcript, and if cleanup fails the raw -transcript is inserted. +## Dictate and shortcuts -Cleanup uses the environment's text generation model unless you pick a -**Cleanup model** for that environment, for example a cheaper or faster one. -It can be a text generator instead of a coding agent; see -[text generation models](./text-generation.md). +- Press the microphone button or `mod+shift+d` to start/stop (`Esc` discards; max recording length: **5 minutes**). +- Configure tap vs. hold behavior in **Settings → Voice → Dictation shortcut** (**Auto**, **Hold**, or **Toggle**), or remap the chord in [Keybindings](./keybindings.md). +- Pressing **Send** (or Save/Comment/Submit) while recording finishes transcription and submits automatically. -If cleanup misses the way you correct yourself, set a **Correction cue**: the -word or phrase you say to flag a correction, such as "scratch that". Cleanup -applies the correction only where the context shows one and drops the cue, and -the model hears the cue as a dictionary hint. +## Improve recognition and cleanup -## Test and troubleshoot +- **Language & translation**: Pick a language or **Auto** (plus **Translate to English** where supported). +- **Personal & project dictionaries**: Add custom terms and common misspelling aliases in **Settings → Voice** (device-level) or scoped to a project/environment (up to 100 combined entries; project entries take priority). +- **Silence filtering & filler removal**: Skip silence (on by default) and strip hesitation words. +- **Transcript cleanup** (off by default): Sends the finished transcript and surrounding draft text (never audio) to your [text generation model](./text-generation.md) (or a dedicated **Cleanup model**) to fix punctuation, numbers, and spoken self-corrections (optionally using a custom **Correction cue** like "scratch that"). Press **Skip** during cleanup to insert raw text. -In **Settings → Voice**, voice input uses the first connected microphone in the -**Microphone** list. A microphone joins the list below System default the first -time it is seen, so nothing changes until you move it up. If a preferred -microphone is unplugged, the next connected one is used. +## Microphones and testing -**Test microphone** records from that microphone for up to ten seconds and -plays it back in your browser; the audio stays on this device and is never transcribed, so silent playback -points at the microphone. **Test model** on the selected model shows a transcript using the -same environment, language, and dictionary as the composer, but skips transcript -cleanup even when it is on, so you see what the model heard. Browser recording -needs HTTPS or localhost and microphone permission; for a remote server over -plain HTTP, use the desktop app. +- **Microphone priority**: Rank built-in, wired, Bluetooth, and CarPlay (iOS) devices in **Settings → Voice**—T3 Code uses the first connected device in the list. +- **Test**: Use **Test microphone** (local 10-second loopback, no transcription) to verify input, and **Test model** to preview raw transcription without cleanup. +- Browser recording requires **HTTPS** or `localhost`—for plain-HTTP remote servers, use the desktop app. diff --git a/docs/user/welcome-page.md b/docs/user/welcome-page.md index ed8e75c28c74c..8715f5bd1960f 100644 --- a/docs/user/welcome-page.md +++ b/docs/user/welcome-page.md @@ -1,117 +1,37 @@ # Welcome page -T3 Code shows a Welcome page when you open a new installation. Existing -workspaces skip it. It shows what T3 Code found on the computer you are using, -on one page: your agents, projects from your Claude Code, Codex, and Pi history, -and the phone app. Only an agent is needed to start chatting. +The Welcome page runs on a fresh local installation to help you verify an agent, optionally import existing projects and conversations, and connect the mobile app. Only one ready agent is required to start. -To see the page again, go to **Settings → About → Welcome page** and select -**Open**. Direct links, such as Settings, open normally before setup is done. - -The hosted app at app.t3.codes does not open the page. With no computer connected, -it asks you to sign in to T3 Connect, then to install T3 Code and run -`t3 connect` on your computer. From home, it adds compatible computers linked to your account and -opens the app. To add more computers later, use **Settings → Environments**. - -If T3 Code cannot confirm the workspace during startup, it shows -**Still connecting** instead of opening the app. Select **Reload** to try again. - -If T3 Code cannot read your saved settings, it shows **Could not read settings**. -Select **Retry** after storage becomes available. Setup does not replace -unreadable settings with defaults. +- Reopen it anytime from **Settings → About → Welcome page → Open**. +- Hosted `app.t3.codes` skips this page and prompts you to sign in to T3 Connect and run `t3 connect` on your computer instead. ## Agents -T3 Code lists the agents it found on the computer first, ready ones on top. -**Add more agents** lists every other agent T3 Code supports, A to Z. When no agent -is found, it reads **Set up an agent** and opens by itself: - -- **Turn on** enables an agent that is off on this computer, including one only - some projects use. T3 Code then checks whether it is installed and signed in. -- For Claude Code, **Install** or **Sign in** opens a terminal with the correct - command ready to run. Install uses the vendor's own installer, which keeps - **Update now** working in Settings. -- For Codex, **Set up** offers sign-in with your ChatGPT account or your own - Codex CLI. **Use existing CLI** opens the terminal to install or sign in, and - **Continue with ChatGPT** stays available until Codex is signed in. -- When T3 Code knows an installed version does not work with it, **Update** opens - the agent in **Settings → Providers**, which shows the version to use and updates it - when it can. -- Other agents, and agents that could not load, open their page in - **Settings → Providers**. -- **Browse** opens the ACP Registry for more agents. +T3 Code lists detected agents first (ready ones on top), followed by **Add more agents** for all other supported providers: -On the desktop app, when the folder of the `t3` command is not on your `PATH`, -**Add to PATH** adds one line to your shell's startup file. +- **Turn on**: Enables a disabled provider and checks its install and sign-in status. +- **Claude Code**: **Install** or **Sign in** opens a setup terminal using the vendor's installer (so **Update now** keeps working in Settings). +- **Codex**: **Set up** offers ChatGPT sign-in or your existing Codex CLI. +- **Outdated or other agents**: **Update** or selecting the agent opens its page in **Settings → Providers**. **Browse** opens the ACP Registry. +- **Desktop CLI**: Click **Add to PATH** if the `t3` command isn't yet on your shell `PATH`. -The setup terminal uses the home directory and environment configured for the -provider instance. Sensitive values remain redacted in Settings and -terminal metadata while the terminal process can use them. - -**Start** waits for one ready agent. Select **Start without an agent** to finish -without one. Checked projects are still imported. +Click **Start** once at least one agent is ready, or **Start without an agent** to enter the app immediately (checked projects still import). ## Phone -Select **Set up** and scan the code with your phone. It opens the App Store on an -iPhone and Google Play on Android. Then select **Sign in to T3 Connect** and allow -this computer when T3 Code asks, so the app can reach it. Sign in to the app with -the same account. If you are signed in but this computer is not shared yet, select -**Set up T3 Connect**. If T3 Connect is on but the app cannot reach this computer, -select **Check T3 Connect** to see why. The page leaves the phone out on builds -without T3 Connect, or when your organization turns it off. You can still pair the -app with a code from **Settings → Sharing & access**. - -## Projects - -T3 Code finds directories that Claude Code, Codex or Pi has used. Git repositories -are listed first, newest activity on top. When the remote is on GitHub, the -group shows the repository as `owner/name`. Clones with the same remote share -one group. Directories that are not git repositories sit under "Other folders". +Select **Set up** to scan the QR code for iOS or Android, then sign in to T3 Connect on both devices. If T3 Connect is unavailable or disabled by policy, pair with a code from **Settings → Sharing & access**. -The page offers git repositories active within the last 30 days with at least -three conversations, already checked. Projects already in T3 Code are not checked -again. Uncheck the box to start without them, or -select **Review all** to pick from everything found, with "Select all" and -"Select none". Linked worktrees of bare repositories -can be offered as separate projects. Conversations in other linked git worktrees -count toward their main checkout, so a repository is offered even if you only -worked in its worktrees. Codex scratch directories under `Documents/Codex`, and -anything under `Downloads` are not offered. +## Projects and conversation import -A large or malformed history can reach the scan limit. T3 Code keeps the -projects it found and warns when projects or conversations may be missing. +T3 Code scans directories used by Claude Code, Codex, and Pi (turn on Pi under **Add more agents** to include Pi sessions). -Imported projects include Claude, Codex and Pi conversations active within the last -30 days. You can continue those conversations in T3 Code. Pi is off by default: -open **Add more agents** and select **Turn on** next to Pi, and the page looks for -its sessions too. Pi sessions -are read from each enabled Pi provider's session directory, which follows -`PI_CODING_AGENT_SESSION_DIR` and `PI_CODING_AGENT_DIR` in its environment. A -Pi conversation imports its active branch, the one Pi reopens. +- Git repositories active in the last 30 days with at least three conversations are pre-selected (excluding already-added projects, Codex scratch directories, and `Downloads`). Use **Review all** to customize the selection. +- Conversations active in the last 30 days are imported so you can continue them in T3 Code. -Conversation import is best effort. T3 Code keeps the first user prompt and the -newest remaining visible user and assistant messages, with 200 messages total. -It omits tool activity and attachments. For Codex, it omits generated setup -context only when a canonical user event and a valid shared turn ID identify the -same user turn. Ambiguous legacy or response-only context stays in the imported -conversation so T3 Code does not remove user text. For Claude, slash commands -and `!` shell commands appear as you typed them; their output, background task -notifications and interruption markers are left out, and a conversation that -only ran commands such as `/clear`, with no reply, is skipped. It reads one -conversation at a time and skips files larger than 4 GiB. It also skips a conversation when the -message text and metadata it keeps need more than 32 MiB of memory. Tool output -does not count toward that limit. It skips a conversation with more than 100,000 -records every time, so opening the page again does not import it. It ignores -malformed records and conversations with no messages, such as a session opened -in an editor but never used. It skips unreadable or unparseable conversations. +### Import limits -Each import attempt reads up to 100 conversations and 4 GiB per project. -Conversations with no messages count toward the 4 GiB but not the 100. To -continue a large batch, open the Welcome page again and pick the project in -**Review all**. Completed conversations are not imported again. You can continue -without the remaining history. +Conversation import is best-effort: -You can start without importing. While an import runs, T3 Code stays on the -Welcome page. If you quit, open the Welcome page again from **Settings → About**; the -projects you started stay checked. +- Keeps the first user prompt and the most recent visible user/assistant messages (up to 200 messages total), omitting tool activity and attachments. +- Skips malformed/empty sessions, files over 4 GiB, sessions over 32 MiB of kept text/metadata, or sessions with over 100,000 records. +- Each import pass reads up to 100 conversations and 4 GiB per project. Reopen the Welcome page and select the project in **Review all** to continue importing a larger batch; already-imported conversations are skipped. diff --git a/docs/user/workflows.md b/docs/user/workflows.md index 5621e3eef415e..e4cbe3f306195 100644 --- a/docs/user/workflows.md +++ b/docs/user/workflows.md @@ -1,21 +1,21 @@ # Workflows -A workflow is a TypeScript script that chains agents, plain code, schedules, webhooks, issue and pull request events, and questions to you into one durable run that survives server restarts. Each step's result is saved when it succeeds, so restarts pick up where the run left off and failures do not lose earlier work. Workflows are an early feature: start runs from the `t3` CLI or a trigger, and follow them in the app. +Workflows (Labs) are durable TypeScript scripts that chain agents, code steps, schedules, webhooks, issue/PR triggers, and human approvals into multi-stage runs that survive server restarts. Each completed step is checkpointed so restarts resume where they left off. -For one prompt on a timer or webhook, use a scheduled task. Use a workflow when work has stages — such as triage, a fix, your approval, and a release. +Use a **scheduled task** for a single prompt on a timer or webhook; use a **workflow** for multi-stage pipelines (e.g., triage → fix → approval → release). -## Turn on workflows +## Enable workflows -Workflows are a Labs feature, off by default. Turn on **Settings → Labs → Workflows** for the server that runs them. On a server without a desktop, set `"workflowsEnabled": true` in `userdata/settings.json` in its T3 home (`~/.t3` by default). While off, nothing in the workflows folder runs and `t3 workflow` says how to turn it on; runs are kept and continue once it is on again. +Turn on **Settings → Labs → Workflows** on the server that will run them (or set `"workflowsEnabled": true` in `~/.t3/userdata/settings.json` on headless servers). Existing runs pause while disabled and resume when re-enabled. ## Create a workflow -Workflow files live in `~/.t3/workflows/` (or wherever `T3CODE_WORKFLOWS` points — a folder or a single file). The server watches the folder and reloads changes without a restart. +Place `.ts` files in `~/.t3/workflows/` (or the path in `T3CODE_WORKFLOWS`). The server watches the folder and hot-reloads valid edits. -- **Ask an agent (recommended):** copy the [`t3-workflows` skill](https://github.com/pingdotgg/t3code/blob/main/skills/t3-workflows/SKILL.md) into your agent's skills folder (such as `~/.claude/skills/` or `~/.agents/skills/`) and describe what you want. -- **Edit directly:** edit files in `~/.t3/workflows/`, or use **Definitions** on the Workflows page (saving and deleting in the app require terminal access). Before anything has run, open the page with **Open workflows** in the command palette. +- **With an agent (recommended)**: Copy the [`t3-workflows` skill](https://github.com/pingdotgg/t3code/blob/main/skills/t3-workflows/SKILL.md) into your agent's skills folder (e.g. `~/.claude/skills/` or `~/.agents/skills/`) and describe what you want. +- **Directly**: Edit files in `~/.t3/workflows/` or use **Definitions** on the Workflows page (**Open workflows** in the command palette; saving/deleting in the app requires terminal access). -A small workflow, saved as `~/.t3/workflows/release.ts`: +Example (`~/.t3/workflows/release.ts`): ```ts const { workflow, step, ask, stop, title } = T3; @@ -36,13 +36,11 @@ export default workflow( ); ``` -Start it with `t3 workflow start release --input '{"name":"v1.4"}' --key v1.4`, then answer its question in the app. `T3`, `Effect`, `Schema` and `Option` are provided; a workflow file imports nothing from T3 or Effect. Name files with letters, digits, `-`, `_` and `.`; other names are skipped with a warning. +- `T3`, `Effect`, `Schema`, and `Option` are globals—no imports needed. +- Filenames may use letters, digits, `-`, `_`, and `.`. Dot-files and subfolders are ignored (put shared helpers in a subfolder; restart the server after editing imported helpers). +- **Versioning**: Keep older workflow versions defined while they have unfinished runs; bump `version` to deploy new steps alongside active runs. -Saving checks that the file loads, does not duplicate a workflow name and version, and does not remove a version with unfinished runs. A file that fails these checks keeps its last working version while the Workflows page (and the server log) shows why; other files are not affected. A change held back by unfinished runs goes in by itself once those runs end or are cancelled. Mistakes inside a workflow body surface when a run hits them and pauses. To change steps while runs are unfinished, add the new body under a higher `version` and keep the old one until those runs end. - -Dot-files and subfolders are ignored. Keep shared helpers in a subfolder and restart the server after editing an imported file. - -## Start and steer +## CLI commands ```sh t3 workflow start --input '' --key @@ -59,114 +57,34 @@ t3 workflow store list t3 workflow store set '' ``` -Every start needs a `--key`: starting twice with the same key returns the same run — even after a version bump — so retries do not duplicate work. Use `signal` with `--run` and `--wait` to answer a question or wake a run, or with `--workflow` and `--channel` to wake whichever run waits on that channel. A signal for a question that is no longer open is kept for a later wait rather than refused, so check `t3 workflow questions` first. Use `withdraw` when a question no longer needs an answer: its `ask` returns `None`, as on a timeout, and the run goes on; the step records who withdrew it and why. A workflow does the same from a step with `withdraw({ run, name, reason })`. Use `store` to read or change state kept between runs. - -## Kinds of question and tags - -A workflow that asks more than one kind of question can name the kinds, so you can answer one kind at a time. List them in the workflow's options with the label to show, and give each `ask` its `kind`: - -```ts -const { workflow, ask, tags, Issue } = T3; - -workflow( - "triage", - { - version: 1, - payload: Issue, - asks: { feature: "Feature wanted?", intended: "Bug or intended?" }, - }, - Effect.fn(function* (issue) { - yield* tags(["backlog"]); - yield* ask("wanted", { - kind: "feature", - title: `Build ${issue.title}?`, - choices: ["Yes", "No"], - }); - }), -); -``` - -Under **Needs you**, a picker then shows each kind with how many questions of it are open, and **Other** for the rest; your pick is remembered on that device. A question whose kind is not in the workflow's own `asks` is asked like any other and shows under **Other**, as do questions asked without a kind. `t3 workflow questions --kind feature` lists the questions asked with exactly that kind from the CLI. - -## Choices, reasons and links - -A choice can be plain text, or `{ value, description, requireReason }` to say what picking it does or to take it only with a reason. `links` puts what to look at before answering on the question: - -```ts -yield * - ask("wanted", { - title: "Build this?", - links: [{ label: "The request", url: issue.url }], - choices: [ - { value: "Yes", description: "Work starts on it" }, - { value: "No", description: "It is closed with a note", requireReason: true }, - ], - }); -``` - -The app asks for the reason before it sends a choice that requires one, and `t3 workflow signal` refuses that choice without a `reason`. Links open in your browser and are part of `t3 workflow questions --json`. The answer also records when it was given and who sent it (`answeredAt`, `answeredBy`): the device's name as **Connections** lists it, the tool that sent it, or for `t3 workflow signal` run by an agent, that agent's thread. What a signal's own value says for these is ignored; a signal sent before its question opens answers it as whoever sent it, at the time it was received. The run shows both on the question's step, and says **You** only in the session that gave the answer; every other session, even another one on the same device, sees that device's name. - -`tags([...])` labels a run for `t3 workflow list --tag backlog`, whether or not it waits on anyone. - -## What a run is about - -A run can name the one thing it is about with `subject(...)`: an issue or pull request a trigger or listing gave it, `{ threadId }`, or a web address. Calling it again replaces the subject, and `start(workflow, payload, { key, subject })` gives a new run one from the start. A project cannot be a subject, and an issue or pull request built by hand needs its `projectId` and `host`. - -```ts -const { workflow, subject, Issue } = T3; - -workflow("triage", { version: 1, payload: Issue }, (issue) => subject(issue)); -``` - -The run lists, **Needs you** included, show the subject under the run and open it beside the run. An issue's or pull request's own view lists the runs about it. `t3 workflow list --subject ` finds runs by their subject's web address, or by a thread id, and a step finds them with `runs({ subject })`. The subject is only a label with a link: nothing watches it. - -## Limit how much runs at once - -Wrap part of a run in a named pool to cap how many runs are inside it at once, across the whole server: - -```ts -const { within, agent } = T3; - -yield* within("builders", { limit: 4 }, agent("fix", { ... })); -``` +- `--key` deduplicates starts across retries and version bumps. +- `signal` answers an open question or wakes a channel wait (signals sent before a channel wait are buffered for 7 days by default). +- `withdraw` cancels an open question so `ask` returns `None`. +- `store` reads/writes shared state persisted between runs. -When all places are taken, later runs queue in the order they asked and show as **Queued** with their place in line; they count as running, not as needing you. A place is given back when the wrapped part ends, or when its run ends, is cancelled, or pauses. The place is handed on at once, so a step of a paused or cancelled run that is still finishing can overlap with the next run in. A resumed run goes ahead of the queue and takes back every place it held, in every pool, all at once; until they are all free it holds none of them and shows as **Queued**. +## Questions, tags, and subjects -`limit: 1` makes it a lock. When calls on the same pool name ask for different limits, a call goes in only while the pool holds fewer runs than its own limit and fewer than the smallest limit of those already inside, and nobody who asked after it goes in first. So a `limit: 1` call always runs alone, but it waits for whoever is inside to finish, two `limit: 2` calls included. +- **Question kinds & tags**: Declare `asks: { kindKey: "Label" }` in workflow options and pass `kind` to `ask(...)` to filter open questions under **Needs you** (and `t3 workflow questions --kind `). Use `tags([...])` to label runs for filtering. +- **Rich choices & links**: Pass `links: [{ label, url }]` and choice objects `{ value, description, requireReason }` to require an explanation before answering. Answers record `answeredAt` and `answeredBy`. +- **Subjects**: Call `subject(issueOrPrOrThreadOrUrl)` (or pass `{ subject }` to `start(...)`) to display and link the target item in run lists, issue/PR views, and `t3 workflow list --subject `. -A run can hold several places in one pool by calling `within` side by side, as in `Effect.all`. Calling `within` for a pool from inside that same pool pauses the run with an error, because it could end up waiting for itself; so does `within` on the workflow's own name when it has a `concurrency`. A run that `invoke`s another while holding a place the other needs can still wait forever, so keep `invoke` out of a lock the invoked workflow takes. Step names starting with `@pool:` are kept for the steps that queue; a step or wait of your own named that way pauses its run with an error. +## Concurrency limits -To cap whole runs, give the workflow `concurrency: 4` in its options: its runs share a pool named after the workflow, and each keeps its place until it ends, `onEnd` included. +- **Whole-workflow cap**: Set `concurrency: 4` in workflow options. +- **Step pools**: Wrap a section in `within("builders", { limit: 4 }, ...)` (`limit: 1` acts as a lock). Waiting runs show as **Queued** in FIFO order; resumed runs re-acquire their pools first. +- Avoid nesting `within` on the same pool name (or a workflow's own concurrency pool), and avoid holding a lock across `invoke` if the child needs the same pool. Step names starting with `@pool:` are reserved. ## Triggers -- **Schedules:** `every` runs on an interval, starting one interval after the workflow loads; `daily` runs at a local time of day (a time missed by more than 10 minutes while the server is down is skipped). -- **Webhooks:** `t3 workflow hooks` prints each hook's path; prepend your server's address. The path contains the hook's secret, so share it only with the sender. A sender's retry that repeats its delivery header (such as GitHub's `X-GitHub-Delivery`) starts no second run, and bodies over 1 MiB are refused. A hook starts at most 60 runs a minute; requests past that get `429` and can be sent again a minute later. Organization policies blocking webhook tasks block workflow webhooks too. -- **Issues and pull requests:** workflows can start on new issues or pull requests and read, comment on, or update them via **Settings → Source control & issues** — no webhook needed. T3 Code checks roughly once a minute, and only items opened after the workflow was first loaded start runs. - -## Follow runs in the app - -Open the Workflows page with **Open workflows** in the command palette of the web or desktop app; the entry shows once a connected server has workflows on. Filter by **Needs you**, **Running**, or **All** (skipped runs stay hidden unless toggled on), open child runs from their parent, and answer questions, resume paused runs, or cancel active runs (requires permission to operate threads). The issues and pull requests a run touched show as chips under its title and on the steps that touched them; a chip opens the item beside the run, in a tab next to any agent transcripts you opened. - -Top-level skipped runs, such as webhook deliveries a workflow chose to ignore, do not keep the payload they started with. Each workflow keeps its latest 500 of them and deletes older ones about an hour after they end; change the number in **Settings → Labs → Skipped runs kept** (0 keeps none), or set `"workflowSkippedRunsKept"` in `userdata/settings.json`. Runs that did anything else are never deleted. Once a skipped run is deleted, a start with its key or a webhook retry with its delivery header starts a new run. - -### Agent threads - -Each `agent` step runs in an ordinary thread, left out of thread lists (including `t3 thread list`). Open it from the run to watch it live, read its transcript, or send follow-up messages; the thread links back to the run. - -An `agent` step can launch a new thread with its own `workspace` (such as a worktree), `runtimeMode`, `interactionMode`, `title`, and typed `returns`, or continue an earlier step's thread. Runs can set their display name with `title(text)`. An `agent` step can also target a project on a [linked environment](remote-access.md#link-another-environment) (requires **Settings → Labs → Linked environments**); the run itself stays on the server that started it. - -### Failures, pause, and cancel - -A plain code step runs once unless it asks for retries. When a step fails, the run pauses there instead of losing earlier work: - -- **Code step failures** retry automatically after 5, 20, and 80 minutes by default, or immediately when you resume; only that step runs again. -- **Agent failures** — when an agent ran and gave up or timed out — pause and wait for you to resume rather than retrying automatically. An agent that could not be started at all, for example because its environment was offline, retries on its own like a failed step. +- **Schedules**: `every` runs on an interval; `daily` runs at a local time of day (skipped if missed by >10 minutes while offline). +- **Webhooks**: Run `t3 workflow hooks` to get each hook's secret path (prepend your server URL). Deduplicates retries by delivery header (e.g. `X-GitHub-Delivery`), rejects bodies >1 MiB, and rate-limits to 60 runs/min (`429`). Blocked if managed policy disables webhooks. +- **Issues & PRs**: Triggers automatically on new issues or PRs via **Settings → Source control & issues** (polled ~every minute; only items opened after the workflow first loads). -Cancelling a run stops its active agent turns and cancels child runs it invoked. A cancelled run cannot be resumed. +## Follow runs, agent threads, and failures -## Limits +Open **Open workflows** from the command palette (web/desktop) to filter **Needs you**, **Running**, or **All**, inspect agent threads, answer questions, resume, or cancel runs. -- Runs live on the server that started them and only advance while it is running; use an always-on machine for schedules or webhooks you cannot miss. -- Keep older workflow versions defined until their unfinished runs end or are cancelled. -- Signals sent to a `channel` before a run waits on it are kept for 7 days by default. +- **Agent steps**: Each `agent` step runs in a regular thread (hidden from sidebar lists) that you can open live from the run. Supports custom `workspace`, `runtimeMode`, `interactionMode`, `title`, typed `returns`, and [linked environments](./remote-access.md#link-another-environment). +- **Retries & pausing**: Failed code steps auto-retry after 5, 20, and 80 minutes (or immediately on **Resume**). Failed or timed-out agent steps pause for manual resume (offline-start failures auto-retry). Cancelling stops active agent turns and child runs permanently. +- **Skipped runs**: Up to 500 skipped top-level runs are kept per workflow (configurable via **Settings → Labs → Skipped runs kept** or `"workflowSkippedRunsKept"` in `settings.json`). +- **Always-on requirement**: Runs only advance while the server that started them is online. From f727a75b59b72f540b0fdf3726d440e9f237b45a Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 25 Nov 2026 18:09:33 -0800 Subject: [PATCH 177/238] fix(web): a draft moved to another machine takes that project's default workspace (#43205) --- .../components/chat/useComposerSelection.ts | 2 + ...seDraftEnvironmentRouting.browser.test.tsx | 43 ++++++++++++ .../chat/useDraftEnvironmentRouting.ts | 5 +- apps/web/src/composerDraftStore.test.ts | 14 ++++ apps/web/src/composerDraftStore.ts | 17 +++++ apps/web/src/hooks/useHandleNewThread.ts | 8 +++ apps/web/src/lib/retargetDraftWorkspace.ts | 68 +++++++++++++++++++ 7 files changed, 156 insertions(+), 1 deletion(-) create mode 100644 apps/web/src/lib/retargetDraftWorkspace.ts diff --git a/apps/web/src/components/chat/useComposerSelection.ts b/apps/web/src/components/chat/useComposerSelection.ts index cbcbb2a5c86fa..ff62eebe2b37b 100644 --- a/apps/web/src/components/chat/useComposerSelection.ts +++ b/apps/web/src/components/chat/useComposerSelection.ts @@ -251,6 +251,7 @@ export function useComposerSelection(input: ComposerSelectionInput) { if (isLocalDraftThread) { setDraftThreadContext(composerDraftTarget, { envMode: mode, + workspaceExplicit: true, startFromOrigin: resolveNewDraftStartFromOrigin({ envMode: mode, newWorktreesStartFromOrigin: activeProjectSettings.settings.newWorktreesStartFromOrigin, @@ -278,6 +279,7 @@ export function useComposerSelection(input: ComposerSelectionInput) { if (isLocalDraftThread) { setDraftThreadContext(composerDraftTarget, { startFromOrigin: nextStartFromOrigin, + workspaceExplicit: true, }); } }; diff --git a/apps/web/src/components/chat/useDraftEnvironmentRouting.browser.test.tsx b/apps/web/src/components/chat/useDraftEnvironmentRouting.browser.test.tsx index 1a6e2b038832c..c8b0632be428f 100644 --- a/apps/web/src/components/chat/useDraftEnvironmentRouting.browser.test.tsx +++ b/apps/web/src/components/chat/useDraftEnvironmentRouting.browser.test.tsx @@ -41,6 +41,7 @@ vi.mock("../../hooks/useLoadBalancedEnvironment", () => ({ })); vi.mock("../../state/entities", () => ({ useProjects: () => resources.projects, + readThreadShells: () => [], readProject: (ref: { environmentId: EnvironmentId; projectId: ProjectId }) => resources.projects.find( (project) => project.environmentId === ref.environmentId && project.id === ref.projectId, @@ -353,3 +354,45 @@ it.each([ expect(draft?.modelSelectionByProvider[codex]?.model).toBe(model); expect(draft?.modelSelectionExplicit === true).toBe(explicit); }); + +it("takes the destination's default workspace when the draft switches machine by hand", async () => { + const { b, draftId, input, store } = fanoutSetup(); + resources.projects = resources.projects.map((project) => + project.environmentId === b + ? { ...project, defaultThreadEnvMode: "worktree" as const } + : project, + ); + // The source's own default, never picked by the user. + store.setDraftThreadContext(draftId, { envMode: "local", startFromOrigin: false }); + await using screen = await render( + , + ); + await screen.getByRole("button", { name: `Switch to ${b}` }).click(); + await expect.element(screen.getByText(b)).toBeInTheDocument(); + expect(store.getDraftSession(draftId)?.envMode).toBe("worktree"); +}); + +it("keeps a workspace the user picked when the draft switches machine by hand", async () => { + const { b, draftId, input, store } = fanoutSetup(); + resources.projects = resources.projects.map((project) => + project.environmentId === b + ? { ...project, defaultThreadEnvMode: "worktree" as const } + : project, + ); + // Picked by hand, even though it is also the source's default. + store.setDraftThreadContext(draftId, { + envMode: "local", + startFromOrigin: false, + workspaceExplicit: true, + }); + await using screen = await render( + , + ); + await screen.getByRole("button", { name: `Switch to ${b}` }).click(); + await expect.element(screen.getByText(b)).toBeInTheDocument(); + expect(store.getDraftSession(draftId)?.envMode).toBe("local"); +}); diff --git a/apps/web/src/components/chat/useDraftEnvironmentRouting.ts b/apps/web/src/components/chat/useDraftEnvironmentRouting.ts index 87e62d24a134e..278ba7529a96a 100644 --- a/apps/web/src/components/chat/useDraftEnvironmentRouting.ts +++ b/apps/web/src/components/chat/useDraftEnvironmentRouting.ts @@ -38,6 +38,7 @@ import { useAtomCommand } from "../../state/use-atom-command"; import type { DraftSessionState } from "../../composerDraftStore"; import { loadBalancingSendWarning } from "./composerSend.logic"; import { appAtomRegistry } from "../../rpc/atomRegistry"; +import { retargetDraftWorkspace } from "../../lib/retargetDraftWorkspace"; import { seedDraftModelSelection } from "../../lib/seedDraftModelSelection"; import { draftFanoutSelectionsAtom } from "./chatViewSend"; @@ -331,18 +332,20 @@ export function useDraftEnvironmentRouting(input: DraftEnvironmentRoutingInput) } carryFanoutSelections(currentDraft, target.environmentId); const projectRef = scopeProjectRef(target.environmentId, project.id); + const workspace = retargetDraftWorkspace(currentDraft, projectRef); if (activeProjectIsScratch) { setLogicalProjectDraftThreadId( deriveLogicalProjectKeyFromSettings(project, projectGroupingSettings), projectRef, draftId, - { environmentSelection: "manual", loadBalancedEnvironmentId: null }, + { environmentSelection: "manual", loadBalancedEnvironmentId: null, ...workspace }, ); } else { setDraftThreadContext(draftId, { projectRef, environmentSelection: "manual", loadBalancedEnvironmentId: null, + ...workspace, }); } seedDraftModelSelection(draftId, projectRef); diff --git a/apps/web/src/composerDraftStore.test.ts b/apps/web/src/composerDraftStore.test.ts index c6942b7e01c88..f23a9b00e06d4 100644 --- a/apps/web/src/composerDraftStore.test.ts +++ b/apps/web/src/composerDraftStore.test.ts @@ -1229,6 +1229,20 @@ describe("composerDraftStore project draft thread mapping", () => { }); }); + it("keeps a picked workspace marked as picked when a draft moves environment", () => { + const store = useComposerDraftStore.getState(); + store.setProjectDraftThreadId(projectRef, draftId, { threadId, envMode: "local" }); + store.setDraftThreadContext(draftId, { envMode: "local", workspaceExplicit: true }); + + store.setDraftThreadContext(draftId, { projectRef: remoteProjectRef }); + + expect(useComposerDraftStore.getState().getDraftThread(draftId)).toMatchObject({ + environmentId: OTHER_TEST_ENVIRONMENT_ID, + envMode: "local", + workspaceExplicit: true, + }); + }); + it("clears stale upload metadata when retargeting a draft to another environment", () => { const store = useComposerDraftStore.getState(); const hydratedFile: ComposerFileAttachment = { diff --git a/apps/web/src/composerDraftStore.ts b/apps/web/src/composerDraftStore.ts index 07eca76db05f3..50c116b2f8056 100644 --- a/apps/web/src/composerDraftStore.ts +++ b/apps/web/src/composerDraftStore.ts @@ -417,6 +417,7 @@ const PersistedDraftThreadState = Schema.Struct({ worktreePath: Schema.NullOr(Schema.String), envMode: DraftThreadEnvModeSchema, startFromOrigin: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))), + workspaceExplicit: Schema.optionalKey(Schema.Boolean), checkoutPullRequest: Schema.optionalKey( Schema.Struct({ url: Schema.String, branch: Schema.String }), ), @@ -517,6 +518,8 @@ export interface DraftSessionState { worktreePath: string | null; envMode: DraftThreadEnvMode; startFromOrigin: boolean; + /** The user chose the workspace; without it a draft moving machine takes the new project's default. */ + workspaceExplicit?: true; /** Linked to the thread when the draft is sent on this branch. */ checkoutPullRequest?: DraftCheckoutPullRequest; /** @@ -592,6 +595,7 @@ interface ComposerDraftStoreState { createdAt?: string; envMode?: DraftThreadEnvMode; startFromOrigin?: boolean; + workspaceExplicit?: boolean; runtimeMode?: RuntimeMode; interactionMode?: ProviderInteractionMode; environmentSelection?: "auto" | "manual"; @@ -609,6 +613,7 @@ interface ComposerDraftStoreState { createdAt?: string; envMode?: DraftThreadEnvMode; startFromOrigin?: boolean; + workspaceExplicit?: boolean; runtimeMode?: RuntimeMode; interactionMode?: ProviderInteractionMode; environmentSelection?: "auto" | "manual"; @@ -625,6 +630,7 @@ interface ComposerDraftStoreState { createdAt?: string; envMode?: DraftThreadEnvMode; startFromOrigin?: boolean; + workspaceExplicit?: boolean; runtimeMode?: RuntimeMode; interactionMode?: ProviderInteractionMode; environmentSelection?: "auto" | "manual"; @@ -1729,6 +1735,7 @@ function createDraftThreadState( createdAt?: string; envMode?: DraftThreadEnvMode; startFromOrigin?: boolean; + workspaceExplicit?: boolean; runtimeMode?: RuntimeMode; interactionMode?: ProviderInteractionMode; environmentSelection?: "auto" | "manual"; @@ -1787,6 +1794,9 @@ function createDraftThreadState( envMode: options?.envMode ?? (nextWorktreePath ? "worktree" : (existingThread?.envMode ?? "local")), startFromOrigin: nextStartFromOrigin, + ...((options?.workspaceExplicit ?? existingThread?.workspaceExplicit) + ? { workspaceExplicit: true as const } + : {}), ...(checkoutPullRequest ? { checkoutPullRequest } : {}), ...(!projectChanged && existingThread?.worktreeRepositories !== undefined ? { worktreeRepositories: existingThread.worktreeRepositories } @@ -1851,6 +1861,7 @@ function draftThreadsEqual(left: DraftThreadState | undefined, right: DraftThrea left.worktreePath === right.worktreePath && left.envMode === right.envMode && left.startFromOrigin === right.startFromOrigin && + left.workspaceExplicit === right.workspaceExplicit && checkoutPullRequestsEqual(left.checkoutPullRequest, right.checkoutPullRequest) && worktreeRepositoriesEqual(left.worktreeRepositories, right.worktreeRepositories) && scopedThreadRefsEqual(left.promotedTo, right.promotedTo) @@ -2015,6 +2026,7 @@ function normalizePersistedDraftThreads( worktreePath: normalizedWorktreePath, envMode: normalizeDraftThreadEnvMode(candidateDraftThread.envMode, normalizedWorktreePath), startFromOrigin, + ...(candidateDraftThread.workspaceExplicit === true ? { workspaceExplicit: true } : {}), ...(candidateDraftThread.environmentSelection === "manual" || candidateDraftThread.environmentSelection === "auto" ? { environmentSelection: candidateDraftThread.environmentSelection } @@ -2804,6 +2816,7 @@ function toHydratedDraftThreadState( worktreePath: persistedDraftThread.worktreePath, envMode: persistedDraftThread.envMode, startFromOrigin: persistedDraftThread.startFromOrigin, + ...(persistedDraftThread.workspaceExplicit ? { workspaceExplicit: true } : {}), ...(persistedDraftThread.environmentSelection ? { environmentSelection: persistedDraftThread.environmentSelection } : {}), @@ -3112,6 +3125,9 @@ const composerDraftStore = create()( envMode: options.envMode ?? (nextWorktreePath ? "worktree" : (existing.envMode ?? "local")), startFromOrigin: nextStartFromOrigin, + ...((options.workspaceExplicit ?? existing.workspaceExplicit) + ? { workspaceExplicit: true as const } + : {}), ...(checkoutPullRequest ? { checkoutPullRequest } : {}), ...(worktreeRepositories ? { worktreeRepositories } : {}), promotedTo: existing.promotedTo ?? null, @@ -3129,6 +3145,7 @@ const composerDraftStore = create()( nextDraftThread.worktreePath === existing.worktreePath && nextDraftThread.envMode === existing.envMode && nextDraftThread.startFromOrigin === existing.startFromOrigin && + nextDraftThread.workspaceExplicit === existing.workspaceExplicit && checkoutPullRequestsEqual( nextDraftThread.checkoutPullRequest, existing.checkoutPullRequest, diff --git a/apps/web/src/hooks/useHandleNewThread.ts b/apps/web/src/hooks/useHandleNewThread.ts index ea9c42b2649b5..1fd3dad3478fc 100644 --- a/apps/web/src/hooks/useHandleNewThread.ts +++ b/apps/web/src/hooks/useHandleNewThread.ts @@ -110,6 +110,7 @@ interface NewThreadWorkspaceOptions { worktreePath?: string | null; envMode?: DraftThreadEnvMode; startFromOrigin?: boolean; + workspaceExplicit?: boolean; } function pickExplicitWorkspaceOptions(options: NewThreadWorkspaceOptions | undefined) { @@ -118,6 +119,9 @@ function pickExplicitWorkspaceOptions(options: NewThreadWorkspaceOptions | undef ...(options?.worktreePath !== undefined ? { worktreePath: options.worktreePath } : {}), ...(options?.envMode !== undefined ? { envMode: options.envMode } : {}), ...(options?.startFromOrigin !== undefined ? { startFromOrigin: options.startFromOrigin } : {}), + ...(options?.envMode !== undefined || options?.startFromOrigin !== undefined + ? { workspaceExplicit: true } + : {}), }; } @@ -356,6 +360,7 @@ export function createNewThreadHandler(router: AnyRouter) { worktreePath: null, envMode: defaultEnvMode.envMode, startFromOrigin: startFromOriginFor(defaultEnvMode.envMode), + workspaceExplicit: false, }; } if (workspaceContext) { @@ -454,6 +459,9 @@ export function createNewThreadHandler(router: AnyRouter) { worktreePath: options?.worktreePath ?? null, envMode: initialEnvMode, startFromOrigin: options?.startFromOrigin ?? startFromOriginFor(initialEnvMode), + ...(options?.envMode !== undefined || options?.startFromOrigin !== undefined + ? { workspaceExplicit: true } + : {}), runtimeMode: defaultRuntimeMode, ...(carryInteractionMode ? { interactionMode: carryInteractionMode } : {}), }); diff --git a/apps/web/src/lib/retargetDraftWorkspace.ts b/apps/web/src/lib/retargetDraftWorkspace.ts new file mode 100644 index 0000000000000..c91aebfb954d9 --- /dev/null +++ b/apps/web/src/lib/retargetDraftWorkspace.ts @@ -0,0 +1,68 @@ +import { DEFAULT_SERVER_SETTINGS, type ScopedProjectRef } from "@t3tools/contracts"; +import { resolveNewThreadEnvMode, resolveProjectSettings } from "@t3tools/shared/projectSettings"; + +import type { DraftSessionState } from "../composerDraftStore"; +import { appAtomRegistry } from "../rpc/atomRegistry"; +import { readProject, readThreadShells } from "../state/entities"; +import { readEnvironment } from "../state/environments"; +import { readUnloadedThreadCount } from "../state/olderSettledShelf"; +import { environmentSummaries } from "../state/presentation"; +import { resolveNewDraftStartFromOrigin } from "./chatThreadActions"; +import { peekT3ProjectFile } from "./t3ProjectFileDefaults"; + +function newThreadWorkspace(projectRef: ScopedProjectRef) { + const project = readProject(projectRef); + const serverConfig = readEnvironment(projectRef.environmentId)?.serverConfig; + const settings = serverConfig?.settings ?? DEFAULT_SERVER_SETTINGS; + const consultProjectFile = + project !== null && + resolveProjectSettings(settings, projectRef.projectId, project).settings + .defaultThreadEnvMode === null && + appAtomRegistry + .get(environmentSummaries.connectedEnvironmentIdsAtom) + .includes(projectRef.environmentId); + const projectFile = consultProjectFile + ? (peekT3ProjectFile(projectRef.environmentId, project.workspaceRoot) ?? null) + : null; + const projectSettings = resolveProjectSettings( + settings, + projectRef.projectId, + project, + projectFile, + ); + const envMode = resolveNewThreadEnvMode({ + projectSettings, + workspaceRoot: project?.workspaceRoot ?? null, + newProjectsRoot: serverConfig?.newProjectsRoot, + projectHasThreads: + readThreadShells().some( + (thread) => + thread.environmentId === projectRef.environmentId && + thread.projectId === projectRef.projectId, + ) || + readUnloadedThreadCount( + [{ environmentId: projectRef.environmentId, id: projectRef.projectId }], + [], + ) > 0, + }); + return { + envMode, + startFromOrigin: resolveNewDraftStartFromOrigin({ + envMode, + newWorktreesStartFromOrigin: projectSettings.settings.newWorktreesStartFromOrigin, + }), + }; +} + +/** + * The workspace for a draft moving to another project or machine: the default a new thread + * there starts with, unless the user chose one, which carries over. + */ +export function retargetDraftWorkspace( + draft: Pick, + projectRef: ScopedProjectRef, +): { envMode?: DraftSessionState["envMode"]; startFromOrigin?: boolean } { + return draft.workspaceExplicit || draft.worktreePath !== null + ? {} + : newThreadWorkspace(projectRef); +} From 4c8a324e8fec28fe5f2c34a8a3551078d5aa5dc6 Mon Sep 17 00:00:00 2001 From: Alex Southwell Date: Thu, 26 Nov 2026 13:11:28 +1100 Subject: [PATCH 178/238] fix(shared): file links with escaped quotes in titles keep their folder labels (#43194) Co-authored-by: SAPHID Co-authored-by: Julius Marminge --- packages/shared/src/markdownLinks.test.ts | 3 +++ packages/shared/src/markdownLinks.ts | 9 ++++++--- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/packages/shared/src/markdownLinks.test.ts b/packages/shared/src/markdownLinks.test.ts index 35084dc7d9229..ea49dbc1d9f0e 100644 --- a/packages/shared/src/markdownLinks.test.ts +++ b/packages/shared/src/markdownLinks.test.ts @@ -207,6 +207,9 @@ describe("extractMarkdownLinkHrefs", () => { ], ['[a](/tmp/a(1).txt "title") after', ["/tmp/a(1).txt"]], [`[a](a.ts "it's a title") [b](b.ts 'a "quoted" title') [c](ok)`, ["a.ts", "b.ts", "ok"]], + [`[a.ts](src/a.ts "say \\"hello\\"") [a.ts](lib/a.ts)`, ["src/a.ts", "lib/a.ts"]], + [`[a](a.ts 'it\\'s') [b](b.ts "ends in \\\\") [c](ok)`, ["a.ts", "b.ts", "ok"]], + [`[a](a.ts "unclosed \\") [b](b.ts)`, ["b.ts"]], [`[a](a.ts "mixed') [b](b.ts)`, ["b.ts"]], [`[a](a.ts "it's\n\n[b](lib/a.ts)")`, ["lib/a.ts"]], ["[a](a(b(c))d) [b](ok)", ["a(b(c))d", "ok"]], diff --git a/packages/shared/src/markdownLinks.ts b/packages/shared/src/markdownLinks.ts index 5dd6e999e45ec..1538ab815513c 100644 --- a/packages/shared/src/markdownLinks.ts +++ b/packages/shared/src/markdownLinks.ts @@ -455,7 +455,9 @@ function markdownRunEndFinder(markdown: string, delimiter: RegExp) { if (start >= runStart && start <= runEnd) return runEnd; delimiter.lastIndex = start; runStart = start; - runEnd = delimiter.exec(markdown)?.index ?? markdown.length; + let match = delimiter.exec(markdown); + while (match?.[0].length === 2 && match[0][0] === "\\") match = delimiter.exec(markdown); + runEnd = match?.index ?? markdown.length; return runEnd; }; } @@ -463,8 +465,9 @@ function markdownRunEndFinder(markdown: string, delimiter: RegExp) { function markdownLinkTailScanner(markdown: string) { // A blank line ends the paragraph, so no part of a link's tail runs past one. const whitespaceEnd = markdownRunEndFinder(markdown, /\S|\n[ \t\r]*\n/g); - const doubleQuoteEnd = markdownRunEndFinder(markdown, /"|\n[ \t\r]*\n/g); - const singleQuoteEnd = markdownRunEndFinder(markdown, /'|\n[ \t\r]*\n/g); + // Escape pairs (`\"`, `\\`) match so the finder can skip them. + const doubleQuoteEnd = markdownRunEndFinder(markdown, /\\[\\"]|"|\n[ \t\r]*\n/g); + const singleQuoteEnd = markdownRunEndFinder(markdown, /\\[\\']|'|\n[ \t\r]*\n/g); const titleWhitespaceEnd = markdownRunEndFinder(markdown, /\S|\n[ \t\r]*\n/g); return (start: number) => { const end = whitespaceEnd(start); From 72559e12fac21bbec022f0e64429809eb8ed2cdf Mon Sep 17 00:00:00 2001 From: Victor Date: Wed, 25 Nov 2026 20:30:13 -0600 Subject: [PATCH 179/238] fix(web): cut failure messages and review findings no longer end in a space before the ellipsis (#43195) Co-authored-by: Julius Marminge --- .../pullRequest/pullRequestDetail.logic.test.ts | 9 +++++++++ .../components/pullRequest/pullRequestDetail.logic.ts | 4 ++-- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/apps/web/src/components/pullRequest/pullRequestDetail.logic.test.ts b/apps/web/src/components/pullRequest/pullRequestDetail.logic.test.ts index 60af609c22128..b3dc5b1fa75ba 100644 --- a/apps/web/src/components/pullRequest/pullRequestDetail.logic.test.ts +++ b/apps/web/src/components/pullRequest/pullRequestDetail.logic.test.ts @@ -789,6 +789,12 @@ describe("fix findings handoff", () => { checks: [], }); expect(emojiAtCut.reviewComments[1]?.text).toBe(`reviewer: ${"x".repeat(986)}...`); + const spaceAtCut = buildFixFindingsHandoff({ + ...base, + reviewThreads: [thread(`${"x".repeat(986)} and more of the review.${"y".repeat(100)}`)], + checks: [], + }); + expect(spaceAtCut.reviewComments[1]?.text).toBe(`reviewer: ${"x".repeat(986)}...`); }); it("keeps the newest threads and the failing checks when it has to cut", () => { @@ -1001,6 +1007,9 @@ describe("what to say when an action fails", () => { expect(checkoutFailureDescription(diagnostic(`${"x".repeat(318)}😀 tail`))).toBe( `${"x".repeat(318)}…`, ); + expect(checkoutFailureDescription(diagnostic(`${"x".repeat(318)} tail`))).toBe( + `${"x".repeat(318)}…`, + ); for (const failure of [undefined, diagnostic(""), diagnostic("exited with code 1")]) { expect(checkoutFailureDescription(failure)).toBe( "Check that the branch still exists and is not checked out elsewhere, then try again.", diff --git a/apps/web/src/components/pullRequest/pullRequestDetail.logic.ts b/apps/web/src/components/pullRequest/pullRequestDetail.logic.ts index 32fa21526f701..90c4e09bb53c9 100644 --- a/apps/web/src/components/pullRequest/pullRequestDetail.logic.ts +++ b/apps/web/src/components/pullRequest/pullRequestDetail.logic.ts @@ -930,7 +930,7 @@ function bounded(value: string): string { if (previous >= 0xd800 && previous <= 0xdbff && next >= 0xdc00 && next <= 0xdfff) { end -= 1; } - return `${trimmed.slice(0, end)}...`; + return `${trimmed.slice(0, end).trimEnd()}...`; } function boundedField(value: string): string { @@ -1573,7 +1573,7 @@ export function readableFailure(failure: unknown, hint: string): string { let end = FAILURE_DETAIL_MAX_LENGTH - 1; const last = detail.charCodeAt(end - 1); if (last >= 0xd800 && last <= 0xdbff) end -= 1; - return `${detail.slice(0, end)}…`; + return `${detail.slice(0, end).trimEnd()}…`; } const isGitCommandError = Schema.is(GitCommandError); From d846efc14357bc78a59e4190a52d7772e934937c Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 25 Nov 2026 18:49:26 -0800 Subject: [PATCH 180/238] fix(web): sidebar linked-item hover cards show 8 items and open beside the row (#43222) --- .../src/components/ThreadStatusIndicators.tsx | 126 +++++++++++++----- .../components/sidebar/SidebarThreadRow.tsx | 10 +- apps/web/src/i18n/translations/de.json | 20 ++- apps/web/src/i18n/translations/en.json | 20 ++- apps/web/src/i18n/translations/es.json | 20 ++- apps/web/src/i18n/translations/fr.json | 20 ++- apps/web/src/i18n/translations/ja.json | 20 ++- apps/web/src/i18n/translations/ko.json | 20 ++- apps/web/src/i18n/translations/pt-BR.json | 20 ++- apps/web/src/i18n/translations/ru.json | 19 ++- apps/web/src/i18n/translations/sv.json | 20 ++- apps/web/src/i18n/translations/zh.json | 20 ++- 12 files changed, 292 insertions(+), 43 deletions(-) diff --git a/apps/web/src/components/ThreadStatusIndicators.tsx b/apps/web/src/components/ThreadStatusIndicators.tsx index dc8890f252d8a..e73f42bf47875 100644 --- a/apps/web/src/components/ThreadStatusIndicators.tsx +++ b/apps/web/src/components/ThreadStatusIndicators.tsx @@ -18,7 +18,7 @@ import { type ThreadPullRequestLink, type VcsStatusResult, } from "@t3tools/contracts"; -import { msg, T, useGT, useMessages } from "gt-react"; +import { msg, T, useGT, useMessages, Var } from "gt-react"; import { TerminalIcon } from "lucide-react"; import { m, type MessageResolver } from "../i18n/messages"; import { useEnvironment, usePrimaryEnvironmentId } from "../state/environments"; @@ -41,6 +41,7 @@ import { type ReactElement, } from "react"; import { cn } from "../lib/utils"; +import { Button } from "./ui/button"; import { revealThreadTerminal } from "../lib/revealThreadTerminal"; import { useEnvironmentQuery } from "../state/query"; @@ -408,6 +409,7 @@ export function ThreadPullRequestBadgeControl({ status, onOpenList, onOpenPullRequest, + side, }: { render: ReactElement<{ render?: useRender.RenderProp }>; badge: ThreadPullRequestBadge | null; @@ -417,6 +419,7 @@ export function ThreadPullRequestBadgeControl({ status: PrStatusIndicator | null; onOpenList: () => void; onOpenPullRequest: (event: MouseEvent, url?: string) => void; + side?: ThreadLinkBadgeSide | undefined; }) { const m = useMessages(); const presentation = resolveThreadPullRequestBadgePresentation({ badge, number, url, status }, m); @@ -432,6 +435,7 @@ export function ThreadPullRequestBadgeControl({ pullRequests={pullRequests} onOpenList={onOpenList} onOpenPullRequest={onOpenPullRequest} + side={side} /> ); } @@ -446,6 +450,7 @@ function PullRequestBadge({ pullRequests, onOpenList, onOpenPullRequest, + side, }: { render: ReactElement<{ render?: useRender.RenderProp }>; presentation: NonNullable>; @@ -456,6 +461,7 @@ function PullRequestBadge({ pullRequests: ReadonlyArray; onOpenList: () => void; onOpenPullRequest: (event: MouseEvent, url?: string) => void; + side: ThreadLinkBadgeSide | undefined; }) { const onClick = opensList ? (event: MouseEvent) => { @@ -485,11 +491,13 @@ function PullRequestBadge({ Icon={presentation.Icon} toneClassName={presentation.toneClassName} text={presentation.text} + side={side} > {visibleThreadPullRequests(pullRequests).length > 0 ? ( ) : number !== undefined && url !== undefined ? (