From 0aeb7921c2fb2f4e721735ed5b079fb75bce25b1 Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Mon, 23 Nov 2026 20:21:35 -0800 Subject: [PATCH 001/284] docs: clarify that MIT covers source code only and protect T3 Code branding (#41898) --- AGENTS.md | 2 +- CONTRIBUTING.md | 4 ++++ README.md | 19 ++++++++++++++++--- TRADEMARK.md | 38 ++++++++++++++++++++++++++++++++++++++ docs/README.md | 4 ++-- docs/user/faq.md | 8 ++++++-- 6 files changed, 67 insertions(+), 8 deletions(-) create mode 100644 TRADEMARK.md diff --git a/AGENTS.md b/AGENTS.md index 9340734f36500..a257e1a84a4f0 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -10,7 +10,7 @@ We have over 500,000 users who love T3 Code. It's important we maintain the thin ### 1. Open at the core -T3 Code is truly open. We share our roadmap, we share how we think about things, and of course we share all our code. A large number of our users run forks. We work in the open, and should strive to stay that way. +T3 Code is truly open. We share our roadmap, we share how we think about things, and of course we share all our code. A large number of our users run forks (our MIT license covers source code only, not T3 Code's trademarks or branding; see [TRADEMARK.md](TRADEMARK.md)). We work in the open, and should strive to stay that way. ### 2. Performance without compromise diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index b5445efd4d197..8780eda18a5d1 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -138,6 +138,10 @@ hours later. A reply or a push in that time sends it back for another look. After it is closed, fix the problem and comment on the PR, or open a focused replacement PR that links the old one. +## Forks and branding + +If you want changes outside our scope, you are welcome to fork the MIT-licensed source code. That license covers the source code only, not the **T3 Code** name, wordmark, logos, or branding. Any fork or derivative project must use its own branding and make it unmistakably clear that it is unofficial and not affiliated with T3 Tools, Inc. Using our name, wordmark, logo, or branding without making it unmistakably 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. Truthful, plain-text attribution is fine; see [TRADEMARK.md](./TRADEMARK.md). + ## Setup See the [development runbook](docs/operations/00_development.md#first-checkout). diff --git a/README.md b/README.md index 2ff0418fcd2e0..b3ad8bae49b70 100644 --- a/README.md +++ b/README.md @@ -35,7 +35,7 @@ It works with Claude Code, Codex, Cursor, OpenCode, Grok Build, Antigravity, Kir - **Remote ready.** Run agents on any machine. Connect over your local network, Tailscale, or [T3 Connect](./docs/user/remote-access.md). - **Git built in.** Each thread can work in its own worktree. Review the diff, then commit, push, and open a pull request with one button. - **Fast.** Performance is a feature here. We measure it, and we treat a dropped frame as a bug. -- **Open.** MIT licensed. If you don't like something, fork it. +- **Open.** Source code is MIT licensed. If you don't like something, fork it under your own branding (see [Trademarks and forks](#trademarks-and-forks)). ## Install @@ -81,7 +81,7 @@ T3 Code needs one agent that is installed and signed in. For example, install [C Nothing. We built T3 Code because we wanted the best possible development experience with agents. We were inspired by existing solutions like the Codex desktop app, Conductor, Claude Desktop and Cursor Glass, but none met our bar. -We wanted something performant, remote-ready, and truly open. If we ever go the wrong direction, we want you to have everything you need to fork and build the tool that you want. +We wanted something performant, remote-ready, and truly open. If we ever go the wrong direction, we want you to have everything you need to fork the source code and build the tool that you want, under your own name and branding. ## Documentation @@ -105,4 +105,17 @@ We have limited review capacity. Small, focused fixes are the most likely to be ## License -[MIT](./LICENSE) +The source code in this repository is licensed under the [MIT License](./LICENSE). + +## Trademarks and forks + +The MIT license applies **only to the source code**. It does not grant any rights to T3 Tools, Inc.'s trademarks, branding, or trade dress, including the **T3 Code** name, wordmark, logos, and application icons. + +If you fork, redistribute, or build on T3 Code's source code: + +- **Use your own branding.** Replace the T3 Code name, wordmark, logos, and application icons in any public fork, redistributed build, website, package, or app store listing. +- **Be explicitly clear that your project is unofficial.** Do not use the T3 Code name, wordmark, logo, or branding in your own projects without making it unmistakably clear that your project is unofficial and not affiliated with or endorsed by T3 Tools, Inc. + +Using our name, wordmark, logo, or branding in a way that suggests official status or affiliation is trademark infringement and unlawful. **Any project indicating or implying that it is an official version of T3 Code when it is not will be pursued to the full extent of the law.** + +See [TRADEMARK.md](./TRADEMARK.md) for the full trademark and branding policy. diff --git a/TRADEMARK.md b/TRADEMARK.md new file mode 100644 index 0000000000000..346822bdfbc6c --- /dev/null +++ b/TRADEMARK.md @@ -0,0 +1,38 @@ +# Trademark and Branding Policy + +The [MIT License](./LICENSE) in this repository applies **only to the source code**. It does not grant any rights to T3 Tools, Inc.'s trademarks, service marks, trade names, trade dress, or branding. + +## Protected marks and brand assets + +T3 Tools, Inc. owns the following marks and brand assets, whether registered or unregistered: + +- The names **T3 Code**, **T3 Connect**, and **T3 Tools** +- The **T3** wordmark, logos, application icons (including the brand assets in [`assets/`](./assets/) and `T3Wordmark`), and visual trade dress +- Official domains (`t3.codes`, `app.t3.codes`) and official package or app store listings + +## Forks and derivative projects + +You are welcome to fork, modify, self-host, and redistribute the MIT-licensed source code under the terms of the [MIT License](./LICENSE). However, if you publish or distribute a fork, custom build, website, package, app store listing, or derivative project: + +- **Use your own branding.** Remove and replace the T3 Code name, wordmark, logos, application icons, and other T3 branding with your own. +- **Make it unmistakably clear that your project is unofficial.** You may not use the T3 Code name, wordmark, logo, or other branding in your own projects without being explicitly and prominently clear that your project is unofficial and is not affiliated with, endorsed by, or maintained by T3 Tools, Inc. +- **Keep references strictly factual.** You may include a truthful, plain-text attribution statement noting that your project is derived from this repository (for example, "An unofficial fork based on the T3 Code source code"), provided you do not use T3 logos or wordmarks, do not adopt "T3 Code" as your project's name or domain, and prominently state that your project is unofficial. + +## Prohibited uses and enforcement + +Using the T3 Code name, wordmark, logo, icons, or branding in your own projects without being explicitly clear that they are unofficial, or in any way that suggests official status, sponsorship, or affiliation, is trademark infringement and unlawful. + +**Any project indicating or implying that it is an official version of T3 Code when it is not will be pursued to the full extent of the law.** T3 Tools, Inc. actively enforces its trademark rights, including through platform takedowns, domain disputes, and legal action. + +## Official channels + +The only official T3 Code websites and distributions are: + +- Websites: [t3.codes](https://t3.codes) and [app.t3.codes](https://app.t3.codes) +- Source repository and releases: [github.com/pingdotgg/t3code](https://github.com/pingdotgg/t3code) +- CLI package: [`t3` on npm](https://www.npmjs.com/package/t3) +- Mobile apps: [iOS App Store](https://apps.apple.com/us/app/t3-code-remote-claude-more/id6787819824) and [Google Play](https://play.google.com/store/apps/details?id=com.t3tools.t3code) + +## Contact + +For trademark permission requests or to report unauthorized use or impersonation, contact [legal@t3.tools](mailto:legal@t3.tools). diff --git a/docs/README.md b/docs/README.md index 622d31096da05..00e60de0e7063 100644 --- a/docs/README.md +++ b/docs/README.md @@ -35,8 +35,8 @@ ## Working on T3 Code -Start with the [development runbook](./operations/00_development.md) and -[contribution policy](../CONTRIBUTING.md). +Start with the [development runbook](./operations/00_development.md), +[contribution policy](../CONTRIBUTING.md), and [trademark policy](../TRADEMARK.md). Internal docs preserve architectural decisions, trust boundaries, conventions, and cross-cutting traps that the source alone does not explain. Most code changes do not need an internal diff --git a/docs/user/faq.md b/docs/user/faq.md index 947344894ff4e..d06a1ec43e049 100644 --- a/docs/user/faq.md +++ b/docs/user/faq.md @@ -15,7 +15,7 @@ We were inspired by the Codex desktop app, Conductor, Claude Desktop, and Cursor - 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. If we go the wrong direction, fork it. +- 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) @@ -25,7 +25,11 @@ Yes. ## How much does T3 Code cost? -Nothing. There's no way to pay us to use T3 Code. You bring your own sub. It 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 it, self host, or use Tailscale. [Install](./install.md) +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) + +## 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). ## Can I connect more than 3 machines with T3 Connect? From 9331811180910c38fffe2d28f4457b025aaef2f2 Mon Sep 17 00:00:00 2001 From: Yash Singh Date: Mon, 23 Nov 2026 22:21:42 -0600 Subject: [PATCH 002/284] fix(clients): threads can be dragged above threads from a disconnected machine (#41885) Co-authored-by: Julius Marminge --- .../home/useThreadListActions.test.ts | 65 ++++---- .../threads/thread-provider-instance.test.ts | 23 ++- .../src/features/threads/threadListV2.test.ts | 15 +- .../src/features/threads/threadOrder.ts | 23 ++- apps/web/src/components/Sidebar.logic.test.ts | 144 ++++++++++-------- apps/web/src/components/Sidebar.tsx | 17 ++- .../src/state/threadSort.test.ts | 18 +++ .../client-runtime/src/state/threadSort.ts | 53 ++++--- packages/shared/src/pinOrderKey.ts | 7 + 9 files changed, 231 insertions(+), 134 deletions(-) diff --git a/apps/mobile/src/features/home/useThreadListActions.test.ts b/apps/mobile/src/features/home/useThreadListActions.test.ts index 135cf4e1d85a7..fe02cc50a6fd2 100644 --- a/apps/mobile/src/features/home/useThreadListActions.test.ts +++ b/apps/mobile/src/features/home/useThreadListActions.test.ts @@ -351,37 +351,46 @@ describe("pinned thread operation permissions", () => { }); describe("thread reorder connection availability", () => { - it.each(["active", "pinned"] as const)( - "rejects %s materialization involving a cached capable offline neighbor", - async (section) => { - const moved = makeThread({ - pinnedAt: section === "pinned" ? "2026-09-02T00:00:00.000Z" : null, - }); - state.shells = [ - moved, - makeThread({ - id: ThreadId.make("offline-neighbor"), - environmentId: otherEnvironmentId, - createdAt: "2026-09-02T00:00:00.000Z", - pinnedAt: moved.pinnedAt, - }), - ]; - state.scopes.get(otherEnvironmentId)?.add(AuthOrchestrationOperateScope); - state.connectedEnvironmentIds = [primaryEnvironmentId]; + const offlineNeighborCase = (pinnedAt: string | null) => { + const moved = makeThread({ pinnedAt }); + state.shells = [ + moved, + makeThread({ + id: ThreadId.make("offline-neighbor"), + environmentId: otherEnvironmentId, + createdAt: "2026-09-02T00:00:00.000Z", + pinnedAt, + }), + ]; + state.scopes.get(otherEnvironmentId)?.add(AuthOrchestrationOperateScope); + state.connectedEnvironmentIds = [primaryEnvironmentId]; + return moved; + }; - const { moveThread } = useThreadListActions(); - expect(await moveThread(moved, "up")).toBe(false); - expect(state.requests).toEqual([]); + it("rejects pinned materialization involving a cached capable offline neighbor", async () => { + const moved = offlineNeighborCase("2026-09-02T00:00:00.000Z"); - state.connectedEnvironmentIds = [primaryEnvironmentId, otherEnvironmentId]; + const { moveThread } = useThreadListActions(); + expect(await moveThread(moved, "up")).toBe(false); + expect(state.requests).toEqual([]); - expect(await moveThread(moved, "up")).toBe(true); - expect(state.requests).toHaveLength(2); - expect(new Set(state.requests.map(({ environmentId }) => environmentId))).toEqual( - new Set([primaryEnvironmentId, otherEnvironmentId]), - ); - }, - ); + state.connectedEnvironmentIds = [primaryEnvironmentId, otherEnvironmentId]; + + expect(await moveThread(moved, "up")).toBe(true); + expect(state.requests).toHaveLength(2); + expect(new Set(state.requests.map(({ environmentId }) => environmentId))).toEqual( + new Set([primaryEnvironmentId, otherEnvironmentId]), + ); + }); + + it("moves an active thread past a cached offline neighbor by writing only itself", async () => { + const moved = offlineNeighborCase(null); + + expect(await useThreadListActions().moveThread(moved, "up")).toBe(true); + expect(state.requests).toEqual([ + expect.objectContaining({ action: "reorderActive", environmentId: primaryEnvironmentId }), + ]); + }); it.each(["active", "pinned"] as const)( "uses the latest connection state in a retained %s move callback", diff --git a/apps/mobile/src/features/threads/thread-provider-instance.test.ts b/apps/mobile/src/features/threads/thread-provider-instance.test.ts index 56ddec3ab1542..a8f8c7723356e 100644 --- a/apps/mobile/src/features/threads/thread-provider-instance.test.ts +++ b/apps/mobile/src/features/threads/thread-provider-instance.test.ts @@ -208,13 +208,22 @@ describe("thread list reorder availability", () => { : current.activeReorderEnvironmentIds, }; }; - expect(createThreadMovePlanner(plannerInput())(movedId, "down")).toHaveLength(2); + // Active rows sort by an implied key, so moving past an unarranged row writes only the mover. + const expectMoveDown = (neighborWritable: boolean) => { + const movable = section === "active" || neighborWritable; + expect(createThreadMovePlanner(plannerInput())(movedId, "down")?.length).toBe( + movable ? (section === "active" ? 1 : 2) : undefined, + ); + expect(computeThreadMoveAvailability(plannerInput()).get(movedId)?.canMoveDown).toBe( + movable, + ); + }; + expectMoveDown(true); const before = registry.get(environments); registry.set(connected, [onlineId]); - expect(createThreadMovePlanner(plannerInput())(movedId, "down")).toBeNull(); - expect(computeThreadMoveAvailability(plannerInput()).get(movedId)?.canMoveDown).toBe(false); + expectMoveDown(false); expect(registry.get(environments).pinningEnvironmentIds.has(offlineId)).toBe(true); expect(registry.get(environments).settlementEnvironmentIds.has(offlineId)).toBe(true); expect(registry.get(environments).providersByEnvironmentId.get(offlineId)).toBe( @@ -260,7 +269,7 @@ describe("thread list reorder availability", () => { ); expect(updated.pinReorderEnvironmentIds.has(offlineId)).toBe(false); expect(updated.activeReorderEnvironmentIds.has(offlineId)).toBe(false); - expect(createThreadMovePlanner(plannerInput())(movedId, "down")).toBeNull(); + expectMoveDown(false); registry.set( configs, @@ -284,16 +293,14 @@ describe("thread list reorder availability", () => { registry.set(connected, [onlineId, offlineId]); - expect(createThreadMovePlanner(plannerInput())(movedId, "down")).toHaveLength(2); - expect(computeThreadMoveAvailability(plannerInput()).get(movedId)?.canMoveDown).toBe(true); + expectMoveDown(true); expect(registry.get(environments).snoozePresetsByEnvironmentId.get(offlineId)).toBe( updated.snoozePresetsByEnvironmentId.get(offlineId), ); registry.set(configs, new Map([[onlineId, config]])); - expect(createThreadMovePlanner(plannerInput())(movedId, "down")).toBeNull(); - expect(computeThreadMoveAvailability(plannerInput()).get(movedId)?.canMoveDown).toBe(false); + expectMoveDown(false); } finally { registry.dispose(); } diff --git a/apps/mobile/src/features/threads/threadListV2.test.ts b/apps/mobile/src/features/threads/threadListV2.test.ts index 29f6e97b047b4..36f1005791401 100644 --- a/apps/mobile/src/features/threads/threadListV2.test.ts +++ b/apps/mobile/src/features/threads/threadListV2.test.ts @@ -1199,11 +1199,12 @@ describe("thread drag destinations", () => { assignments, }); expect(pending.orderedIds).toEqual([ids[3], ids[0], ids[1], ids[2]]); + const field = section === "pinned" ? "pinOrderKey" : "activeOrderKey"; const confirmed = ordered.map((row) => ({ ...row, - [section === "pinned" ? "pinOrderKey" : "activeOrderKey"]: assignments.find( - (a) => a.id === `${row.environmentId}:${row.id}`, - )!.orderKey, + [field]: + assignments.find((a) => a.id === `${row.environmentId}:${row.id}`)?.orderKey ?? + row[field], })); expect( getThreadListV2OrderedSection({ threads: confirmed, section, now: NOW }).map( @@ -1216,7 +1217,7 @@ describe("thread drag destinations", () => { }, ); - it("refuses a drop that would need to rewrite an old server's keyless row", () => { + it("moves past an old server's keyless row by writing only the moved row", () => { const old = EnvironmentId.make("old-server"); const ordered = [environmentId, old, environmentId].map((env, index) => makeThread({ @@ -1231,11 +1232,11 @@ describe("thread drag destinations", () => { section: "active", reorderableEnvironmentIds: new Set([environmentId]), })(`${environmentId}:2`, { targetId: `${environmentId}:0`, placement: "before" }), - ).toBeNull(); + ).toEqual([{ id: `${environmentId}:2`, orderKey: expect.any(String) }]); }); }); -it("allows a long drop past an old server even when both adjacent moves fail", () => { +it("moves past an old server one step or in a long drop", () => { const old = EnvironmentId.make("old-server"); const ordered = [ makeThread({ id: ThreadId.make("a"), title: "a" }), @@ -1250,7 +1251,7 @@ it("allows a long drop past an old server even when both adjacent moves fail", ( }); const movedId = `${environmentId}:a`; expect(planner(movedId, "up")).toBeNull(); - expect(planner(movedId, "down")).toBeNull(); + expect(planner(movedId, "down")?.map(({ id }) => id)).toEqual([movedId]); const assignments = planner(movedId, { targetId: `${environmentId}:d`, placement: "after" }); expect(assignments).toHaveLength(1); expect(assignments![0]!.id).toBe(movedId); diff --git a/apps/mobile/src/features/threads/threadOrder.ts b/apps/mobile/src/features/threads/threadOrder.ts index f7654e910f3dd..ed5f87ef8ab90 100644 --- a/apps/mobile/src/features/threads/threadOrder.ts +++ b/apps/mobile/src/features/threads/threadOrder.ts @@ -1,5 +1,6 @@ import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell"; import { + activeThreadSortKey, generateSpreadPinOrderKeys, pinOrderKeyBetween, planPinnedReorder, @@ -72,9 +73,13 @@ function rowId(row: OrderRow): string { return `${row.environmentId}:${row.id}`; } +function storedKey(row: OrderRow, section: PendingThreadOrder["section"]) { + return (section === "pinned" ? row.pinOrderKey : row.activeOrderKey) ?? null; +} + function rowOrder(row: OrderRow, section: PendingThreadOrder["section"]) { return { - key: (section === "pinned" ? row.pinOrderKey : row.activeOrderKey) ?? null, + key: section === "pinned" ? storedKey(row, section) : activeThreadSortKey(row), anchor: section === "pinned" ? (row.pinnedAt ?? "") : (row.unsettledAt ?? row.createdAt), }; } @@ -86,12 +91,13 @@ export function createThreadMovePlanner(input: { readonly reorderableEnvironmentIds: ReadonlySet; }) { const orderedIds = input.ordered.map(rowId); - const keysById = new Map( - (input.allThreads ?? input.ordered).map((row) => [ - rowId(row), - rowOrder(row, input.section).key, - ]), - ); + // Hidden rows keep their stored key: only stored keys can collide with a write. + const keysById = new Map([ + ...(input.allThreads ?? input.ordered).map( + (row) => [rowId(row), storedKey(row, input.section)] as const, + ), + ...input.ordered.map((row) => [rowId(row), rowOrder(row, input.section).key] as const), + ]); const writableIds = new Set( (input.allThreads ?? input.ordered) .filter((row) => input.reorderableEnvironmentIds.has(row.environmentId)) @@ -141,9 +147,10 @@ export function computeThreadMoveAvailability(input: { const writableIds = new Set(); for (const row of input.allThreads ?? input.ordered) { const id = rowId(row); - keysById.set(id, rowOrder(row, input.section).key); + keysById.set(id, storedKey(row, input.section)); if (input.reorderableEnvironmentIds.has(row.environmentId)) writableIds.add(id); } + for (const row of rows) keysById.set(rowId(row), rowOrder(row, input.section).key); const reservedKeys = new Set(); keysById.forEach((key, id) => { if (key != null && !indexById.has(id)) reservedKeys.add(key); diff --git a/apps/web/src/components/Sidebar.logic.test.ts b/apps/web/src/components/Sidebar.logic.test.ts index a17427fcdb54e..685d865c4e9ad 100644 --- a/apps/web/src/components/Sidebar.logic.test.ts +++ b/apps/web/src/components/Sidebar.logic.test.ts @@ -43,6 +43,7 @@ import { } from "./Sidebar.logic"; import { scopeThreadRef, scopedThreadKey } from "@t3tools/client-runtime/environment"; import { + activeThreadSortKey, sortActiveThreadsByOrderKey, sortPinnedThreadsByOrderKey, } from "@t3tools/client-runtime/state/thread-sort"; @@ -1335,7 +1336,12 @@ describe("Working shelf (beta)", () => { : sortPinnedThreadsByOrderKey(rows); const originalOrder = sort(input.rows).map(keyOf); const targetOrder = input.order.map(keyOf); - const keysById = new Map(input.rows.map((entry) => [keyOf(entry), entry.activeOrderKey])); + const keysById = new Map( + input.rows.map((entry) => [ + keyOf(entry), + input.section === "active" ? activeThreadSortKey(entry) : entry.pinOrderKey, + ]), + ); const plan = planSidebarThreadDrop({ activeKey: keyOf(input.moved), activeSection: input.from ?? input.section, @@ -1420,38 +1426,52 @@ describe("Working shelf (beta)", () => { expect(result.actualOrder).toEqual(result.targetOrder); }); - it.each(["active", "pinned"] as const)( - "rejects rebalancing a keyed offline bound in %s", - (section) => { - const bound = thread("offline", offlineEnvironmentId, "m"); - const neighbor = thread("neighbor"); - const result = planDrop({ - section, - rows: [bound, online, neighbor], - moved: online, - order: [bound, neighbor, online], - }); + it("rejects rebalancing a keyed offline bound in pinned", () => { + const bound = thread("offline", offlineEnvironmentId, "m"); + const neighbor = thread("neighbor"); + const result = planDrop({ + section: "pinned", + rows: [bound, online, neighbor], + moved: online, + order: [bound, neighbor, online], + }); - expect(result.plan).toEqual({ kind: "none" }); - expect(result.assignments).toEqual([]); - }, - ); + expect(result.plan).toEqual({ kind: "none" }); + expect(result.assignments).toEqual([]); + }); - it.each(["active", "pinned"] as const)( - "rejects crossing the frozen keyless boundary in %s", - (section) => { - const bound = { - ...offline, - createdAt: - section === "active" ? "2026-03-09T12:00:00.000Z" : "2026-03-09T10:00:00.000Z", - }; - const order = section === "active" ? [online, bound] : [bound, online]; - const result = planDrop({ section, rows: [bound, online], moved: online, order }); - - expect(result.plan).toEqual({ kind: "none" }); - expect(result.assignments).toEqual([]); - }, - ); + it("rejects crossing the frozen keyless boundary in pinned", () => { + const bound = { ...offline, createdAt: "2026-03-09T10:00:00.000Z" }; + const result = planDrop({ + section: "pinned", + rows: [bound, online], + moved: online, + order: [bound, online], + }); + + expect(result.plan).toEqual({ kind: "none" }); + expect(result.assignments).toEqual([]); + }); + + it.each([ + ["an unarranged", null], + ["an arranged", "m"], + ] as const)("moves %s thread anywhere around an offline one in active", (_, key) => { + const neighbor = thread("neighbor"); + const moved = { + ...thread("moved", onlineEnvironmentId, key), + createdAt: "2026-03-09T09:00:00.000Z", + }; + const rows = [offline, neighbor, moved]; + for (const order of [ + [moved, offline, neighbor], + [offline, moved, neighbor], + ]) { + const result = planDrop({ section: "active", rows, moved, order }); + expect(result.assignments.map(({ id }) => id)).toEqual([keyOf(moved)]); + expect(result.actualOrder).toEqual(result.targetOrder); + } + }); it.each(["active", "pinned"] as const)( "allows realizable moves beside a frozen keyless row in %s", @@ -1473,38 +1493,42 @@ describe("Working shelf (beta)", () => { }, ); - it.each(["active", "pinned"] as const)( - "checks fallback assignments to other rows at the %s boundary", - (section) => { - const neighbor = thread("neighbor"); - const order = - section === "active" ? [neighbor, offline, online] : [online, offline, neighbor]; - const result = planDrop({ - section, - rows: [offline, online, neighbor], - moved: online, - order, - }); + it("checks fallback assignments to other rows at the pinned boundary", () => { + const neighbor = thread("neighbor"); + const result = planDrop({ + section: "pinned", + rows: [offline, online, neighbor], + moved: online, + order: [online, offline, neighbor], + }); - expect(result.plan).toEqual({ kind: "none" }); - }, - ); + expect(result.plan).toEqual({ kind: "none" }); + }); - it.each(["active", "pinned"] as const)( - "rejects impossible pin/unpin placement across the %s boundary", - (section) => { - const order = section === "active" ? [online, offline] : [offline, online]; - const result = planDrop({ - section, - rows: [offline, online], - moved: online, - order, - from: section === "active" ? "pinned" : "active", - }); + it("rejects impossible pin placement across the pinned boundary", () => { + const result = planDrop({ + section: "pinned", + rows: [offline, online], + moved: online, + order: [offline, online], + from: "active", + }); - expect(result.plan).toEqual({ kind: "none" }); - }, - ); + expect(result.plan).toEqual({ kind: "none" }); + }); + + it("unpins a thread above an offline one in active", () => { + const result = planDrop({ + section: "active", + rows: [offline, online], + moved: online, + order: [online, offline], + from: "pinned", + }); + + expect(result.assignments.map(({ id }) => id)).toEqual([keyOf(online)]); + expect(result.actualOrder).toEqual(result.targetOrder); + }); }); it("only changes lifecycle when the inbox is time-ordered", () => { diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 59fcb56bfce9d..8d308d501dad3 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -37,7 +37,7 @@ import { createInboxReturnTracker, isThreadWorking, } from "@t3tools/client-runtime/state/thread-inbox"; -import { sortSettledThreads } from "@t3tools/client-runtime/state/thread-sort"; +import { activeThreadSortKey, sortSettledThreads } from "@t3tools/client-runtime/state/thread-sort"; import { nextShownOrder, threadSearchMatchKey, @@ -624,9 +624,12 @@ function useSidebarThreads(input: { pinnedKeysById: new Map( threads.map((thread) => [threadShellKey(thread), thread.pinOrderKey ?? null] as const), ), - activeKeysById: new Map( - threads.map((thread) => [threadShellKey(thread), thread.activeOrderKey ?? null] as const), - ), + activeKeysById: new Map([ + ...threads.map((thread) => [threadShellKey(thread), thread.activeOrderKey ?? null] as const), + ...activeThreads.map( + (thread) => [threadShellKey(thread), activeThreadSortKey(thread)] as const, + ), + ]), }; } @@ -2196,7 +2199,11 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve plan.kind === "settle" || (plan.kind === "move-active" && plan.unsnooze), order: plan.kind === "settle" ? null : plan.order, - keysAtDrop: target.section === "active" ? activeKeysById : pinnedKeysById, + // Stored keys, not sort keys: an unpinned row gaining its implied key is not a foreign write. + keysAtDrop: + target.section === "active" + ? new Map([...threadByKey].map(([key, thread]) => [key, thread.activeOrderKey ?? null])) + : pinnedKeysById, assignedKeys: new Map(assignments.map(({ id, orderKey }) => [id, orderKey])), }; setOptimisticDrop(drop); diff --git a/packages/client-runtime/src/state/threadSort.test.ts b/packages/client-runtime/src/state/threadSort.test.ts index 3ac982044b5bb..f2ed7fdb1bdc9 100644 --- a/packages/client-runtime/src/state/threadSort.test.ts +++ b/packages/client-runtime/src/state/threadSort.test.ts @@ -2,6 +2,7 @@ import { RunId } from "@t3tools/contracts"; import { describe, expect, it } from "vite-plus/test"; import { + activeThreadSortKey, generateSpreadPinOrderKeys, pinOrderKeyBetween, planPinnedReorder, @@ -286,6 +287,23 @@ describe("sortActiveThreadsByOrderKey", () => { ]); }); + it("places an arranged thread between unarranged ones without arranging them", () => { + const newer = { id: "newer", createdAt: "2026-03-09T12:00:00.000Z" }; + const older = { id: "older", createdAt: "2026-03-09T10:00:00.000Z", unsettledAt: null }; + const arranged = { + id: "arranged", + createdAt: "2026-03-01T09:00:00.000Z", + activeOrderKey: pinOrderKeyBetween(activeThreadSortKey(newer), activeThreadSortKey(older)), + }; + const brandNew = { id: "brand-new", createdAt: "2026-03-10T09:00:00.000Z" }; + const saved = { id: "saved", createdAt: "2026-03-11T09:00:00.000Z", activeOrderKey: "b" }; + expect( + sortActiveThreadsByOrderKey([saved, older, arranged, newer, brandNew]).map( + (thread) => thread.id, + ), + ).toEqual(["brand-new", "newer", "arranged", "older", "saved"]); + }); + it("breaks equal order keys and timestamps by thread then environment", () => { for (const activeOrderKey of [null, "m"]) { const threads = [ diff --git a/packages/client-runtime/src/state/threadSort.ts b/packages/client-runtime/src/state/threadSort.ts index 3d0ebe16d75e8..a10c870e71422 100644 --- a/packages/client-runtime/src/state/threadSort.ts +++ b/packages/client-runtime/src/state/threadSort.ts @@ -1,6 +1,10 @@ import type { ProjectId } from "@t3tools/contracts"; import type { SidebarProjectSortOrder, SidebarThreadSortOrder } from "@t3tools/contracts/settings"; -import { generateSpreadPinOrderKeys, pinOrderKeyBetween } from "@t3tools/shared/pinOrderKey"; +import { + generateSpreadPinOrderKeys, + LEADING_ORDER_TIER, + pinOrderKeyBetween, +} from "@t3tools/shared/pinOrderKey"; import type { EnvironmentThreadShell } from "./models.ts"; export { generateSpreadPinOrderKeys, pinOrderKeyBetween } from "@t3tools/shared/pinOrderKey"; @@ -251,6 +255,32 @@ export function sortPinnedThreadsByOrderKey< return [...keyed, ...keyless]; } +const IMPLIED_KEY_WIDTH = 10; +const IMPLIED_KEY_MAX_MS = 26 ** IMPLIED_KEY_WIDTH - 1; + +/** + * Sort key for the Active section. A thread nobody arranged takes an implied key from its + * anchor time, newest first, in a tier ahead of every arranged key. A move then only writes + * the moved thread, even beside threads whose server is offline. + */ +export function activeThreadSortKey(thread: { + readonly createdAt: string; + readonly unsettledAt?: string | null | undefined; + readonly activeOrderKey?: string | null | undefined; +}): string { + if (thread.activeOrderKey != null) return thread.activeOrderKey; + let value = + IMPLIED_KEY_MAX_MS - + Math.min(Math.max(activeThreadAnchorTimestampMs(thread), 0), IMPLIED_KEY_MAX_MS); + let digits = ""; + for (let index = 0; index < IMPLIED_KEY_WIDTH; index += 1) { + digits = String.fromCharCode(97 + (value % 26)) + digits; + value = Math.floor(value / 26); + } + // A trailing "a" leaves no room to place a thread directly above this one. + return `${LEADING_ORDER_TIER}${digits}n`; +} + export function sortActiveThreadsByOrderKey< T extends { readonly id: string; @@ -261,25 +291,12 @@ export function sortActiveThreadsByOrderKey< }, >(threads: readonly T[]): T[] { if (threads.length < 2) return [...threads]; - const timestamps = new Map(); - for (const thread of threads) { - if (thread.activeOrderKey == null) { - timestamps.set(thread, activeThreadAnchorTimestampMs(thread)); - } - } + const keys = new Map(threads.map((thread) => [thread, activeThreadSortKey(thread)])); return [...threads].sort((left, right) => { - const leftKey = left.activeOrderKey; - const rightKey = right.activeOrderKey; - if (leftKey == null && rightKey != null) return -1; - if (leftKey != null && rightKey == null) return 1; - let order = 0; - if (leftKey != null && rightKey != null) { - order = leftKey < rightKey ? -1 : leftKey > rightKey ? 1 : 0; - } else { - order = timestamps.get(right)! - timestamps.get(left)!; - } + const leftKey = keys.get(left)!; + const rightKey = keys.get(right)!; return ( - order || + (leftKey < rightKey ? -1 : leftKey > rightKey ? 1 : 0) || left.id.localeCompare(right.id) || (left.environmentId ?? "").localeCompare(right.environmentId ?? "") ); diff --git a/packages/shared/src/pinOrderKey.ts b/packages/shared/src/pinOrderKey.ts index f1867e6fb8f4d..1f51f3418d0ae 100644 --- a/packages/shared/src/pinOrderKey.ts +++ b/packages/shared/src/pinOrderKey.ts @@ -4,8 +4,11 @@ * so the server places an agent-issued pin the same way a client pin is placed. */ const PIN_ORDER_DIGITS = "abcdefghijklmnopqrstuvwxyz"; +/** Prefix of a tier that sorts before every plain key (see `activeThreadSortKey`). */ +export const LEADING_ORDER_TIER = "0"; function isValidPinOrderKey(key: string): boolean { + if (key.startsWith(LEADING_ORDER_TIER)) key = key.slice(LEADING_ORDER_TIER.length); if (key.length === 0) return false; for (const char of key) { if (!PIN_ORDER_DIGITS.includes(char)) return false; @@ -43,6 +46,10 @@ export function pinOrderKeyBetween(before: string | null, after: string | null): if (a !== "" && !isValidPinOrderKey(a)) return null; if (b !== "" && !isValidPinOrderKey(b)) return null; if (b !== "" && a >= b) return null; + const tier = LEADING_ORDER_TIER; + if (b.startsWith(tier)) + return tier + pinOrderMidpoint(a.slice(tier.length), b.slice(tier.length)); + if (a.startsWith(tier)) return tier + pinOrderMidpoint(a.slice(tier.length), ""); return pinOrderMidpoint(a, b); } From ac3af66f2110cc53734d8d6a8f37744b50b24a80 Mon Sep 17 00:00:00 2001 From: tiliakoos <73005126+tiliakoos@users.noreply.github.com> Date: Tue, 24 Nov 2026 05:37:04 +0100 Subject: [PATCH 003/284] fix(web): a copied issue or pull request error no longer ends in a broken character (#41901) Co-authored-by: Julius Marminge --- .../pullRequest/pullRequestDetail.logic.test.ts | 3 +++ .../components/pullRequest/pullRequestDetail.logic.ts | 10 +++++----- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/apps/web/src/components/pullRequest/pullRequestDetail.logic.test.ts b/apps/web/src/components/pullRequest/pullRequestDetail.logic.test.ts index a71bc0d2db367..4fd39e8169bda 100644 --- a/apps/web/src/components/pullRequest/pullRequestDetail.logic.test.ts +++ b/apps/web/src/components/pullRequest/pullRequestDetail.logic.test.ts @@ -989,6 +989,9 @@ describe("what to say when an action fails", () => { const reason = "The worktree directory already exists. Choose another directory."; expect(checkoutFailureDescription(diagnostic(reason))).toBe(reason); expect(checkoutFailureDescription(diagnostic("x".repeat(900)))).toBe(`${"x".repeat(319)}…`); + 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 ad9285f6fc322..e69fd93773e89 100644 --- a/apps/web/src/components/pullRequest/pullRequestDetail.logic.ts +++ b/apps/web/src/components/pullRequest/pullRequestDetail.logic.ts @@ -1569,11 +1569,11 @@ export function readableFailure(failure: unknown, hint: string): string { failure instanceof Error ? failure.message : typeof failure === "string" ? failure : ""; const detail = raw.replace(OPERATION_PREFIX, "").trim(); if (detail.length === 0 || TOOL_NOISE.some((pattern) => pattern.test(detail))) return hint; - const bounded = - detail.length <= FAILURE_DETAIL_MAX_LENGTH - ? detail - : `${detail.slice(0, FAILURE_DETAIL_MAX_LENGTH - 1)}…`; - return bounded; + if (detail.length <= FAILURE_DETAIL_MAX_LENGTH) return detail; + 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)}…`; } const isGitCommandError = Schema.is(GitCommandError); From 28d67191144e931c49c72f6da3f7c4b38c35648e Mon Sep 17 00:00:00 2001 From: hj-smith Date: Tue, 24 Nov 2026 12:38:37 +0800 Subject: [PATCH 004/284] fix(server): ending a Claude CLI on Windows also ends the shells it started (#41857) Co-authored-by: hj-smith Co-authored-by: Julius Marminge --- apps/server/src/process/SpawnWorker.test.ts | 30 +++++++++++++++++++++ apps/server/src/process/SpawnWorker.ts | 14 +++++++--- 2 files changed, 40 insertions(+), 4 deletions(-) diff --git a/apps/server/src/process/SpawnWorker.test.ts b/apps/server/src/process/SpawnWorker.test.ts index 9c88d4f586c4b..97fca54f915bd 100644 --- a/apps/server/src/process/SpawnWorker.test.ts +++ b/apps/server/src/process/SpawnWorker.test.ts @@ -199,6 +199,36 @@ describe("SpawnWorker", () => { }); const exited = new Promise((resolve) => direct.once("exit", () => resolve(direct.killed))); expect(yield* Effect.promise(() => exited)).toBe(true); + // Windows has no process groups. Node ends a non-detached grandchild with its parent, but a + // detached one, like a CLI's background shell, outlives it unless the kill ends the tree. + if (HostProcess.Platform.defaultValue() === "win32") { + const cli = SpawnWorker.spawnPiped( + process.execPath, + [ + "-e", + "const c=require('child_process').spawn(process.execPath,['-e','setInterval(()=>{},1e3)'],{detached:true,stdio:'ignore'});process.stdout.write(String(c.pid));process.stdin.resume()", + ], + {}, + ); + const grandchild = yield* Effect.promise( + () => + new Promise((resolve) => + cli.stdout.once("data", (pid) => resolve(Number(String(pid)))), + ), + ); + const cliExited = new Promise((resolve) => cli.once("exit", resolve)); + cli.kill(); + yield* Effect.promise(() => cliExited); + const survived = (() => { + try { + return process.kill(grandchild, 0); + } catch { + return false; + } + })(); + if (survived) process.kill(grandchild); + expect(survived).toBe(false); + } }).pipe(Effect.scoped, Effect.provide(layer)), ); }); diff --git a/apps/server/src/process/SpawnWorker.ts b/apps/server/src/process/SpawnWorker.ts index 58373b5bdc0a8..b4d867bd80c0a 100644 --- a/apps/server/src/process/SpawnWorker.ts +++ b/apps/server/src/process/SpawnWorker.ts @@ -182,6 +182,7 @@ class WorkerChild killed = false; spawned = false; exited = false; + killsTree = false; readonly #writes = new Map void>>(); readonly #finals = new Map void>(); readonly #paused = new Set(); @@ -269,7 +270,8 @@ class WorkerChild kill(signal: NodeJS.Signals | number = "SIGTERM"): boolean { if (this.exited) return false; this.killed = true; - this.worker.post({ type: "kill", id: this.id, signal }); + if (this.killsTree && this.pid !== undefined) this.worker.pool.killTree(this.pid, () => {}); + else this.worker.post({ type: "kill", id: this.id, signal }); return true; } @@ -542,15 +544,19 @@ export const spawnPiped = ( command: string, args: ReadonlyArray, options: Omit, -) => - (sharedPool ??= new SpawnWorkerPool("win32")).spawn(command, args, { +) => { + const child = (sharedPool ??= new SpawnWorkerPool("win32")).spawn(command, args, { ...options, stdio: ["pipe", "pipe", "pipe"], - }) as WorkerChild & { + }); + // Windows has no process groups: ending only the CLI leaves its background shells running. + child.killsTree = true; + return child as WorkerChild & { readonly stdin: NodeStream.Writable; readonly stdout: NodeStream.Readable; readonly stderr: NodeStream.Readable; }; +}; export const layer = Layer.unwrap( Effect.gen(function* () { From ccf6ef5501ceb45f630a9cb4635b5c0051a71cf7 Mon Sep 17 00:00:00 2001 From: 4Fe_Andy <127666127+zs-andy@users.noreply.github.com> Date: Tue, 24 Nov 2026 12:39:43 +0800 Subject: [PATCH 005/284] fix(server): parent stop skips already-idle delegated child threads (#41860) Co-authored-by: Julius Marminge --- .../ThreadManagementService.ts | 101 ++++++++++++++-- .../src/orchestration-v2/ThreadStop.test.ts | 113 ++++++++++++++++++ 2 files changed, 205 insertions(+), 9 deletions(-) diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.ts b/apps/server/src/orchestration-v2/ThreadManagementService.ts index dfddf29474b6b..0c8879cfe18a5 100644 --- a/apps/server/src/orchestration-v2/ThreadManagementService.ts +++ b/apps/server/src/orchestration-v2/ThreadManagementService.ts @@ -14,6 +14,7 @@ import { CommandId, isDelegatedAppThread, isListedThreadLineage, + isOrchestrationV2WorkActive, MessageId, OrchestrationV2StopWorkflowError, type OrchestrationV2StopWorkflowInput, @@ -44,6 +45,7 @@ import { type TurnItemId, } from "@t3tools/contracts"; import { delegatedTaskProgress } from "@t3tools/provider-core/server/subagentProjection"; +import { derivePendingBackgroundWork } from "@t3tools/shared/orchestrationV2PendingBackgroundWork"; import { threadTranscriptHeader } from "@t3tools/shared/threadTranscript"; import { AgentScope } from "@t3tools/shared/AgentScope"; import * as Clock from "effect/Clock"; @@ -1740,6 +1742,58 @@ const make = Effect.gen(function* () { return { matched, unmatched: input.taskIds.filter((taskId) => !matchedIds.has(taskId)) }; }); + // Mirrors what Orchestrator's thread.stop would change; a clause missing here leaves that work running. + const childNeedsStop = ( + child: ProjectionRecords<"runs" | "providerThreads" | "turnItems" | "subagents">, + ): boolean => { + if (child.thread.deletedAt !== null) return false; + const latestRun = child.runs.findLast((run) => run.status !== "queued"); + const hasStoppableRun = child.runs.some( + (run) => + run.status === "preparing" || + run.status === "starting" || + run.status === "running" || + run.status === "queued" || + run.delegatedCompletion?.delivery != null, + ); + const hasPendingRecovery = + latestRun !== undefined && + (latestRun.status === "cancelled" || + (latestRun.status === "failed" && + (latestRun.restartContinuationOfRunId !== undefined || + child.thread.limitRecovery?.runId !== latestRun.id || + child.thread.limitRecovery.autoResume !== false))); + const hasPendingSubagent = child.subagents.some( + (task) => + (task.origin === "provider_native" && + task.runId !== null && + isOrchestrationV2WorkActive(task.status)) || + (task.origin === "app_owned" && + (isOrchestrationV2WorkActive(task.status) || + (task.runId !== null && + task.completionDelivery?.state !== "acknowledged" && + task.completionDelivery?.state !== "delivered" && + task.completionDelivery?.state !== "disposed"))), + ); + return ( + hasStoppableRun || + hasPendingRecovery || + child.thread.limitRecovery?.autoResume === true || + (child.thread.pullRequests ?? []).some((link) => link.watch !== undefined) || + derivePendingBackgroundWork({ + latestRun, + providerThreads: child.providerThreads, + turnItems: child.turnItems, + activeProviderThreadId: child.thread.activeProviderThreadId, + runs: child.runs, + }).length > 0 || + child.turnItems.some( + (item) => item.type === "link_request" && item.linkStatus === "pending", + ) || + hasPendingSubagent + ); + }; + const stopDelegatedTasks: ThreadManagementServiceShape["stopDelegatedTasks"] = Effect.fn( "ThreadManagementService.stopDelegatedTasks", )(function* (input) { @@ -1747,6 +1801,15 @@ const make = Effect.gen(function* () { const failures: Array< Orchestrator.OrchestratorV2Error | ThreadManagementProviderInstanceDisabledError > = []; + const activeChildThreadIds = new Set( + subagents.flatMap((task) => + task.origin === "app_owned" && + task.childThreadId !== null && + isOrchestrationV2WorkActive(task.status) + ? [task.childThreadId] + : [], + ), + ); const stoppedChildThreadIds = new Set(); for (const task of subagents) { if (task.origin !== "app_owned") continue; @@ -1789,16 +1852,36 @@ const make = Effect.gen(function* () { // Follow-up tasks reuse a child thread; walk its subtree only once. if (stoppedChildThreadIds.has(threadId)) continue; stoppedChildThreadIds.add(threadId); - yield* dispatch({ - type: "thread.stop", - commandId: CommandId.make(`${input.commandId}:stop:${threadId}`), - threadId, - stopDelegatedTasks: false, - ...(input.reason === undefined ? {} : { reason: input.reason }), + yield* Effect.gen(function* () { + let shouldStop = activeChildThreadIds.has(threadId); + let hasAppOwnedChildren = true; + if (!shouldStop) { + const child = yield* orchestrator.getThreadRecords( + threadId, + ["runs", "providerThreads", "turnItems", "subagents"], + { + turnItemTypes: ["command_execution", "dynamic_tool", "subagent", "link_request"], + turnItemStatuses: ["pending", "running", "waiting"], + }, + ); + shouldStop = childNeedsStop(child); + hasAppOwnedChildren = child.subagents.some( + (childTask) => childTask.origin === "app_owned", + ); + } + if (shouldStop) { + yield* dispatch({ + type: "thread.stop", + commandId: CommandId.make(`${input.commandId}:stop:${threadId}`), + threadId, + stopDelegatedTasks: false, + ...(input.reason === undefined ? {} : { reason: input.reason }), + }); + } + if (hasAppOwnedChildren) { + yield* stopDelegatedTasks({ threadId, commandId: input.commandId, reason: input.reason }); + } }).pipe( - Effect.andThen( - stopDelegatedTasks({ threadId, commandId: input.commandId, reason: input.reason }), - ), Effect.catch((error) => Effect.logWarning("Unable to stop a delegated task", { parentThreadId: input.threadId, diff --git a/apps/server/src/orchestration-v2/ThreadStop.test.ts b/apps/server/src/orchestration-v2/ThreadStop.test.ts index fc52191d32b29..2ba9e343956ac 100644 --- a/apps/server/src/orchestration-v2/ThreadStop.test.ts +++ b/apps/server/src/orchestration-v2/ThreadStop.test.ts @@ -611,6 +611,119 @@ it.effect.each(["run.interrupt", "thread.stop"] as const)( }).pipe(Effect.provide(layerTest)), ); +it.effect( + "stopDelegatedTasks skips idle completed children while still stopping active follow-ups and grandchildren", + () => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const projections = yield* ProjectionStore.ProjectionStoreV2; + const threads = yield* ThreadManagementService.ThreadManagementService; + const parentThreadId = ThreadId.make("thread:stop-skip-idle-parent"); + yield* createWatchingThread(parentThreadId, 30); + yield* send(parentThreadId, "parent", "start_immediately"); + const idleChildId = yield* delegate(parentThreadId, "idle completed child"); + const intermediateChildId = yield* delegate( + parentThreadId, + "completed child with active grandchild", + ); + const activeGrandchildId = yield* delegate(intermediateChildId, "running grandchild"); + const followupChildId = yield* delegate(parentThreadId, "completed child with follow-up"); + + const now = yield* DateTime.now; + const completeThreadRun = (threadId: ThreadId, eventPrefix: string) => + Effect.gen(function* () { + const run = (yield* orchestrator.getThreadProjection(threadId)).runs[0]!; + yield* projections.apply({ + id: EventId.make(`event:${eventPrefix}:run-completed`), + type: "run.updated", + threadId, + runId: run.id, + occurredAt: now, + payload: { ...run, status: "completed", startedAt: now, completedAt: now }, + }); + }); + + yield* completeThreadRun(idleChildId, "stop-skip-idle:leaf"); + yield* completeThreadRun(intermediateChildId, "stop-skip-idle:intermediate"); + yield* completeThreadRun(followupChildId, "stop-skip-idle:followup"); + + const parentSubagents = (yield* orchestrator.getThreadProjection(parentThreadId)).subagents; + for (const task of parentSubagents) { + yield* projections.apply({ + id: EventId.make(`event:stop-skip-idle:task:${task.id}`), + type: "subagent.updated", + threadId: parentThreadId, + runId: task.runId!, + nodeId: task.id, + providerInstanceId: instanceId, + occurredAt: now, + payload: { + ...task, + status: "completed", + result: "done", + completedAt: now, + completionDelivery: { state: "acknowledged", observedByRunId: null }, + }, + }); + } + + // Mark the intermediate child's task for its grandchild completed too, while leaving the + // grandchild's own run active, so recursion must still inspect descendants. + const intermediateBefore = yield* orchestrator.getThreadProjection(intermediateChildId); + const intermediateTask = intermediateBefore.subagents[0]!; + const intermediateTaskItem = intermediateBefore.turnItems.find( + (item) => item.type === "subagent" && item.subagentId === intermediateTask.id, + )!; + yield* projections.apply({ + id: EventId.make("event:stop-skip-idle:grandchild-task"), + type: "subagent.updated", + threadId: intermediateChildId, + runId: intermediateTask.runId!, + nodeId: intermediateTask.id, + providerInstanceId: instanceId, + occurredAt: now, + payload: { + ...intermediateTask, + status: "completed", + result: "done", + completedAt: now, + completionDelivery: { state: "acknowledged", observedByRunId: null }, + }, + }); + yield* projections.apply({ + id: EventId.make("event:stop-skip-idle:grandchild-task-item"), + type: "turn-item.updated", + threadId: intermediateChildId, + runId: intermediateTask.runId!, + nodeId: intermediateTask.id, + providerInstanceId: instanceId, + occurredAt: now, + payload: { ...intermediateTaskItem, status: "completed", completedAt: now, updatedAt: now }, + }); + + // Start a new follow-up turn directly on the third child after its original task completed. + yield* send(followupChildId, "follow-up work", "start_immediately"); + + yield* threads.stopDelegatedTasks({ + threadId: parentThreadId, + commandId: CommandId.make("stop-skip-idle"), + }); + + const idleProjection = yield* orchestrator.getThreadProjection(idleChildId); + assert.isEmpty( + idleProjection.turnItems.filter((item) => item.type === "run_interrupt_request"), + ); + assert.isFalse((yield* projections.getThreadShell(idleChildId))?.latestRunStopRequested); + + const intermediateProjection = yield* orchestrator.getThreadProjection(intermediateChildId); + assert.isEmpty( + intermediateProjection.turnItems.filter((item) => item.type === "run_interrupt_request"), + ); + assert.deepEqual((yield* threadState(activeGrandchildId)).runs, ["interrupted"]); + assert.deepEqual((yield* threadState(followupChildId)).runs, ["completed", "interrupted"]); + }).pipe(Effect.provide(layerTest)), +); + it.effect("a repeated Stop that changes nothing still stops the delegated tasks", () => Effect.gen(function* () { const orchestrator = yield* Orchestrator.OrchestratorV2; From a4029d4b91f5a22c6195d99b315fbab8802201c2 Mon Sep 17 00:00:00 2001 From: Victor Date: Mon, 23 Nov 2026 22:50:07 -0600 Subject: [PATCH 006/284] fix(web): an IME Escape no longer dismisses the citation highlight (#41899) Co-authored-by: Julius Marminge --- .../chat/MessagesTimeline.browser.test.tsx | 31 +++++++++++++++++++ .../chat/useAssistantCitationTarget.ts | 1 + 2 files changed, 32 insertions(+) diff --git a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx index a38a51feab4c7..222f498e7123a 100644 --- a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx @@ -1403,6 +1403,37 @@ describe("MessagesTimeline citations", () => { }); }); + it("keeps the citation highlight through an IME Escape", async () => { + await using _screen = await renderTimeline( + [ + message("A question", {}, "question"), + message("the cited answer", { role: "assistant" }, "cited"), + ], + { citationRequest: CITATION_REQUEST, citationHistory: { _tag: "found" } }, + ); + const highlighted = () => document.querySelector("[data-citation-highlighted]"); + await vi.waitFor(() => expect(highlighted()).not.toBeNull()); + const pressEscape = (init: KeyboardEventInit, prevented = false) => + act(() => { + const event = new KeyboardEvent("keydown", { + key: "Escape", + ...init, + bubbles: true, + cancelable: true, + }); + // The composer's editor prevents every plain Escape before it reaches the document. + if (prevented) event.preventDefault(); + document.body.dispatchEvent(event); + }); + + for (const init of [{ isComposing: true }, { keyCode: 229 }]) { + await pressEscape(init); + expect(highlighted()).not.toBeNull(); + } + await pressEscape({ keyCode: 27 }, true); + expect(highlighted()).toBeNull(); + }); + it("opens the superseded attempt that folds the cited response", async () => { const runId = RunId.make("run-steered"); const attempt = (id: string, ordinal: number, status: "superseded" | "running") => ({ diff --git a/apps/web/src/components/chat/useAssistantCitationTarget.ts b/apps/web/src/components/chat/useAssistantCitationTarget.ts index e8dd083e62463..3c3e39b9b6dc9 100644 --- a/apps/web/src/components/chat/useAssistantCitationTarget.ts +++ b/apps/web/src/components/chat/useAssistantCitationTarget.ts @@ -89,6 +89,7 @@ export function useAssistantCitationTarget({ setSettlement({ target, dismissed: true }); }; const onKeyDown = (event: KeyboardEvent) => { + if (event.isComposing || event.keyCode === 229) return; if (event.key === "Escape") { dismiss(false); } else if ( From 3c3246e8ce0304c9d2eb28cacb9fe2fab97297c6 Mon Sep 17 00:00:00 2001 From: tiliakoos <73005126+tiliakoos@users.noreply.github.com> Date: Tue, 24 Nov 2026 05:50:19 +0100 Subject: [PATCH 007/284] fix(server): title regeneration failures no longer end in a broken character (#41903) Co-authored-by: Julius Marminge --- .../ThreadTitleRegenerationService.test.ts | 36 ++++++++++ .../ThreadTitleRegenerationService.ts | 8 ++- ...itle-failure-keeps-whole-characters.e2e.ts | 70 +++++++++++++++++++ 3 files changed, 111 insertions(+), 3 deletions(-) create mode 100644 scripts/scenarios/title-failure-keeps-whole-characters.e2e.ts diff --git a/apps/server/src/orchestration-v2/ThreadTitleRegenerationService.test.ts b/apps/server/src/orchestration-v2/ThreadTitleRegenerationService.test.ts index 1d39000ed3a9f..1958ebe88d1ae 100644 --- a/apps/server/src/orchestration-v2/ThreadTitleRegenerationService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadTitleRegenerationService.test.ts @@ -944,6 +944,42 @@ describe("ThreadTitleRegenerationService", () => { }), ); + it.effect("cuts a long failure message without splitting an emoji", () => + Effect.gen(function* () { + const harness = makeHarness({ + generateTitle: () => + Effect.fail( + new TextGenerationError({ + operation: "generateThreadTitle", + detail: `${"a".repeat(298)}🚀 and the rest of the error`, + }), + ), + }); + yield* Effect.gen(function* () { + const threads = yield* ThreadManagement.ThreadManagementService; + const titleRegeneration = yield* ThreadTitleRegeneration.ThreadTitleRegenerationService; + const threadId = yield* createThread({ + command: "command:title:long-failure:create", + thread: "thread:title:long-failure", + }); + yield* dispatchUserMessage({ + command: "command:title:long-failure:message", + threadId, + text: "Some conversation", + }); + const requestId = yield* armRegeneration({ + command: "command:title:long-failure:1", + threadId, + }); + + yield* titleRegeneration.execute({ threadId, requestId, kind: { type: "regenerate" } }); + + const projection = yield* threads.getThreadProjection(threadId); + assert.equal(projection.thread.lastTitleRegeneration?.message, `${"a".repeat(298)}…`); + }).pipe(Effect.provide(harness.layer)); + }), + ); + it.effect("records an unchanged outcome when the model keeps the current title", () => Effect.gen(function* () { const harness = makeHarness({ diff --git a/apps/server/src/orchestration-v2/ThreadTitleRegenerationService.ts b/apps/server/src/orchestration-v2/ThreadTitleRegenerationService.ts index 725a15aa136e0..136e0c7b8bf1d 100644 --- a/apps/server/src/orchestration-v2/ThreadTitleRegenerationService.ts +++ b/apps/server/src/orchestration-v2/ThreadTitleRegenerationService.ts @@ -69,9 +69,11 @@ function failureMessage(cause: Cause.Cause): string { : []; const detail = lines.at(-1); if (detail === undefined) return "Title generation failed."; - return detail.length > MAX_FAILURE_MESSAGE_LENGTH - ? `${detail.slice(0, MAX_FAILURE_MESSAGE_LENGTH - 1)}…` - : detail; + if (detail.length <= MAX_FAILURE_MESSAGE_LENGTH) return detail; + const keep = MAX_FAILURE_MESSAGE_LENGTH - 1; + const last = detail.charCodeAt(keep - 1); + const end = keep - (last >= 0xd800 && last <= 0xdbff ? 1 : 0); + return `${detail.slice(0, end)}…`; } const make = Effect.gen(function* () { diff --git a/scripts/scenarios/title-failure-keeps-whole-characters.e2e.ts b/scripts/scenarios/title-failure-keeps-whole-characters.e2e.ts new file mode 100644 index 0000000000000..4b2eeab3cbd47 --- /dev/null +++ b/scripts/scenarios/title-failure-keeps-whole-characters.e2e.ts @@ -0,0 +1,70 @@ +import { expect } from "e2e"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Path from "effect/Path"; + +import { T3_HOME } from "../e2e.config.ts"; +import { runPromise, test, WEB } from "./t3.ts"; + +const PREFIX = "Codex CLI command failed: "; +const KEPT = `${PREFIX}${"The title model refused this request. ".repeat(10)}`.slice(0, 298); +// The emoji's two UTF-16 units straddle unit 299, where the server cuts the failure message. +const FAKE_CODEX = `#!/bin/sh +printf '%s\\n' '${KEPT.slice(PREFIX.length)}😀 and the rest of the error' >&2 +exit 1 +`; + +test( + "A long title regeneration failure ends without a broken character", + WEB, + async ({ t3, app, browser, screen }) => { + const { fakeCodex, settingsPath, originalSettings } = await runPromise( + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + return { + fakeCodex: path.join(T3_HOME, "bin/fake-codex"), + settingsPath: path.join(T3_HOME, "userdata/settings.json"), + originalSettings: yield* fs.readFileString(path.join(T3_HOME, "userdata/settings.json")), + }; + }), + ); + const settings = JSON.parse(originalSettings); + settings.providerInstances.codex = { + driver: "codex", + enabled: true, + config: { binaryPath: fakeCodex }, + }; + const nextSettings = JSON.stringify(settings); + try { + await runPromise( + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + yield* fs.writeFileString(fakeCodex, FAKE_CODEX); + yield* fs.chmod(fakeCodex, 0o755); + yield* fs.writeFileString(settingsPath, nextSettings); + }), + ); + + const project = await t3.project("demo"); + const thread = await t3.thread({ project, title: "Earlier work", messages: ["first"] }); + await t3.open(thread); + + await screen.getByRole("button", "Thread actions for Earlier work").tap(); + await screen.getByRole("menuitem", "Regenerate title").tap(); + await expect(screen.getByText("Failed to regenerate thread title")).toBeVisible(); + // Read the toast once: it closes by itself, and its four-line clamp hides the cut. + const message = await browser.locator('[data-slot="toast-description"]').textContent(); + await app.screenshot("regenerate-failed"); + expect(message).toBe(`${KEPT}…`); + } finally { + await runPromise( + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + yield* fs.writeFileString(settingsPath, originalSettings); + yield* fs.remove(fakeCodex, { force: true }); + }), + ); + } + }, +); From 2c3d3b4501349f28c3d71b52af8c62baa0969847 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 20:52:17 -0800 Subject: [PATCH 008/284] fix(server): settle on merge no longer cancels a wake queued behind a finished turn (#29934) --- .../src/orchestration-v2/Orchestrator.ts | 18 +++ .../ThreadSettlementService.ts | 3 +- .../src/orchestration-v2/runtimeLayer.test.ts | 113 ++++++++++++++++++ 3 files changed, 132 insertions(+), 2 deletions(-) diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index f459d6c3d6642..93693cc55fca4 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -785,6 +785,8 @@ function delegatedTasksStopEffect(command: { } const WORKSPACE_PREPARATION_INPUT = "Preparing workspace"; +/** How long automatic settlement waits for a queued turn to start. */ +export const QUEUED_TURN_START_GRACE_MS = 2 * 60 * 1_000; const RUNTIME_REQUEST_DELIVERY_FAILED_MESSAGE = "T3 Code could not confirm that your answer reached the agent. If the run stays stuck, stop it and try again."; @@ -16022,6 +16024,22 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio cause: `Thread ${command.threadId} changed before automatic settlement.`, }); } + // The completion reaction starts or holds the queue just after a run ends; settling + // first would cancel an automatic wake it was about to start. + const { runs } = yield* loadProjectionForCommand(command, ["runs"]); + const endedAt = latestExecutedRun(runs)?.completedAt; + if ( + endedAt != null && + runs.some((run) => run.status === "queued") && + Math.abs(DateTime.toEpochMillis(yield* DateTime.now) - DateTime.toEpochMillis(endedAt)) < + QUEUED_TURN_START_GRACE_MS + ) { + return yield* new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: `Thread ${command.threadId} has a queued run that may still start.`, + }); + } yield* dispatchThreadMutation( { type: "thread.settle", diff --git a/apps/server/src/orchestration-v2/ThreadSettlementService.ts b/apps/server/src/orchestration-v2/ThreadSettlementService.ts index 5b1f615c708cf..0a4cb5e9c1ec7 100644 --- a/apps/server/src/orchestration-v2/ThreadSettlementService.ts +++ b/apps/server/src/orchestration-v2/ThreadSettlementService.ts @@ -53,7 +53,6 @@ export interface SettlementPullRequest { } const DAY_MS = 24 * 60 * 60 * 1_000; -const QUEUED_TURN_START_GRACE_MS = 2 * 60 * 1_000; function toMillis(value: DateTime.Utc | null | undefined): number | null { return value == null ? null : DateTime.toEpochMillis(value); @@ -146,7 +145,7 @@ export function threadHasQueuedTurnStart( const messageAtMs = toMillis(thread.latestUserMessageAt); if (messageAtMs === null || thread.status === "failed") return false; const age = nowMs - messageAtMs; - if (Number.isNaN(age) || Math.abs(age) > QUEUED_TURN_START_GRACE_MS) return false; + if (Number.isNaN(age) || Math.abs(age) > Orchestrator.QUEUED_TURN_START_GRACE_MS) return false; if (thread.latestRunId === null) return true; return [ toMillis(thread.latestRunRequestedAt), diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index 85076da975852..10306f4142895 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -4610,6 +4610,119 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => { }), ); + // A thread watching a pull request, with a wake queued behind a running turn. + const queuedWatchWake = (prefix: string) => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const threadId = ThreadId.make(`${prefix}-auto-settle`); + yield* orchestrator.dispatch({ + type: "thread.create", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make(`${prefix}-create`), + threadId, + projectId: ProjectId.make(`${prefix}-project`), + title: "Queued watch wake", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: process.cwd(), + }); + const key = { host: "github.com", repository: "pingdotgg/t3code", number: 7 }; + yield* orchestrator.dispatch({ + type: "thread.pull-request.watch", + commandId: CommandId.make(`${prefix}-start`), + threadId, + ...key, + watching: true, + link: { url: "https://github.com/pingdotgg/t3code/pull/7", source: "agent" }, + }); + const started = (yield* orchestrator.getThreadShell(threadId))?.pullRequests?.[0]?.watch; + assert.isDefined(started); + yield* orchestrator.dispatch({ + type: "message.dispatch", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make(`${prefix}-active`), + threadId, + messageId: MessageId.make(`${prefix}-active`), + text: "Merge it", + attachments: [], + modelSelection, + dispatchMode: { type: "start_immediately" }, + }); + const wakeMessageId = MessageId.make(prefix); + yield* orchestrator.dispatch({ + type: "thread.pull-request-watch.sync", + commandId: CommandId.make(`${prefix}-sync`), + threadId, + ...key, + startedAt: started.startedAt, + watch: { ...started, headSha: "merged", wakes: 1 }, + wake: { + messageId: wakeMessageId, + text: "Update", + notification: { source: { kind: "monitor" }, outcome: "updated", summary: "#7 merged" }, + }, + }); + const before = yield* orchestrator.getThreadProjection(threadId); + const activeRun = before.runs.find((run) => run.status === "starting"); + const wakeRun = before.runs.find((run) => run.userMessageId === wakeMessageId); + assert.isDefined(activeRun); + assert.isDefined(wakeRun); + assert.equal(wakeRun.status, "queued"); + assert.notEqual(wakeRun.queueHeld, true); + return { threadId, activeRun, wakeRun }; + }); + + // regression: #29898 settle on merge cancelled a watch wake queued behind the finished run + it.effect("automatic settlement refuses a held wake only within the queued-turn grace", () => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const eventSink = yield* EventSink.EventSinkV2; + const { threadId, activeRun, wakeRun } = yield* queuedWatchWake("pr-watch-held-wake"); + const now = yield* DateTime.now; + // Startup recovery's command prefix skips the completion reaction, as after a restart. + yield* eventSink.write({ + commandId: CommandId.make("command:runtime-reconcile:pr-watch-held-wake"), + events: [ + { + id: EventId.make("pr-watch-held-wake-completed"), + type: "run.updated", + threadId, + occurredAt: now, + payload: { ...activeRun, status: "completed", completedAt: now }, + }, + { + id: EventId.make("pr-watch-held-wake-hold"), + type: "run.updated", + threadId, + occurredAt: now, + payload: { ...wakeRun, queueHeld: true }, + }, + ], + }); + const autoSettle = (commandId: string) => + Effect.flatMap(orchestrator.getThreadShell(threadId), (shell) => + orchestrator.dispatch({ + type: "thread.auto-settle", + commandId: CommandId.make(commandId), + threadId, + snapshotAt: shell?.updatedAt ?? now, + }), + ); + const early = yield* autoSettle("pr-watch-held-wake-early").pipe(Effect.exit); + assert.equal(early._tag, "Failure"); + + yield* TestClock.adjust(Orchestrator.QUEUED_TURN_START_GRACE_MS); + yield* autoSettle("pr-watch-held-wake-late"); + const after = yield* orchestrator.getThreadProjection(threadId); + assert.isNotNull(after.thread.settledAt); + assert.equal(after.runs.find((run) => run.id === wakeRun.id)?.status, "cancelled"); + }), + ); + it.effect("archiving ends watches, and an archived thread cannot start one", () => Effect.gen(function* () { const orchestrator = yield* Orchestrator.OrchestratorV2; From 72e7e8b044ec29ab21845a0f5b05e28fd47d5fe0 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 20:52:30 -0800 Subject: [PATCH 009/284] fix: multi-select questions can be answered with nothing checked (#32017) --- .../Adapters/OpenCode2AdapterV2.test.ts | 69 +++++++++++++++++++ .../src/orchestration-v2/Orchestrator.ts | 9 +++ .../src/orchestration-v2/runtimeLayer.test.ts | 5 +- .../fixtures/acp_titled_multiselect/output.ts | 1 + .../src/state/pendingUserInput.test.ts | 34 +++++++++ .../src/state/pendingUserInput.ts | 13 ++-- .../src/server/elicitationForm.test.ts | 29 ++++++++ .../src/server/elicitationForm.ts | 9 ++- .../src/server/xaiAcpExtension.test.ts | 26 +++++++ .../src/server/xaiAcpExtension.ts | 4 +- .../src/server/v2/adapter.ts | 10 ++- 11 files changed, 194 insertions(+), 15 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts index 33b2ecd4638c5..a6a1056d1a95b 100644 --- a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts @@ -3263,6 +3263,75 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { }), ); + it.effect("answers an optional multiselect with none and keeps a minimum choice required", () => + Effect.gen(function* () { + const formID = "frm_0eb79ab35001fkvFECSh3wYNVE"; + const { runtime, thread } = yield* resumed([ + out("session.prompt", { sessionID: SESSION, text: "" }), + promptAccepted, + event("session.execution.started", { sessionID: SESSION }), + event("form.created", { + form: { + id: formID, + sessionID: SESSION, + title: "Setup", + fields: [ + { + key: "extras", + type: "multiselect", + title: "Extras", + options: [ + { value: "lint", label: "Lint" }, + { value: "tests", label: "Tests" }, + ], + }, + { + key: "targets", + type: "multiselect", + title: "Targets", + minItems: 1, + options: [{ value: "web", label: "Web" }], + }, + ], + }, + }), + out("session.form.reply", { + sessionID: SESSION, + formID, + answer: { extras: [], targets: ["web"] }, + }), + reply("session.form.reply", null), + event("session.execution.succeeded", { sessionID: SESSION }), + ]); + const shown = yield* runtime.events.pipe( + Stream.takeUntil((event) => event.type === "runtime_request.updated"), + Stream.runCollect, + Effect.forkScoped, + ); + yield* runtime.startTurn(turnInput(thread)); + const events = yield* Fiber.join(shown); + const questions = events.flatMap((event) => + event.type === "turn_item.updated" && event.turnItem.type === "user_input_request" + ? event.turnItem.questions + : [], + ); + assert.deepEqual( + questions.map((question) => [question.id, question.required]), + [ + ["extras", undefined], + ["targets", true], + ], + ); + const request = events.find((event) => event.type === "runtime_request.updated"); + const terminal = yield* terminalOf(runtime).pipe(Effect.forkScoped); + yield* runtime.respondToRuntimeRequest({ + requestId: request!.runtimeRequest.id, + answers: { extras: [], targets: ["web"] }, + }); + assert.equal((yield* Fiber.join(terminal))?.status, "completed"); + }).pipe(Effect.scoped), + ); + it.effect("asks a subagent's permission request on the parent thread's turn", () => Effect.gen(function* () { const child = "ses_f0e5aa64cffelFnoQRL0DAA9BH"; diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 93693cc55fca4..10a986269e9bb 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -11704,6 +11704,15 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio } for (const question of approvalTurnItem.questions) { const answer = answers?.[question.id]; + if ( + question.multiSelect === true && + question.required !== true && + Array.isArray(answer) && + answer.length === 0 + ) { + replies.push(`${question.question}\nNone selected`); + continue; + } const answered = isMessageQuestionAnswer(answer); // Clients send "" for a skipped optional question, such as an attachment-only answer. if (!answered && question.required === false) continue; diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index 10306f4142895..27091a5027bcd 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -2703,7 +2703,6 @@ it.layer(layerTest)("OrchestrationV2LayerLive", (it) => { const beforeSequence = yield* eventSink.latestSequence(); for (const [index, answers] of [ { color: " ", sizes: ["Small"] }, - { color: "Blue", sizes: [] }, { color: "Blue", sizes: ["Small", " "] }, { color: "Blue", sizes: ["Small"], extra: " " }, ].entries()) { @@ -2728,7 +2727,7 @@ it.layer(layerTest)("OrchestrationV2LayerLive", (it) => { commandId: CommandId.make("runtime-async-question-answer"), threadId, requestId, - answers: { color: " Blue ", sizes: ["Small", "Large"], note: "" }, + answers: { color: " Blue ", sizes: [], note: "" }, }; const accepted = yield* orchestrator.dispatch(command); const repeated = yield* orchestrator.dispatch(command); @@ -2753,7 +2752,7 @@ it.layer(layerTest)("OrchestrationV2LayerLive", (it) => { }); } assert.equal(answered.messages.length, 1); - assert.equal(answered.messages[0]?.text, "Which color?\nBlue\n\nWhich sizes?\nSmall, Large"); + assert.equal(answered.messages[0]?.text, "Which color?\nBlue\n\nWhich sizes?\nNone selected"); assert.equal(answered.messages[0]?.role, "user"); assert.equal(answered.runs.length, 1); assert.deepEqual( diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/acp_titled_multiselect/output.ts b/apps/server/src/orchestration-v2/testkit/fixtures/acp_titled_multiselect/output.ts index 14e4f2ddb793e..8e2454eecbf64 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/acp_titled_multiselect/output.ts +++ b/apps/server/src/orchestration-v2/testkit/fixtures/acp_titled_multiselect/output.ts @@ -41,6 +41,7 @@ export function assertAcpTitledMultiSelectOutput( ], allowCustomAnswer: false, multiSelect: true, + required: true, }, ]); } diff --git a/packages/client-runtime/src/state/pendingUserInput.test.ts b/packages/client-runtime/src/state/pendingUserInput.test.ts index d9d4ddbddb6bc..3d6b7dc5f83b3 100644 --- a/packages/client-runtime/src/state/pendingUserInput.test.ts +++ b/packages/client-runtime/src/state/pendingUserInput.test.ts @@ -189,6 +189,40 @@ describe("buildPendingUserInputAnswers", () => { compat: "Keep the current envelope for one release window", }); }); + + it("answers a multi-select question with no options checked as an empty list", () => { + const extrasQuestion = { + id: "extras", + header: "Extras", + question: "Which extras do you want?", + options: [{ label: "Lint" }, { label: "Tests" }, { label: "CI" }], + multiSelect: true, + } as const; + const uncheckedAgain = togglePendingUserInputOptionSelection( + extrasQuestion, + togglePendingUserInputOptionSelection(extrasQuestion, undefined, "Lint"), + "Lint", + ); + const scope = { selectedOptionValues: ["Node.js"] }; + + expect(buildPendingUserInputAnswers([singleSelectQuestion, extrasQuestion], { scope })).toEqual( + { scope: "Node.js", extras: [] }, + ); + expect( + buildPendingUserInputAnswers([singleSelectQuestion, extrasQuestion], { + scope, + extras: uncheckedAgain, + }), + ).toEqual({ scope: "Node.js", extras: [] }); + expect( + buildPendingUserInputAnswers([singleSelectQuestion, extrasQuestion], { extras: {} }), + ).toBeNull(); + expect( + buildPendingUserInputAnswers([singleSelectQuestion, { ...extrasQuestion, required: true }], { + scope, + }), + ).toBeNull(); + }); }); it.each([ diff --git a/packages/client-runtime/src/state/pendingUserInput.ts b/packages/client-runtime/src/state/pendingUserInput.ts index 6569d7a5db77e..228883323e7ca 100644 --- a/packages/client-runtime/src/state/pendingUserInput.ts +++ b/packages/client-runtime/src/state/pendingUserInput.ts @@ -77,17 +77,16 @@ export function resolvePendingUserInputAnswer( } const selectedOptionValues = normalizeSelectedOptionValues(question, draft?.selectedOptionValues); + const fallback = + customAnswer ?? + (question.allowCustomAnswer !== false && (draft?.attachmentCount ?? 0) > 0 ? "" : null); if (question.multiSelect) { + // Checking nothing answers "none of these" unless the provider requires a choice. return selectedOptionValues.length > 0 ? selectedOptionValues - : (customAnswer ?? - (question.allowCustomAnswer !== false && (draft?.attachmentCount ?? 0) > 0 ? "" : null)); + : (fallback ?? (question.required ? null : [])); } - return ( - selectedOptionValues[0] ?? - customAnswer ?? - (question.allowCustomAnswer !== false && (draft?.attachmentCount ?? 0) > 0 ? "" : null) - ); + return selectedOptionValues[0] ?? fallback; } export function setPendingUserInputCustomAnswer( diff --git a/packages/provider-acp/src/server/elicitationForm.test.ts b/packages/provider-acp/src/server/elicitationForm.test.ts index b288f8603132d..251ee68ac4170 100644 --- a/packages/provider-acp/src/server/elicitationForm.test.ts +++ b/packages/provider-acp/src/server/elicitationForm.test.ts @@ -104,4 +104,33 @@ describe("parseElicitationForm", () => { q0__other: "SQLite", }); }); + + it("requires a multi-select only for a required minimum and accepts none otherwise", () => { + const items = { type: "string", enum: ["web", "mobile"] }; + const form = parseElicitationForm( + { + type: "object", + properties: { + targets: { type: "array", minItems: 1, items }, + extras: { type: "array", items }, + platforms: { type: "array", minItems: 1, items }, + }, + required: ["targets"], + }, + "Choose", + ); + assert(form !== undefined); + assert.deepStrictEqual( + form.questions.map((question) => [question.id, question.required]), + [ + ["targets", true], + ["extras", undefined], + ["platforms", undefined], + ], + ); + assert.deepStrictEqual(form.content({ targets: ["web"], extras: [], platforms: [] }), { + targets: ["web"], + extras: [], + }); + }); }); diff --git a/packages/provider-acp/src/server/elicitationForm.ts b/packages/provider-acp/src/server/elicitationForm.ts index 948306c137722..281d8a69a14dd 100644 --- a/packages/provider-acp/src/server/elicitationForm.ts +++ b/packages/provider-acp/src/server/elicitationForm.ts @@ -111,7 +111,7 @@ function parseField( const values = new Set(options.map(optionValue)); const minItems = typeof property.minItems === "number" ? property.minItems : 0; const maxItems = typeof property.maxItems === "number" ? property.maxItems : Infinity; - // Clients require a selection, so empty-only questions cannot be answered. + // Empty-only questions carry no choice worth asking. if (maxItems === 0 || minItems > maxItems || minItems > values.size) return undefined; return { field: { kind: "multiChoice", values, minItems, maxItems }, options }; } @@ -222,7 +222,8 @@ export function parseElicitationForm( const questions: OrchestrationV2UserInputQuestion[] = []; for (const { id, property, options } of parsedFields) { if (folded.has(id)) continue; - const kind = fields.get(id)?.kind; + const field = fields.get(id); + const kind = field?.kind; questions.push({ id, header: text(property.title) ?? `Question ${questions.length + 1}`, @@ -235,6 +236,10 @@ export function parseElicitationForm( ? {} : { allowCustomAnswer: false }), ...(kind === "multiChoice" ? { multiSelect: true } : {}), + // An empty selection answers "none" unless the schema demands a choice. + ...(field?.kind === "multiChoice" && field.minItems > 0 && required.has(id) + ? { required: true } + : {}), ...(kind === "text" && !required.has(id) ? { required: false } : {}), }); } diff --git a/packages/provider-grok/src/server/xaiAcpExtension.test.ts b/packages/provider-grok/src/server/xaiAcpExtension.test.ts index b1a24b2cff81f..732330b08b9c3 100644 --- a/packages/provider-grok/src/server/xaiAcpExtension.test.ts +++ b/packages/provider-grok/src/server/xaiAcpExtension.test.ts @@ -1249,6 +1249,32 @@ describe("XAiAcpExtension", () => { }); }); + it("answers a multi-select question with nothing checked as an empty list", () => { + const response = makeXAiAskUserQuestionResponse( + { + sessionId: "session-1", + toolCallId: "tool-call-1", + mode: "default", + questions: [ + { + question: "Which files should Grok touch?", + multiSelect: true, + options: [ + { label: "Tests", description: "Update tests" }, + { label: "Docs", description: "Update docs" }, + ], + }, + ], + }, + { "Which files should Grok touch?": [] }, + ); + + expect(response).toEqual({ + outcome: "accepted", + answers: { "Which files should Grok touch?": [] }, + }); + }); + it.effect("settles a hung prompt from a root-session prompt_complete notification", () => Effect.gen(function* () { const handlers = new Map Effect.Effect>(); diff --git a/packages/provider-grok/src/server/xaiAcpExtension.ts b/packages/provider-grok/src/server/xaiAcpExtension.ts index 7181d1927923c..cb74c645e12ea 100644 --- a/packages/provider-grok/src/server/xaiAcpExtension.ts +++ b/packages/provider-grok/src/server/xaiAcpExtension.ts @@ -1211,7 +1211,9 @@ function normalizeAnswerForXAi( ): NormalizedXAiAnswer | undefined { const values = answerValues(answer); if (values.length === 0) { - return undefined; + return question.multiSelect === true && Array.isArray(answer) + ? { questionText: question.question, selectedLabels: [] } + : undefined; } const optionByLabel = new Map(question.options.map((option) => [option.label, option])); diff --git a/packages/provider-opencode/src/server/v2/adapter.ts b/packages/provider-opencode/src/server/v2/adapter.ts index f72771656c1e6..838d4199d93f1 100644 --- a/packages/provider-opencode/src/server/v2/adapter.ts +++ b/packages/provider-opencode/src/server/v2/adapter.ts @@ -530,6 +530,9 @@ const formQuestions = ( options, multiSelect: field.type === "multiselect", allowCustomAnswer: field.custom === true || options.length === 0, + ...(field.required === true || (field.type === "multiselect" && (field.minItems ?? 0) > 0) + ? { required: true } + : {}), }); } return { questions }; @@ -542,8 +545,11 @@ const formAnswer = (form: NativeForm, answers: Readonly> const values = (Array.isArray(raw) ? raw : [raw]).filter( (value): value is string => typeof value === "string" && value.trim().length > 0, ); - if (values.length > 0) { - answer[field.key] = field.type === "multiselect" ? values : values.join(", "); + // An explicit empty list answers an optional multiselect with "none". + if (field.type === "multiselect" && (Array.isArray(raw) || values.length > 0)) { + answer[field.key] = values; + } else if (values.length > 0) { + answer[field.key] = values.join(", "); } } return answer; From 8032cbb66bc0d067a9c7d2eb88f6d06f9fa415cf Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 20:52:43 -0800 Subject: [PATCH 010/284] fix(web): Cmd+F searches a side chat, and Escape closes it (#28919) --- .../src/components/chat/SideThreadPane.tsx | 27 +++-- .../components/chat/threadFindStore.test.ts | 21 ++++ .../src/components/chat/threadFindStore.ts | 16 ++- .../chat/useChatShortcuts.browser.test.tsx | 107 +++++++++++++++--- .../src/components/chat/useChatShortcuts.ts | 42 +++---- apps/web/src/lib/previewFocus.ts | 6 +- 6 files changed, 171 insertions(+), 48 deletions(-) diff --git a/apps/web/src/components/chat/SideThreadPane.tsx b/apps/web/src/components/chat/SideThreadPane.tsx index 9f32d90c4f8a7..516103c5415f0 100644 --- a/apps/web/src/components/chat/SideThreadPane.tsx +++ b/apps/web/src/components/chat/SideThreadPane.tsx @@ -1,4 +1,4 @@ -import { scopeThreadRef } from "@t3tools/client-runtime/environment"; +import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment"; import { sideThreadKindOf } from "@t3tools/client-runtime/side-thread"; import { formatSubagentDisplayTitle } from "@t3tools/client-runtime/state/subagent-display"; import { @@ -18,7 +18,12 @@ import { useClientSettings } from "../../hooks/useSettings"; import { releaseComposerDraftUploads } from "../../lib/composerDraftUploads"; import type { SideChatParentPanel } from "../../lib/sideChatPane"; import { readLocalApi } from "../../localApi"; -import { hostRightPanel, type ThreadSurface, useRightPanelStore } from "../../rightPanelStore"; +import { + hostRightPanel, + rightPanelHostRef, + type ThreadSurface, + useRightPanelStore, +} from "../../rightPanelStore"; import { useQuietThreadProjection, useQuietThreadShell } from "../../state/entities"; import { useEnvironmentScope } from "../../state/session"; import { useEnvironmentShellStatus } from "../../state/shell"; @@ -34,6 +39,7 @@ 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"; /** * A side chat or a subagent as a tab: the thread's own chat, which decides its bottom, the @@ -51,11 +57,18 @@ export default function SideThreadPane(props: { const { threadId } = surface; const gt = useGT(); const threadRef = scopeThreadRef(parentRef.environmentId, threadId); - // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- registers the parent panel as host in the panel store - useEffect( - () => hostRightPanel(scopeThreadRef(parentRef.environmentId, threadId), parentRef), - [parentRef, threadId], - ); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- registers the parent panel as host in the panel store, and closes this side chat's find with its pane + useEffect(() => { + const ref = scopeThreadRef(parentRef.environmentId, threadId); + const unhost = hostRightPanel(ref, parentRef); + return () => { + unhost(); + // Crossing the sheet breakpoint remounts the pane in the same commit, which re-hosts it. + queueMicrotask(() => { + if (rightPanelHostRef(ref) === ref) closeThreadFindIn(scopedThreadKey(ref)); + }); + }; + }, [parentRef, threadId]); const shell = useQuietThreadShell(threadRef); const bootstrapComplete = isThreadRouteSnapshotAuthoritative( useEnvironmentShellStatus(parentRef.environmentId), diff --git a/apps/web/src/components/chat/threadFindStore.test.ts b/apps/web/src/components/chat/threadFindStore.test.ts index 3819d8a4110f7..78f65d411ea76 100644 --- a/apps/web/src/components/chat/threadFindStore.test.ts +++ b/apps/web/src/components/chat/threadFindStore.test.ts @@ -2,6 +2,8 @@ import { scopeThreadRef } from "@t3tools/client-runtime/environment"; import { EnvironmentId, MessageId, ThreadId } from "@t3tools/contracts"; import { describe, expect, it, vi } from "vite-plus/test"; +import { hostRightPanel } from "../../rightPanelStore"; + import { attachThreadFindTimeline, closeThreadFind, @@ -78,6 +80,25 @@ describe("thread find store", () => { retainThreadFindForRoute({ modalPage: false, threadRef: null }); expect(useThreadFindStore.getState().threadKey).toBeNull(); }); + + it("keeps a side chat's find on its parent's route while the side chat is shown there", () => { + setup(); + const unhost = hostRightPanel(otherRef, threadRef); + openThreadFindOnQuery("env-1:thread-2", { query: "x" }); + retainThreadFindForRoute({ modalPage: true, threadRef: null }); + retainThreadFindForRoute({ modalPage: false, threadRef }); + expect(useThreadFindStore.getState()).toMatchObject({ + threadKey: "env-1:thread-2", + query: "x", + }); + // A route to the side chat itself shows it too, even while its pane is still hosted. + retainThreadFindForRoute({ modalPage: false, threadRef: otherRef }); + expect(useThreadFindStore.getState().threadKey).toBe("env-1:thread-2"); + + unhost(); + retainThreadFindForRoute({ modalPage: false, threadRef }); + expect(useThreadFindStore.getState().threadKey).toBeNull(); + }); }); describe("findForMessageMatch", () => { diff --git a/apps/web/src/components/chat/threadFindStore.ts b/apps/web/src/components/chat/threadFindStore.ts index e3004c64adda0..260c0b089928c 100644 --- a/apps/web/src/components/chat/threadFindStore.ts +++ b/apps/web/src/components/chat/threadFindStore.ts @@ -3,7 +3,7 @@ import type { OrchestrationV2SearchThreadResult, ScopedThreadRef, } from "@t3tools/contracts"; -import { scopedThreadKey } from "@t3tools/client-runtime/environment"; +import { parseScopedThreadKey, scopedThreadKey } from "@t3tools/client-runtime/environment"; import { findSearchTokenRanges, messagePhrase, @@ -11,6 +11,7 @@ import { } from "@t3tools/shared/paletteSearch"; import { create } from "zustand"; import type { ThemeAppearance } from "~/themePalette"; +import { rightPanelHostRef } from "../../rightPanelStore"; import type { ThreadFindPositionReader, ThreadFindStart } from "./threadFind"; export interface ThreadFindLocalSelection { @@ -148,9 +149,15 @@ export function closeThreadFind(): void { useThreadFindStore.setState(CLOSED_THREAD_FIND); } +/** Closes find if it is open in `threadKey`, leaving another thread's find alone. */ +export function closeThreadFindIn(threadKey: string): void { + if (useThreadFindStore.getState().threadKey === threadKey) closeThreadFind(); +} + /** * Find belongs to the thread it was opened in: a route showing anything else - * closes it. Settings and Usage draw over the thread, so they keep it. + * closes it. Settings and Usage draw over the thread, so they keep it, and a + * side chat is shown by its parent's route while its pane is open there. */ export function retainThreadFindForRoute(route: { readonly modalPage: boolean; @@ -158,8 +165,11 @@ export function retainThreadFindForRoute(route: { }): void { if (route.modalPage) return; const { threadKey } = useThreadFindStore.getState(); + if (threadKey === null) return; const shownKey = route.threadRef ? scopedThreadKey(route.threadRef) : null; - if (threadKey !== null && threadKey !== shownKey) closeThreadFind(); + const findRef = parseScopedThreadKey(threadKey); + const hostKey = findRef ? scopedThreadKey(rightPanelHostRef(findRef)) : threadKey; + if (threadKey !== shownKey && hostKey !== shownKey) closeThreadFind(); } /** Whether find is open in `thread`, as long as find is available there. */ diff --git a/apps/web/src/components/chat/useChatShortcuts.browser.test.tsx b/apps/web/src/components/chat/useChatShortcuts.browser.test.tsx index 378bc2b5cce74..d3d1b06871e98 100644 --- a/apps/web/src/components/chat/useChatShortcuts.browser.test.tsx +++ b/apps/web/src/components/chat/useChatShortcuts.browser.test.tsx @@ -3,6 +3,8 @@ import { useEffect, useState } from "react"; import { expect, it } from "vite-plus/test"; import { userEvent } from "vite-plus/test/browser"; +import { compileResolvedKeybindingsConfig } from "@t3tools/shared/keybindings"; +import { isPreviewFocused } from "~/lib/previewFocus"; import { surfaceShortcutKey } from "~/lib/surfaceShortcutKey"; import { render } from "../../../test/render"; import type { ChatComposerHandle } from "./ChatComposer"; @@ -20,6 +22,11 @@ const shortcutContext = { const focusOnMount = (element: HTMLElement | null) => element?.focus(); +const ctrl = (key: string, command: KeybindingCommand, shiftKey = false) => ({ + command, + shortcut: { key, metaKey: false, ctrlKey: true, shiftKey, altKey: false, modKey: false }, +}); + // Stands in for the right panel's launcher, which needs the whole app around it. Like the // real one it takes focus, advertises its letters in `data-surface-launcher-keys`, and // claims one from its own window capture listener unless the key was already handled. @@ -47,10 +54,14 @@ function Launcher(props: { keys: string; received: string[] }) { // The chat's shortcut listener registers when the chat mounts, so a launcher that opens // later registers after it. Tests mount the chat first and add the launcher by rerendering. -function Chat(props: { composerKeys: string[]; launcher?: { keys: string; received: string[] } }) { +function Chat(props: { + composerKeys: string[]; + launcher?: { keys: string; received: string[] }; + finds?: string[]; +}) { useChatShortcuts({ enabled: true, - keybindings: [], + keybindings: [ctrl("f", "chat.find")], scriptKeybindings: [], getShortcutContext: () => shortcutContext, threadFindActive: false, @@ -65,7 +76,7 @@ function Chat(props: { composerKeys: string[]; launcher?: { keys: string; receiv }, branchToolbarRef: { current: null }, closeThreadFind: () => {}, - commands: {}, + commands: { "chat.find": () => void props.finds?.push("main") }, fallback: () => undefined, }); return props.launcher ? : null; @@ -134,17 +145,23 @@ it.each([ expect(received).toEqual(launcher); }); -const ctrlShift = (key: string, command: KeybindingCommand) => ({ - command, - shortcut: { key, metaKey: false, ctrlKey: true, shiftKey: true, altKey: false, modKey: false }, -}); const sideChatKeybindings: ResolvedKeybindingsConfig = [ - ctrlShift("m", "modelPicker.toggle"), - ctrlShift("x", "thread.stop"), + ctrl("m", "modelPicker.toggle", true), + ctrl("x", "thread.stop", true), + // The default find rule, with ctrl for mod so it matches on every platform. + ...compileResolvedKeybindingsConfig([ + { key: "ctrl+f", command: "chat.find", when: "!terminalFocus && !previewFocus" }, + ]), ]; -// A side chat in the main chat's panel: no window listeners, only its composer's own chords. -function SideChat(props: { toggles: string[]; stops: string[] }) { +// A side chat in the main chat's right panel: no window listeners, only its pane's find and its +// composer's own chords. Passing `findCloses` opens its find. +function SideChat(props: { + toggles: string[]; + stops: string[]; + finds?: string[]; + findCloses?: string[]; +}) { const [composerElement, setComposerElement] = useState(null); useChatShortcuts({ enabled: false, @@ -152,22 +169,33 @@ function SideChat(props: { toggles: string[]; stops: string[] }) { composerElement, keybindings: sideChatKeybindings, scriptKeybindings: [], - getShortcutContext: () => shortcutContext, - threadFindActive: false, + getShortcutContext: () => ({ ...shortcutContext, previewFocus: isPreviewFocused() }), + threadFindActive: props.findCloses !== undefined, composerRef: { current: { toggleModelPicker: () => props.toggles.push("model"), } as Partial as ChatComposerHandle, }, branchToolbarRef: { current: null }, - closeThreadFind: () => {}, - commands: { "thread.stop": () => void props.stops.push("stop") }, + closeThreadFind: () => void props.findCloses?.push("side"), + commands: { + "thread.stop": () => void props.stops.push("stop"), + "chat.find": () => void props.finds?.push("side"), + }, fallback: () => undefined, }); return ( <> -
-