From 49c3ab86323444c3464f1404ace52017ccd7f83b Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 16 Nov 2026 23:43:54 -0800 Subject: [PATCH 001/133] fix(web): published background no longer shows under a saved theme with the same id (#37981) --- apps/web/src/themeBackground.test.ts | 32 ++++++++++++++++++++++++++-- apps/web/src/themeBackground.ts | 4 +++- 2 files changed, 33 insertions(+), 3 deletions(-) diff --git a/apps/web/src/themeBackground.test.ts b/apps/web/src/themeBackground.test.ts index d09ea591730d..5c0e7c3c91b4 100644 --- a/apps/web/src/themeBackground.test.ts +++ b/apps/web/src/themeBackground.test.ts @@ -38,17 +38,25 @@ vi.mock( ); import { applyThemeBackground, startThemeBackground } from "./themeBackground"; +import { + CUSTOM_THEMES_STORAGE_KEY, + getThemeDefinition, + invalidateCustomThemes, +} from "./themePalette"; const BACKGROUND = "--theme-background-image"; const image = new Blob(["image"], { type: "image/png" }); const offline = () => Promise.reject(new TypeError("Failed to fetch")); const loaded = async () => ({ ok: true, blob: async () => image }); -function setup() { +function setup(storage: Record = {}) { vi.useFakeTimers(); const properties = new Map(); - const browser = new EventTarget(); + const browser = Object.assign(new EventTarget(), { + localStorage: { getItem: (key: string) => storage[key] ?? null }, + }); vi.stubGlobal("window", browser); + invalidateCustomThemes(); vi.stubGlobal("document", { documentElement: { dataset: { themeId: "nightfall" }, @@ -71,6 +79,7 @@ function setup() { stop(); applyThemeBackground(undefined); vi.unstubAllGlobals(); + invalidateCustomThemes(); vi.useRealTimers(); }, }; @@ -129,4 +138,23 @@ describe("theme backgrounds", () => { await vi.advanceTimersByTimeAsync(30_000); expect(t.fetchBackground).toHaveBeenCalledTimes(1); }); + + it("shows no published background when a saved theme shares its id", async () => { + using t = setup({ + [CUSTOM_THEMES_STORAGE_KEY]: JSON.stringify([ + { + id: "nightfall", + label: "Nightfall", + appearance: "dark", + colors: { canvas: "#162327", accent: "#cc3344" }, + }, + ]), + }); + t.fetchBackground.mockImplementation(loaded); + expect(getThemeDefinition("nightfall")?.colors.accent).toBeDefined(); + applyThemeBackground("nightfall"); + await vi.advanceTimersByTimeAsync(0); + expect(t.fetchBackground).not.toHaveBeenCalled(); + expect(t.properties.has(BACKGROUND)).toBe(false); + }); }); diff --git a/apps/web/src/themeBackground.ts b/apps/web/src/themeBackground.ts index 43098883eab5..26267de50d2f 100644 --- a/apps/web/src/themeBackground.ts +++ b/apps/web/src/themeBackground.ts @@ -7,6 +7,7 @@ import { assetEnvironment } from "./state/assets"; import { themeEnvironmentIdAtom } from "./state/primaryEnvironment"; import { themeServerEnvironmentThemesAtom } from "./state/server"; import { environmentSession } from "./state/session"; +import { getCustomThemes } from "./themePalette"; const THEME_BACKGROUND_VARIABLE = "--theme-background-image"; const RETRY_DELAYS_MS = [1_000, 2_000, 4_000, 8_000]; @@ -55,8 +56,9 @@ async function loadBackground( export function applyThemeBackground(themeId: string | undefined): void { if (typeof document === "undefined") return; const environmentId = appAtomRegistry.get(themeEnvironmentIdAtom); + // A saved theme wins its id over a published one, so the published image is not its. const revision = - themeId === undefined + themeId === undefined || getCustomThemes().some((theme) => theme.id === themeId) ? undefined : appAtomRegistry.get(themeServerEnvironmentThemesAtom)?.find((theme) => theme.id === themeId) ?.background; From 6ec1d31b1ebade38fdc6bf88c7401d0ea35a1180 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Tue, 17 Nov 2026 09:11:34 +0100 Subject: [PATCH 002/133] fix(web): preserve literal XML declarations in EPUB previews (#36624) Co-authored-by: Julius Marminge --- .../components/files/FilePreviewPanel.test.ts | 25 ++++++++++---- .../files/extendedDocumentPreview.ts | 34 ++++++++++++------- 2 files changed, 39 insertions(+), 20 deletions(-) diff --git a/apps/web/src/components/files/FilePreviewPanel.test.ts b/apps/web/src/components/files/FilePreviewPanel.test.ts index 46293599740c..970c4a2ff5da 100644 --- a/apps/web/src/components/files/FilePreviewPanel.test.ts +++ b/apps/web/src/components/files/FilePreviewPanel.test.ts @@ -470,7 +470,7 @@ Third}`; expect(result.pages[0]!.html).toBe(`${html}
`); }); - it.each(["odt", "odp"] as const)("reads %s text and rejects XML entities", async (kind) => { + it.each(["odt", "odp"] as const)("reads %s text and rejects unsupported XML", async (kind) => { const archive = new JSZip().file( "content.xml", `${kind === "odt" ? "Field notes" : 'Launch planSpeaker only'}`, @@ -480,11 +480,19 @@ Third}`; if (result.type !== "document") throw new Error("Expected document"); expect(result.pages[0]!.html).toContain(kind === "odt" ? "Field notes" : "Launch plan"); expect(result.pages[0]!.html).not.toContain("Speaker only"); - archive.file( - "content.xml", + for (const source of [ ']>&external;', - ); - await expect(openDocument(archive, kind)).rejects.toThrow("unsupported XML"); + '

x

]>&e;', + '

x

]>&e;', + 'TYPE x [TITY e "boom">]>&e;', + ']>
', + ']>', + "" + "< © ≂̸', ) .file( "Book/cover.png", @@ -518,7 +526,10 @@ Third}`; expect(result.pages.map((page) => page.title)).toEqual(["Second", "First"]); expect(result.pages[0]!.html).toContain("A\u00a0B © — ≂̸ &lt;"); expect(result.pages[0]!.html).toContain("
Use &amp; and &lt; literally
"); - expect(result.pages[0]!.html).toContain('alt="© ≂̸"'); + expect(result.pages[0]!.html).toContain( + "
<!DOCTYPE html><!ENTITY author "Ada">
", + ); + expect(result.pages[0]!.html).toContain('alt="< © ≂̸"'); expect(result.pages[1]!.html).toContain('src="data:image/png;base64,'); expect(result.pages[1]!.html).not.toMatch(/https:|script|alert/); }); diff --git a/apps/web/src/components/files/extendedDocumentPreview.ts b/apps/web/src/components/files/extendedDocumentPreview.ts index 8a8ceefe1d89..9fe4a3f7c627 100644 --- a/apps/web/src/components/files/extendedDocumentPreview.ts +++ b/apps/web/src/components/files/extendedDocumentPreview.ts @@ -35,13 +35,17 @@ const namespacePrefixes: Record = { "urn:oasis:names:tc:opendocument:xmlns:container": "", }; function parseXml(source: string): XmlNode { - // EPUB XHTML commonly declares an external DTD. Discard it without resolving it. - source = source.replaceAll(/[\]]*>/gi, ""); - if ( - source.length > 8 * 1024 * 1024 || - /|$)||$)||$)|([\]]*>)|( { + if (declaration) declares = true; + return externalDoctype ? " " : markup; + }, + ); + if (source.length > 8 * 1024 * 1024 || declares || XMLValidator.validate(source) !== true) throw new Error("This document contains invalid or unsupported XML."); const parser = new XMLParser({ preserveOrder: true, @@ -71,10 +75,13 @@ function parseXml(source: string): XmlNode { return { name: "#text", attrs: {}, children: [], text: literal }; } const attrs = Object.fromEntries( - Object.entries((item[":@"] ?? {}) as Record).map(([key, value]) => [ - key, - decodeEntities(value), - ]), + Object.entries((item[":@"] ?? {}) as Record).map(([key, value]) => { + // fast-xml-parser accepts raw '<' in element attributes, which can mask declarations + // above. Processing instructions end at their first '?>', so their data may hold '<'. + if (!name.startsWith("?") && value.includes("<")) + throw new Error("This document contains invalid or unsupported XML."); + return [key, decodeEntities(value)]; + }), ); const namespaces = Object.create(inherited) as Record; for (const [key, value] of Object.entries(attrs)) { @@ -419,8 +426,9 @@ export async function openEpub(archive: JSZip): Promise { const chapter = parseXml(await entry.async("string")); pages.push({ title: - text(find(chapter, "title")[0] ?? find(chapter, "h1")[0] ?? chapter).slice(0, 120) || - `Chapter ${pages.length + 1}`, + text(find(chapter, "title")[0] ?? find(chapter, "h1")[0] ?? chapter) + .trim() + .slice(0, 120) || `Chapter ${pages.length + 1}`, html: await epubHtml(chapter, archive, path), }); } From 980f5d412863d1b00e832b877d2692b9cdab7dba Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 17 Nov 2026 00:28:00 -0800 Subject: [PATCH 003/133] fix(server): read the active shell index without parsing thread payloads (#37966) --- .../src/orchestration-v2/ProjectionStore.ts | 81 +++++++++++-------- apps/server/src/persistence/Migrations.ts | 2 + .../Migrations/098_ActiveShellIndexIndexes.ts | 35 ++++++++ .../reconcileV2PreviewMigration.test.ts | 2 + 4 files changed, 87 insertions(+), 33 deletions(-) create mode 100644 apps/server/src/persistence/Migrations/098_ActiveShellIndexIndexes.ts diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index 9daad8e1cdae..5b8a636cc24f 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -9038,6 +9038,16 @@ export const layer: Layer.Layer = return rows[0]?.count ?? 0; }, Effect.mapError(shellSnapshotReadError)); + // Migration 98 indexes these exact expressions, so the read takes them from the index instead + // of parsing every active thread's payload. Changing one here needs a matching index change. + const indexedField = (path: string, read: "json_extract" | "json_type" = "json_extract") => + sql.literal( + `CASE WHEN json_valid(t.payload_json) THEN ${read}(t.payload_json, '${path}') END`, + ); + // The planner otherwise scans the whole (thread_id, type, status) index for this list. + const PENDING_ITEMS_INDEX = sql.literal( + "INDEXED BY orchestration_v2_projection_turn_items_shell_pending_idx", + ); const listActiveShellIndex = Effect.fn("ProjectionStore.listActiveShellIndex")(function* () { const rows = yield* sql<{ readonly thread_id: string; @@ -9057,48 +9067,53 @@ export const layer: Layer.Layer = SELECT t.thread_id, t.project_id, - json_extract(t.payload_json, '$.lineage.relationshipToParent') AS relationship_to_parent, - json_extract(t.payload_json, '$.lineage.parentThreadId') AS parent_thread_id, - json_extract(t.payload_json, '$.lineage.rootThreadId') AS root_thread_id, - json_extract(t.payload_json, '$.lineage.sideChat') AS side_chat, - json_extract(t.payload_json, '$.settledOverride') AS settled_override, - json_extract(t.payload_json, '$.settledAt') AS settled_at, - json_extract(t.payload_json, '$.pinnedAt') AS pinned_at, - json_extract(t.payload_json, '$.pinOrderKey') AS pin_order_key, - json_extract(t.payload_json, '$.snoozedUntil') AS snoozed_until, + ${indexedField("$.lineage.relationshipToParent")} AS relationship_to_parent, + ${indexedField("$.lineage.parentThreadId")} AS parent_thread_id, + ${indexedField("$.lineage.rootThreadId")} AS root_thread_id, + ${indexedField("$.lineage.sideChat")} AS side_chat, + ${indexedField("$.settledOverride")} AS settled_override, + ${indexedField("$.settledAt")} AS settled_at, + ${indexedField("$.pinnedAt")} AS pinned_at, + ${indexedField("$.pinOrderKey")} AS pin_order_key, + ${indexedField("$.snoozedUntil")} AS snoozed_until, -- A superset of isLiveSubagentShell: the sources of its run status, pending request, - -- and pending background work. + -- and pending background work. Each source is one list for the whole read, found + -- through its partial index, so finished threads cost no lookups. ( - EXISTS ( - SELECT 1 FROM orchestration_v2_projection_runs r - WHERE r.thread_id = t.thread_id - AND r.status IN ('queued', 'preparing', 'starting', 'running', 'waiting') + t.thread_id IN ( + SELECT r.thread_id FROM orchestration_v2_projection_runs r + WHERE r.status IN ('queued', 'preparing', 'starting', 'running', 'waiting') ) - OR EXISTS ( - SELECT 1 FROM orchestration_v2_projection_runtime_requests request - WHERE request.thread_id = t.thread_id AND request.status = 'pending' + OR t.thread_id IN ( + SELECT request.thread_id FROM orchestration_v2_projection_runtime_requests request + WHERE request.status = 'pending' ) -- Same predicates as the shell's pending item and link reads, for their partial indexes. - OR EXISTS ( - SELECT 1 FROM orchestration_v2_projection_turn_items item - WHERE item.thread_id = t.thread_id - AND item.type IN ('command_execution', 'dynamic_tool', 'subagent') + OR t.thread_id IN ( + SELECT item.thread_id + FROM orchestration_v2_projection_turn_items item ${PENDING_ITEMS_INDEX} + WHERE item.type IN ('command_execution', 'dynamic_tool', 'subagent') AND item.status NOT IN ('completed', 'interrupted', 'failed', 'cancelled') ) - OR EXISTS ( - SELECT 1 FROM orchestration_v2_projection_turn_items link_request - WHERE link_request.thread_id = t.thread_id - AND link_request.type = 'link_request' AND link_request.status = 'waiting' - ) - OR EXISTS ( - SELECT 1 FROM orchestration_v2_projection_provider_threads provider_thread - WHERE provider_thread.thread_id = t.thread_id - AND json_array_length(provider_thread.payload_json, '$.pendingBackgroundTasks') > 0 + OR t.thread_id IN ( + SELECT link_request.thread_id FROM orchestration_v2_projection_turn_items link_request + WHERE link_request.type = 'link_request' AND link_request.status = 'waiting' ) - OR EXISTS ( - SELECT 1 FROM json_each(t.payload_json, '$.pullRequests') link - WHERE json_type(link.value, '$.watch') IS NOT NULL + OR t.thread_id IN ( + SELECT provider_thread.thread_id + FROM orchestration_v2_projection_provider_threads provider_thread + WHERE CASE WHEN json_valid(provider_thread.payload_json) + THEN json_array_length(provider_thread.payload_json, '$.pendingBackgroundTasks') > 0 + ELSE 0 END ) + -- Only a thread with a pull request link reads its payload. CASE, not AND: SQLite + -- 3.50 evaluates both AND operands here. + OR CASE WHEN ${indexedField("$.pullRequests[0]", "json_type")} IS NOT NULL + THEN EXISTS ( + SELECT 1 FROM json_each(t.payload_json, '$.pullRequests') link + WHERE json_type(link.value, '$.watch') IS NOT NULL + ) + ELSE 0 END ) AS may_be_live, -- One list for the whole read, found through the child_thread_id index. A lookup per -- thread would parse the payload of every subagent row. diff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.ts index 8cde1a34a035..e2c62dd79379 100644 --- a/apps/server/src/persistence/Migrations.ts +++ b/apps/server/src/persistence/Migrations.ts @@ -105,6 +105,7 @@ import Migration0094 from "./Migrations/094_TurnItemMessageOrdinalIndex.ts"; import Migration0095 from "./Migrations/095_TurnItemInlineWorkOutput.ts"; import Migration0096 from "./Migrations/096_RepairStaleTitleRegeneration.ts"; import Migration0097 from "./Migrations/097_IssueTrackerBindings.ts"; +import Migration0098 from "./Migrations/098_ActiveShellIndexIndexes.ts"; const migrationEntries = [ [1, "OrchestrationEvents", Migration0001], @@ -205,6 +206,7 @@ const migrationEntries = [ [95, "TurnItemInlineWorkOutput", Migration0095], [96, "RepairStaleTitleRegeneration", Migration0096], [97, "IssueTrackerBindings", Migration0097], + [98, "ActiveShellIndexIndexes", Migration0098], ] as const; export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const); diff --git a/apps/server/src/persistence/Migrations/098_ActiveShellIndexIndexes.ts b/apps/server/src/persistence/Migrations/098_ActiveShellIndexIndexes.ts new file mode 100644 index 000000000000..da25d04c6ebf --- /dev/null +++ b/apps/server/src/persistence/Migrations/098_ActiveShellIndexIndexes.ts @@ -0,0 +1,35 @@ +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/sql/SqlClient"; + +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + // ProjectionStore.listActiveShellIndex reads these fields from the index instead of parsing + // every active thread's payload. Keep the expressions identical to that query's. + yield* sql` + CREATE INDEX IF NOT EXISTS orchestration_v2_projection_threads_active_shell_idx + ON orchestration_v2_projection_threads( + updated_at, + thread_id, + project_id, + CASE WHEN json_valid(payload_json) THEN json_extract(payload_json, '$.lineage.relationshipToParent') END, + CASE WHEN json_valid(payload_json) THEN json_extract(payload_json, '$.lineage.parentThreadId') END, + CASE WHEN json_valid(payload_json) THEN json_extract(payload_json, '$.lineage.rootThreadId') END, + CASE WHEN json_valid(payload_json) THEN json_extract(payload_json, '$.lineage.sideChat') END, + CASE WHEN json_valid(payload_json) THEN json_extract(payload_json, '$.settledOverride') END, + CASE WHEN json_valid(payload_json) THEN json_extract(payload_json, '$.settledAt') END, + CASE WHEN json_valid(payload_json) THEN json_extract(payload_json, '$.pinnedAt') END, + CASE WHEN json_valid(payload_json) THEN json_extract(payload_json, '$.pinOrderKey') END, + CASE WHEN json_valid(payload_json) THEN json_extract(payload_json, '$.snoozedUntil') END, + CASE WHEN json_valid(payload_json) THEN json_type(payload_json, '$.pullRequests[0]') END + ) + WHERE deleted_at IS NULL AND archived_at IS NULL + `; + yield* sql` + CREATE INDEX IF NOT EXISTS orchestration_v2_projection_provider_threads_pending_tasks_idx + ON orchestration_v2_projection_provider_threads(thread_id) + WHERE CASE WHEN json_valid(payload_json) + THEN json_array_length(payload_json, '$.pendingBackgroundTasks') > 0 + ELSE 0 END + `; +}); diff --git a/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts b/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts index 79e52b517f65..fbe47613c87e 100644 --- a/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts +++ b/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts @@ -77,6 +77,7 @@ describe("V2 preview upgrade", () => { [95, "TurnItemInlineWorkOutput"], [96, "RepairStaleTitleRegeneration"], [97, "IssueTrackerBindings"], + [98, "ActiveShellIndexIndexes"], ]); assert.deepStrictEqual(yield* runMigrations(), []); assert.deepStrictEqual(yield* sql`SELECT * FROM orchestration_v2_legacy_imports`, imports); @@ -197,6 +198,7 @@ describe("V2 preview upgrade", () => { [95, "TurnItemInlineWorkOutput"], [96, "RepairStaleTitleRegeneration"], [97, "IssueTrackerBindings"], + [98, "ActiveShellIndexIndexes"], ]); }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))), ); From f98249acad344b021f074d483be8643d79928c2e Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 17 Nov 2026 00:29:52 -0800 Subject: [PATCH 004/133] fix(web): unsaved PR review comments survive a light/dark switch (#38004) --- .../PullRequestCodeTab.browser.test.tsx | 61 +++++++++++++++++++ .../pullRequest/PullRequestCodeTab.tsx | 8 +-- 2 files changed, 63 insertions(+), 6 deletions(-) diff --git a/apps/web/src/components/pullRequest/PullRequestCodeTab.browser.test.tsx b/apps/web/src/components/pullRequest/PullRequestCodeTab.browser.test.tsx index 21f5c099a54c..4d305c4da66e 100644 --- a/apps/web/src/components/pullRequest/PullRequestCodeTab.browser.test.tsx +++ b/apps/web/src/components/pullRequest/PullRequestCodeTab.browser.test.tsx @@ -12,6 +12,7 @@ import { userEvent } from "vite-plus/test/browser"; import "~/index.css"; import { __setClientSettingsForTests } from "../../hooks/useSettings"; +import { setAppearanceMode } from "../../hooks/useTheme"; import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings"; const { diffAtom, pagedDiffAtom } = await vi.hoisted(async () => { @@ -499,3 +500,63 @@ it("hides a resolved conversation behind avatars on its line until they are clic .element(screen.getByRole("button", { name: "2 resolved conversations" })) .toBeVisible(); }); + +// regression: #37996 +it("keeps an unsent reply when the appearance switches between light and dark", async () => { + setup({ paged: false }); + __setClientSettingsForTests({ ...DEFAULT_CLIENT_SETTINGS, diffFilesCollapsed: false }); + setAppearanceMode("dark"); + using _preferences = { + [Symbol.dispose]() { + __setClientSettingsForTests(DEFAULT_CLIENT_SETTINGS); + setAppearanceMode("system"); + }, + }; + const container = document.createElement("div"); + container.className = "flex h-[700px] w-[900px]"; + await using screen = await render( + {}} + environmentId={EnvironmentId.make("environment")} + reference={detail} + detail={{ + ...detail, + capabilities: { + ...detail.capabilities, + review: { ...detail.capabilities.review, reply: true }, + }, + viewerPermissions: { ...detail.viewerPermissions, comment: true }, + reviewThreads: [ + { + id: "thread", + path: "a.ts", + line: 3, + side: "right", + isResolved: false, + isOutdated: false, + comments: [ + { + id: "comment", + author: { login: "reviewer", name: null, avatarUrl: null }, + body: "Rename this.", + createdAt: "2026-09-01T00:00:00Z", + url: null, + }, + ], + }, + ], + }} + selectedCommitOid={null} + onSelectedCommitChange={() => {}} + onRefresh={() => {}} + />, + { container }, + ); + const reply = () => screen.getByRole("textbox", { name: "Reply to this conversation" }); + await screen.getByRole("button", { name: "Reply", exact: true }).click(); + await reply().fill("Unsent"); + + setAppearanceMode("light"); + + await expect.element(reply()).toHaveValue("Unsent"); +}); diff --git a/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx b/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx index 454cdaafcbf3..573a7bfb2798 100644 --- a/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx +++ b/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx @@ -651,11 +651,7 @@ function PullRequestCodeTab({ parsedSlices, loadedFiles: pagedFiles, sourceFileStats, - } = diffModel( - loadedSlices, - `pull-request:${scopeKey}:${resolvedTheme}:${ignoreWhitespace}`, - ignoreWhitespace, - ); + } = diffModel(loadedSlices, `pull-request:${scopeKey}:${ignoreWhitespace}`, ignoreWhitespace); const withheldResults = useAtomValue( withheldFileDiffsAtom( JSON.stringify({ environmentId, input: withheldInput, paths: withheldPaths }), @@ -684,7 +680,7 @@ function PullRequestCodeTab({ nextCursor: null, omittedFileStats: [], }, - `pull-request:${scopeKey}:${resolvedTheme}:withheld:${path}`, + `pull-request:${scopeKey}:withheld:${path}`, // Cut lines can match up to the cut and differ after it; hiding them would drop changes. false, ); From f79ab79721e3dc49cf738b7dc840e79282c3eca9 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 17 Nov 2026 00:33:18 -0800 Subject: [PATCH 005/133] fix(web): stopped or expired questions return their attached files to the composer (#38005) --- .../src/state/thread-task-permissions.test.ts | 48 +++++++++++++++++-- .../src/state/use-selected-thread-requests.ts | 37 ++++++++++++-- apps/web/src/questionAttachments.test.ts | 34 ++++++++++++- apps/web/src/questionAttachments.ts | 48 ++++++++++++++++--- 4 files changed, 152 insertions(+), 15 deletions(-) diff --git a/apps/mobile/src/state/thread-task-permissions.test.ts b/apps/mobile/src/state/thread-task-permissions.test.ts index 7051193be117..9b47cdcfef69 100644 --- a/apps/mobile/src/state/thread-task-permissions.test.ts +++ b/apps/mobile/src/state/thread-task-permissions.test.ts @@ -1,12 +1,14 @@ import { AuthOrchestrationOperateScope, DEFAULT_SERVER_SETTINGS, + EnvironmentId, MessageId, ProjectId, ProviderDriverKind, ProviderInstanceId, RunId, RuntimeRequestId, + ThreadId, TurnItemId, type ModelSelection, type OrchestrationV2ThreadProjection, @@ -19,7 +21,10 @@ import { } from "../../../../packages/client-runtime/src/state/orchestrationV2TestFixtures"; import type { DraftComposerImageAttachment } from "../lib/composerImages"; import type { PendingThreadRequests } from "@t3tools/client-runtime/state/thread-requests"; -import { sendApprovalFeedback } from "@t3tools/client-runtime/state/thread-requests"; +import { + makeThreadRequestsResolvedAnnouncer, + sendApprovalFeedback, +} from "@t3tools/client-runtime/state/thread-requests"; import { DateTime } from "effect"; import { AsyncResult, type Atom } from "effect/reactivity"; import { beforeEach, describe, expect, it, vi } from "vite-plus/test"; @@ -42,6 +47,11 @@ const state = vi.hoisted(() => ({ compactDueAt: "", setFreshPending: vi.fn(), clearDraft: vi.fn(), + appendAttachments: vi.fn(), + questionDrafts: {} as Record< + string, + { text: string; attachments: DraftComposerImageAttachment[] } + >, approve: vi.fn(), answer: vi.fn(), feedback: vi.fn(), @@ -168,13 +178,13 @@ vi.mock("./use-composer-drafts", async () => { updateComposerDraftSettings: state.updateSettings, ensureComposerDraftsLoaded: () => {}, scheduleUnusedComposerAttachmentCleanup: () => {}, - appendComposerDraftAttachments: vi.fn(), + appendComposerDraftAttachments: state.appendAttachments, appendComposerDraftText: vi.fn(), mergeComposerDraftContent: vi.fn(), removeComposerDraftAttachment: vi.fn(), useComposerDraft: () => state.draft, useComposerDraftSettings: () => state.draft, - questionAttachmentDraftsAtom: () => Atom.make({}), + questionAttachmentDraftsAtom: () => Atom.make(state.questionDrafts), }; }); vi.mock("../lib/composerImages", () => ({ @@ -195,6 +205,7 @@ vi.mock("./use-remote-environment-registry", () => ({ setPendingConnectionError: import { Alert } from "react-native"; import { useThreadComposerState } from "./use-thread-composer-state"; import { useSelectedThreadRequests } from "./use-selected-thread-requests"; +import { questionAttachmentDraftKey } from "./question-attachments"; const NO_SIDE_CHATS = { startSideChat: async () => false }; @@ -208,6 +219,7 @@ beforeEach(() => { runtimeMode: undefined, }; state.freshPending = false; + state.questionDrafts = {}; state.compactModel = null; state.compactDueAt = ""; state.thread.latestRun = null; @@ -506,6 +518,36 @@ describe("mobile task permissions", () => { }); }); +it.each(["cancelled", "expired"] as const)( + "returns unsent attachments to the thread composer when a question is %s", + (status) => { + const environmentId = EnvironmentId.make("secondary"); + const threadId = ThreadId.make("thread"); + const notes = { + id: "notes", + type: "file", + name: "notes.txt", + mimeType: "text/plain", + sizeBytes: 5, + } as unknown as DraftComposerImageAttachment; + state.questionDrafts = { + [questionAttachmentDraftKey(environmentId, threadId, "input", "language")]: { + text: "", + attachments: [notes], + }, + }; + makeThreadRequestsResolvedAnnouncer( + environmentId, + threadId, + )([{ id: RuntimeRequestId.make("input"), status }]); + expect(state.appendAttachments).toHaveBeenCalledWith( + "secondary:thread", + [notes], + expect.objectContaining({ appendReference: true }), + ); + }, +); + describe("mobile handoff preview and submission", () => { it("follows project enablement and provider availability for the selected destination", async () => { state.grantedEnvironments.add("secondary"); diff --git a/apps/mobile/src/state/use-selected-thread-requests.ts b/apps/mobile/src/state/use-selected-thread-requests.ts index 776a3faf51c9..1492201cf643 100644 --- a/apps/mobile/src/state/use-selected-thread-requests.ts +++ b/apps/mobile/src/state/use-selected-thread-requests.ts @@ -5,9 +5,12 @@ import { questionAttachmentDraftPrefix, questionAttachmentPreparationAtom, } from "./question-attachments"; +import { scopedThreadKey } from "../lib/scopedEntities"; import { + appendComposerDraftAttachments, clearComposerDraft, composerDraftsAtom, + getComposerDraftSnapshot, questionAttachmentDraftsAtom, } from "./use-composer-drafts"; import { @@ -134,11 +137,39 @@ function pruneResolvedRequestDrafts( if (changed) appAtomRegistry.set(questionAttachmentPreparationAtom, counts); } +/** + * Stop cancels an open question and a provider timeout expires it; neither sent + * its attachments, so they move to the thread's own draft before pruning. + */ +function returnUnsentAttachmentsToThreadDraft( + environmentId: EnvironmentId, + threadId: ThreadId, + unansweredRequestIds: ReadonlyArray, +): void { + if (unansweredRequestIds.length === 0) return; + const prefix = questionAttachmentDraftPrefix(environmentId, threadId); + const drafts = appAtomRegistry.get(questionAttachmentDraftsAtom(prefix)); + const otherRequestKeys = new Set( + resolvedQuestionDraftKeys(Object.keys(drafts), prefix, unansweredRequestIds), + ); + const attachments = Object.entries(drafts).flatMap(([key, draft]) => + otherRequestKeys.has(key) ? [] : draft.attachments, + ); + const threadKey = scopedThreadKey(environmentId, threadId); + const { text } = getComposerDraftSnapshot(threadKey); + // Chips go after the draft's text, never over a selection the user left in it. + appendComposerDraftAttachments(threadKey, attachments, { + appendReference: true, + insertion: { text, start: text.length, end: text.length }, + }); +} + // Resolution can come from anywhere: another device, an interrupt, the turn // ending, or a reload over drafts for requests that resolved meanwhile. -onThreadRequestsResolved(({ environmentId, threadId, pendingRequestIds }) => - pruneResolvedRequestDrafts(environmentId, threadId, pendingRequestIds), -); +onThreadRequestsResolved(({ environmentId, threadId, pendingRequestIds, unansweredRequestIds }) => { + returnUnsentAttachmentsToThreadDraft(environmentId, threadId, unansweredRequestIds); + pruneResolvedRequestDrafts(environmentId, threadId, pendingRequestIds); +}); /** * Drops `answeredRequestId`'s drafts as soon as the server accepts the diff --git a/apps/web/src/questionAttachments.test.ts b/apps/web/src/questionAttachments.test.ts index 2ca477b4212e..b7d8dd8ee4ac 100644 --- a/apps/web/src/questionAttachments.test.ts +++ b/apps/web/src/questionAttachments.test.ts @@ -169,9 +169,36 @@ it.each(["cancelled", "expired"] as const)( ); const answer = `Purple, like ${formatInlineContextReference(threadContextReference(reference))}`; store.setPrompt({ environmentId, threadId }, "Earlier draft"); - store.setThreadContexts(questionAttachmentDraftId(environmentId, threadId, request, "first"), [ - reference, + const questionDraft = questionAttachmentDraftId(environmentId, threadId, request, "first"); + store.setThreadContexts(questionDraft, [reference]); + store.addFiles(questionDraft, [ + { + type: "file", + id: "notes", + name: "notes.txt", + mimeType: "text/plain", + sizeBytes: 5, + file: new File(["notes"], "notes.txt", { type: "text/plain" }), + }, ]); + const photo = { + type: "image" as const, + id: "photo", + name: "photo.png", + mimeType: "image/png", + sizeBytes: 5, + previewUrl: "blob:photo", + file: new File(["photo"], "photo.png", { type: "image/png" }), + }; + store.addImages(questionDraft, [photo]); + const savedPhoto = { + id: "photo", + name: "photo.png", + mimeType: "image/png", + sizeBytes: 5, + dataUrl: "data:image/png;base64,cGhvdG8=", + }; + void store.syncPersistedAttachments(questionDraft, [savedPhoto]); usePendingUserInputAnswers.setState({ [userInputDraftKey(environmentId, threadId, request)]: { first: { customAnswer: answer }, @@ -185,6 +212,9 @@ it.each(["cancelled", "expired"] as const)( expect(store.getComposerDraft({ environmentId, threadId })).toMatchObject({ prompt: `Earlier draft\n\n${answer}\n\nAlso this`, threadContexts: [reference], + files: [expect.objectContaining({ name: "notes.txt" })], + images: [expect.objectContaining({ id: "photo" })], + persistedAttachments: [savedPhoto], }); expect(usePendingUserInputAnswers.getState()).toEqual({}); }, diff --git a/apps/web/src/questionAttachments.ts b/apps/web/src/questionAttachments.ts index 712bd537b3ba..b024a390cd66 100644 --- a/apps/web/src/questionAttachments.ts +++ b/apps/web/src/questionAttachments.ts @@ -99,13 +99,19 @@ export function changeQuestionAttachmentPreparation(key: DraftId, delta: number) ); } -export function clearQuestionAttachmentDraft(key: DraftId): void { +/** Releases the draft's attachments except `keepIds`, which have moved to another draft. */ +export function clearQuestionAttachmentDraft( + key: DraftId, + keepIds: ReadonlySet = new Set(), +): void { const store = useComposerDraftStore.getState(); const draft = store.getComposerDraft(key); if (draft) { - releaseDraftAttachments([...draft.images, ...draft.files]); + releaseDraftAttachments([...draft.images, ...draft.files].filter(({ id }) => !keepIds.has(id))); for (const image of draft.images) { - if (image.previewUrl.startsWith("blob:")) URL.revokeObjectURL(image.previewUrl); + if (!keepIds.has(image.id) && image.previewUrl.startsWith("blob:")) { + URL.revokeObjectURL(image.previewUrl); + } } } store.clearComposerContent(key); @@ -135,7 +141,8 @@ function pruneResolvedQuestionAttachmentDrafts( /** * Stop cancels an open question and a provider timeout expires it; neither sent * the typed answers, so they move to the thread's own draft (not a queued-message - * edit the composer may be showing) with the thread chips they reference. + * edit the composer may be showing) with the thread chips they reference and + * every file or image attached to them. */ function returnUnsentAnswersToThreadDraft( environmentId: EnvironmentId, @@ -165,9 +172,36 @@ function returnUnsentAnswersToThreadDraft( ); } } - if (prompt === currentPrompt) return; - store.setPrompt(target, prompt); - store.addThreadContexts(target, threadContexts, { appendReference: false }); + if (prompt !== currentPrompt) { + store.setPrompt(target, prompt); + store.addThreadContexts(target, threadContexts, { appendReference: false }); + } + + const threadPrefix = questionAttachmentDraftPrefix(environmentId, threadId); + const requestPrefixes = unansweredRequestIds.map( + (requestId) => + `${threadPrefix}${encodeURIComponent(`${JSON.stringify([requestId]).slice(0, -1)},`)}`, + ); + const questionDrafts = Object.entries(store.draftsByThreadKey).filter(([key]) => + requestPrefixes.some((requestPrefix) => key.startsWith(requestPrefix)), + ); + const images = questionDrafts.flatMap(([, draft]) => draft.images); + const files = questionDrafts.flatMap(([, draft]) => draft.files); + if (images.length === 0 && files.length === 0) return; + store.addImages(target, images); + store.addFiles(target, files); + const moved = useComposerDraftStore.getState().getComposerDraft(target); + const movedIds = new Set([...(moved?.images ?? []), ...(moved?.files ?? [])].map(({ id }) => id)); + // Only a mounted composer re-serializes images, so carry their saved copies for a reload. + const persisted = moved?.persistedAttachments ?? []; + const persistedIds = new Set(persisted.map(({ id }) => id)); + const movedPersisted = questionDrafts + .flatMap(([, draft]) => draft.persistedAttachments) + .filter(({ id }) => movedIds.has(id) && !persistedIds.has(id)); + if (movedPersisted.length > 0) { + void store.syncPersistedAttachments(target, [...persisted, ...movedPersisted]); + } + for (const [key] of questionDrafts) clearQuestionAttachmentDraft(DraftId.make(key), movedIds); } // Resolution can come from anywhere: another device, an interrupt, the turn From 17c142588b090a30ed33439375113891668982b8 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 17 Nov 2026 00:42:40 -0800 Subject: [PATCH 006/133] fix(server): remove one-time scheduled tasks after their turn completes (#37991) --- .../ScheduledTaskService.test.ts | 71 +++++++++++++++++++ .../scheduledTasks/ScheduledTaskService.ts | 23 +++--- 2 files changed, 86 insertions(+), 8 deletions(-) diff --git a/apps/server/src/scheduledTasks/ScheduledTaskService.test.ts b/apps/server/src/scheduledTasks/ScheduledTaskService.test.ts index 1335e369484a..3edf786b15ec 100644 --- a/apps/server/src/scheduledTasks/ScheduledTaskService.test.ts +++ b/apps/server/src/scheduledTasks/ScheduledTaskService.test.ts @@ -509,6 +509,77 @@ it.effect.each([ }).pipe(Effect.provide(SqlitePersistence.layerMemory)), ); +it.effect("a one-time task is removed once its turn completes", () => + Effect.gen(function* () { + yield* TestClock.setTime(Date.parse("2026-11-01T07:00:00.000Z")); + const projectId = ProjectId.make("project:test"); + const ended = yield* Deferred.make(); + const sent = yield* Ref.make(""); + const run = { id: "run:1", status: "completed", rootNodeId: "node:root" }; + const layer = ScheduledTaskService.layer.pipe( + Layer.provide( + Layer.mergeAll( + ManagedPolicy.layerTest(), + Layer.mock(ThreadLaunchService.ThreadLaunchService)({}), + Layer.mock(ThreadManagementService.ThreadManagementService)({ + sendToThread: (input) => Ref.set(sent, input.messageId).pipe(Effect.as({} as never)), + getThreadShell: () => Effect.succeed(threadShell(projectId)), + getProjectThreadRecords: () => + Effect.map( + Ref.get(sent), + (userMessageId) => ({ runs: [{ ...run, userMessageId }] }) as never, + ), + waitForThread: (input) => + Deferred.await(ended).pipe( + Effect.as({ threadId: input.threadId, run, timedOut: false } as never), + ), + }), + Layer.mock(SecretRequests.SecretRequests)({}), + Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({ + namedProjectsRoot: "/projects", + isScratchProject: () => Effect.succeed(false), + }), + NodeCrypto.layer, + Scheduler.layer, + ), + ), + ); + yield* Effect.gen(function* () { + const service = yield* ScheduledTaskService.ScheduledTaskService; + const { task } = yield* service.upsert({ + id: ScheduledTaskId.make("task:once"), + title: "Release notes", + prompt: "Draft the release notes", + enabled: true, + schedule: { type: "once", runAt: "2026-11-01T07:01:00.000Z" }, + projectId, + threadId: ThreadId.make("thread:once"), + workspaceStrategy: { type: "root" }, + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" }, + runtimeMode: "full-access", + interactionMode: "default", + }); + const dispatched = service.subscribeList().pipe( + Stream.map(({ tasks }) => tasks.find((candidate) => candidate.id === task.id)), + Stream.filter((current) => current?.lastRunStatus === "succeeded"), + Stream.runHead, + ); + const removed = service.subscribeList().pipe( + Stream.filter(({ tasks }) => tasks.every((candidate) => candidate.id !== task.id)), + Stream.runHead, + ); + const recorded = yield* Effect.forkChild(dispatched); + const gone = yield* Effect.forkChild(removed); + yield* TestClock.adjust("2 minutes"); + // The dispatch alone keeps it: the turn can still fail. + assert.isNull(Option.getOrThrow(yield* Fiber.join(recorded))?.nextRunAt); + yield* Deferred.succeed(ended, undefined); + yield* Fiber.join(gone); + assert.lengthOf((yield* service.list()).tasks, 0); + }).pipe(Effect.provide(layer)); + }).pipe(Effect.provide(SqlitePersistence.layerMemory)), +); + it.effect("a bound run follows its thread when promotion moves it mid-send", () => Effect.gen(function* () { const scratch = ProjectId.make("project:scratch"); diff --git a/apps/server/src/scheduledTasks/ScheduledTaskService.ts b/apps/server/src/scheduledTasks/ScheduledTaskService.ts index 9ed134be2da5..17840c50bf49 100644 --- a/apps/server/src/scheduledTasks/ScheduledTaskService.ts +++ b/apps/server/src/scheduledTasks/ScheduledTaskService.ts @@ -884,8 +884,9 @@ export const layer = Layer.effect( ); // A dispatch is recorded once the message is accepted; the provider can still - // reject the turn after that, so follow the run and record its failure. - const recordRunFailure = Effect.fn("ScheduledTaskService.recordRunFailure")(function* ( + // reject the turn after that, so follow the run and record its failure. A one-time + // task whose turn completed is spent, so it is removed; its thread stays. + const recordRunOutcome = Effect.fn("ScheduledTaskService.recordRunOutcome")(function* ( taskId: ScheduledTaskId, startedAtIso: string, threadId: ThreadId, @@ -902,12 +903,18 @@ export const layer = Layer.effect( runId: dispatched.id, timeoutMs: RUN_OUTCOME_WAIT_MS, }); - if ( - run === null || - run.status === "completed" || - !ThreadManagementService.isTerminalRunStatus(run.status) - ) + if (run === null || !ThreadManagementService.isTerminalRunStatus(run.status)) return; + if (run.status === "completed") { + const removed = yield* sql` + DELETE FROM scheduled_tasks + WHERE task_id = ${taskId} AND last_run_at = ${startedAtIso} + AND last_run_status = 'succeeded' AND next_run_at IS NULL + AND json_extract(schedule_json, '$.type') = 'once' + RETURNING task_id + `; + if (removed.length > 0) yield* notifyChanged; return; + } const { turnItems, messages } = yield* threadManagement.getProjectThreadRecords(thread, [ "turnItems", "messages", @@ -1176,7 +1183,7 @@ export const layer = Layer.effect( ); if (written) yield* notifyChanged; if (written && threadId !== null) { - yield* recordRunFailure(active.id, startedAtIso, threadId, messageId).pipe( + yield* recordRunOutcome(active.id, startedAtIso, threadId, messageId).pipe( Effect.catchCause((cause) => Effect.logWarning("Could not record scheduled run outcome", { taskId: active.id, From b78914e4f3d4813990014316c3f8d1f902a75d6d Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Tue, 17 Nov 2026 09:56:56 +0100 Subject: [PATCH 007/133] fix(client-runtime): Linear filters keep their choices when a search has no matches (#37971) Co-authored-by: Julius Marminge --- apps/server/src/issue/IssueService.test.ts | 6 ++++ apps/server/src/issue/IssueService.ts | 6 ++++ packages/client-runtime/src/issueList.test.ts | 13 ++++++++ packages/client-runtime/src/issueList.ts | 30 ++++++++++--------- packages/contracts/src/issue.ts | 5 ++++ 5 files changed, 46 insertions(+), 14 deletions(-) diff --git a/apps/server/src/issue/IssueService.test.ts b/apps/server/src/issue/IssueService.test.ts index fd6f7b2f0a0c..ccbeb8727972 100644 --- a/apps/server/src/issue/IssueService.test.ts +++ b/apps/server/src/issue/IssueService.test.ts @@ -467,6 +467,12 @@ describe("IssueService with a standalone tracker", () => { ["github", "github.com"], ["linear", "linear.app"], ]); + expect(result.scopes).toContainEqual({ + projectId: "web", + tracker: "linear", + host: "linear.app", + scope: "ENG", + }); // A reference picks the project's tracker by kind; both are the project's own, so writable. const linearRef = { projectId: "web" as ProjectId, diff --git a/apps/server/src/issue/IssueService.ts b/apps/server/src/issue/IssueService.ts index a53aeb698ce8..e2312582dbc1 100644 --- a/apps/server/src/issue/IssueService.ts +++ b/apps/server/src/issue/IssueService.ts @@ -424,6 +424,12 @@ const make = Effect.gen(function* () { entries, errors, nextCursors, + scopes: [...scopes.values()].map((project) => ({ + projectId: project.project.id, + tracker: project.tracker, + host: project.host, + scope: project.scope, + })), }; }); diff --git a/packages/client-runtime/src/issueList.test.ts b/packages/client-runtime/src/issueList.test.ts index 3923519abf06..591c41087656 100644 --- a/packages/client-runtime/src/issueList.test.ts +++ b/packages/client-runtime/src/issueList.test.ts @@ -130,6 +130,19 @@ describe("issueFilterScopes", () => { ]); }); + it("offers a bound tracker's scope the answer names when a search matches nothing", () => { + const scope = { + projectId: api, + tracker: "linear" as IssueTrackerKind, + host: "linear.app", + scope: "ENG", + }; + const held = new Map([ + [environmentId, hold(answer({ trackers: [tracker({})], entries: [], scopes: [scope] }))], + ]); + expect(issueFilterScopes(held, [])).toEqual([{ environmentId, input: scope }]); + }); + it("skips a tracker that cannot be read", () => { const held = new Map([ [ diff --git a/packages/client-runtime/src/issueList.ts b/packages/client-runtime/src/issueList.ts index c1ade3fc9002..34d421231382 100644 --- a/packages/client-runtime/src/issueList.ts +++ b/packages/client-runtime/src/issueList.ts @@ -189,30 +189,32 @@ export function issueFilterScopes( input: { projectId: project.id, tracker: tracker.tracker, host, scope }, }); } - // A tracker bound in settings (a Linear team) is no repository's; its rows name its scope. - for (const entry of page.entries) { + // A tracker bound in settings (a Linear team) is no repository's; the answer names its scope, + // matched or not. Older servers do not, so their rows stand in. + const covered: ReadonlyArray = + page.answer.scopes ?? + page.entries.map(({ projectId, tracker, host, scope }) => ({ + projectId, + tracker, + host, + scope, + })); + for (const input of covered) { + const host = input.host?.toLowerCase(); const tracker = page.answer.trackers.find( - (t) => t.tracker === entry.tracker && t.host.toLowerCase() === entry.host.toLowerCase(), + (t) => t.tracker === input.tracker && t.host.toLowerCase() === host, ); if (!tracker?.configured) continue; if (!tracker.capabilities?.labels && !tracker.capabilities?.assignees) continue; if ( scopes.some( (s) => - s.input.scope.toLowerCase() === entry.scope.toLowerCase() && - s.input.host?.toLowerCase() === entry.host.toLowerCase(), + s.input.scope.toLowerCase() === input.scope.toLowerCase() && + s.input.host?.toLowerCase() === host, ) ) continue; - scopes.push({ - environmentId, - input: { - projectId: entry.projectId, - tracker: entry.tracker, - host: entry.host, - scope: entry.scope, - }, - }); + scopes.push({ environmentId, input }); } } return scopes; diff --git a/packages/contracts/src/issue.ts b/packages/contracts/src/issue.ts index b2fc5532dac4..acd0eed54a42 100644 --- a/packages/contracts/src/issue.ts +++ b/packages/contracts/src/issue.ts @@ -308,6 +308,11 @@ export const IssueListResult = Schema.Struct({ errors: Schema.Array(IssueListProjectError), /** Where each scope carries on, sent straight back as `cursors`. Absent once a scope is done. */ nextCursors: IssueListCursors, + /** + * Every scope the listing covers, matched or not, with one project that reads it. A Linear team + * bound in settings is named nowhere else. Absent from servers that predate it. + */ + scopes: Schema.optional(Schema.Array(IssueScopeRef)), }); export type IssueListResult = typeof IssueListResult.Type; From 9bc3fda0ac28020977c8adc89422c2d6c6c0e907 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 17 Nov 2026 01:02:19 -0800 Subject: [PATCH 008/133] fix(azure-devops): pull requests show their labels (#38018) --- .../server/AzureDevOpsPullRequestCli.test.ts | 9 +++-- .../src/server/AzureDevOpsPullRequestCli.ts | 19 +++++++++++ .../AzureDevOpsPullRequestProvider.test.ts | 5 +++ .../server/AzureDevOpsPullRequestProvider.ts | 10 ++++-- .../server/azureDevOpsPullRequestJson.test.ts | 11 ++++++- .../src/server/azureDevOpsPullRequestJson.ts | 33 +++++++++++++++++++ 6 files changed, 82 insertions(+), 5 deletions(-) diff --git a/packages/source-control-azure-devops/src/server/AzureDevOpsPullRequestCli.test.ts b/packages/source-control-azure-devops/src/server/AzureDevOpsPullRequestCli.test.ts index 1a2c34d8f0e0..156caac9e7a5 100644 --- a/packages/source-control-azure-devops/src/server/AzureDevOpsPullRequestCli.test.ts +++ b/packages/source-control-azure-devops/src/server/AzureDevOpsPullRequestCli.test.ts @@ -189,7 +189,10 @@ layer("AzureDevOpsPullRequestCli.layer", (it) => { ), ) .mockReturnValueOnce(Effect.succeed(output(json({ changeEntries: [] })))) - .mockReturnValueOnce(Effect.succeed(output("[]"))); + .mockReturnValueOnce(Effect.succeed(output("[]"))) + .mockReturnValueOnce( + Effect.succeed(output(json({ count: 1, value: [{ id: "4f1c", name: "release-1.0" }] }))), + ); const provider = yield* AzureDevOpsPullRequestProvider.make; const detail = yield* provider.getChangeRequest({ cwd: "/w", @@ -200,7 +203,9 @@ layer("AzureDevOpsPullRequestCli.layer", (it) => { expect(detail.headSha).toBe(latestHead); expect(argsOfCall(2)).toContain("iterationId=2"); - expect(mockedExecute).toHaveBeenCalledTimes(4); + expect(argsOfCall(4)).toContain("pullRequestLabels"); + expect(detail.labels).toEqual([{ name: "release-1.0", color: null }]); + expect(mockedExecute).toHaveBeenCalledTimes(5); }), ); diff --git a/packages/source-control-azure-devops/src/server/AzureDevOpsPullRequestCli.ts b/packages/source-control-azure-devops/src/server/AzureDevOpsPullRequestCli.ts index 7ed77ab5a4ec..98d94953530f 100644 --- a/packages/source-control-azure-devops/src/server/AzureDevOpsPullRequestCli.ts +++ b/packages/source-control-azure-devops/src/server/AzureDevOpsPullRequestCli.ts @@ -9,6 +9,7 @@ import type { PullRequestCheck, PullRequestComment, PullRequestInvolvement, + PullRequestLabel, PullRequestListState, PullRequestMergeMethod, } from "@t3tools/contracts"; @@ -21,6 +22,7 @@ import { decodeItemContentJson, decodeIterationChangesJson, decodeIterationsJson, + decodeLabelsJson, decodePolicyChecksJson, decodePullRequestJson, decodePullRequestListJson, @@ -186,6 +188,13 @@ export class AzureDevOpsPullRequestCli extends Context.Service< readonly number: number; }) => Effect.Effect, AzureDevOpsPullRequestCliError>; + /** `az repos pr show` returns null labels, so the detail reads them here. */ + readonly listLabels: (input: { + readonly cwd: string; + readonly location: AzureDevOpsRepositoryLocation; + readonly number: number; + }) => Effect.Effect, AzureDevOpsPullRequestCliError>; + readonly listIterations: (input: { readonly cwd: string; readonly location: AzureDevOpsRepositoryLocation; @@ -627,6 +636,16 @@ export const make = Effect.gen(function* () { }); }), + listLabels: Effect.fn("AzureDevOpsPullRequestCli.listLabels")(function (input) { + return invoke({ + cwd: input.cwd, + operation: "listLabels", + resource: "pullRequestLabels", + routeParameters: pullRequestRoute(input), + decode: decodeLabelsJson, + }); + }), + listIterations: Effect.fn("AzureDevOpsPullRequestCli.listIterations")(function (input) { return invoke({ cwd: input.cwd, diff --git a/packages/source-control-azure-devops/src/server/AzureDevOpsPullRequestProvider.test.ts b/packages/source-control-azure-devops/src/server/AzureDevOpsPullRequestProvider.test.ts index 82917a307b82..83cda1bff15b 100644 --- a/packages/source-control-azure-devops/src/server/AzureDevOpsPullRequestProvider.test.ts +++ b/packages/source-control-azure-devops/src/server/AzureDevOpsPullRequestProvider.test.ts @@ -39,6 +39,7 @@ const PULL_REQUEST = { body: "", reviewRequestLogins: [], reviewers: [], + labels: [], location: { project: "acme", repository: "web" }, autoMergeEnabled: false, }; @@ -138,6 +139,7 @@ describe("getChangeRequest", () => { Layer.mock(AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli)({ getPullRequest: () => Effect.succeed(PULL_REQUEST), listPolicyChecks: () => Effect.succeed([]), + listLabels: () => Effect.succeed([]), listIterations: () => Effect.succeed([ITERATION, { ...ITERATION, id: 4, headCommit: "new-head" }]), listIterationChanges: () => @@ -173,6 +175,7 @@ describe("getChangeRequest", () => { Layer.mock(AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli)({ getPullRequest: () => Effect.succeed(PULL_REQUEST), listPolicyChecks: () => Effect.succeed([]), + listLabels: () => Effect.succeed([]), listIterations: () => state === "missing" ? Effect.succeed([]) @@ -218,6 +221,7 @@ describe("getChangeRequest", () => { Effect.succeed({ contents: side("new", 2, 4), isBinary: false }), ...NO_BLOBS, listPolicyChecks: () => Effect.succeed([]), + listLabels: () => Effect.succeed([]), listThreads: () => Effect.succeed([]), }), ), @@ -273,6 +277,7 @@ describe("policy checks", () => { listIterations: () => Effect.succeed([ITERATION]), listIterationChanges: () => Effect.succeed({ changes: [], truncated: false }), listPolicyChecks, + listLabels: () => Effect.succeed([]), }), ), ); diff --git a/packages/source-control-azure-devops/src/server/AzureDevOpsPullRequestProvider.ts b/packages/source-control-azure-devops/src/server/AzureDevOpsPullRequestProvider.ts index 8c29f529a749..b329561c3636 100644 --- a/packages/source-control-azure-devops/src/server/AzureDevOpsPullRequestProvider.ts +++ b/packages/source-control-azure-devops/src/server/AzureDevOpsPullRequestProvider.ts @@ -149,8 +149,7 @@ function toChangeRequest(pullRequest: AzureDevOpsPullRequest): ProviderChangeReq mergedAt: pullRequest.state === "merged" ? pullRequest.closedAt : null, updatedAt: pullRequest.updatedAt, reviewRequestLogins: pullRequest.reviewRequestLogins, - // Azure keeps labels on work items rather than on the pull request. - labels: [], + labels: pullRequest.labels, }; } @@ -465,8 +464,15 @@ export const make = Effect.gen(function* () { Effect.orElseSucceed(() => 0), ); const checks = yield* readChecks(input, pullRequest).pipe(Effect.orElseSucceed(() => [])); + const labels = + location === null + ? pullRequest.labels + : yield* cli + .listLabels({ cwd: input.cwd, location, number: input.number }) + .pipe(Effect.orElseSucceed(() => pullRequest.labels)); const detail: ProviderChangeRequestDetail = { ...toChangeRequest(pullRequest), + labels, body: pullRequest.body, ...(headSha === undefined ? {} : { headSha }), changedFiles, diff --git a/packages/source-control-azure-devops/src/server/azureDevOpsPullRequestJson.test.ts b/packages/source-control-azure-devops/src/server/azureDevOpsPullRequestJson.test.ts index cdd86e31b830..48cc27b00e00 100644 --- a/packages/source-control-azure-devops/src/server/azureDevOpsPullRequestJson.test.ts +++ b/packages/source-control-azure-devops/src/server/azureDevOpsPullRequestJson.test.ts @@ -42,7 +42,15 @@ const asJson = (value: unknown) => JSON.stringify(value); describe("decodePullRequestListJson", () => { it("reads a pull request as a change request", () => { - const batch = expectSuccess(decodePullRequestListJson(asJson([pullRequest()]))); + const batch = expectSuccess( + decodePullRequestListJson( + asJson([ + pullRequest({ + labels: [{ id: "4f1c", name: "release-1.0", active: true, url: null }], + }), + ]), + ), + ); expect(batch.items).toHaveLength(1); expect(batch.items[0]).toMatchObject({ @@ -54,6 +62,7 @@ describe("decodePullRequestListJson", () => { state: "open", isDraft: false, mergeability: "mergeable", + labels: [{ name: "release-1.0" }], }); }); diff --git a/packages/source-control-azure-devops/src/server/azureDevOpsPullRequestJson.ts b/packages/source-control-azure-devops/src/server/azureDevOpsPullRequestJson.ts index aa05451452b7..40bdcf72c7fb 100644 --- a/packages/source-control-azure-devops/src/server/azureDevOpsPullRequestJson.ts +++ b/packages/source-control-azure-devops/src/server/azureDevOpsPullRequestJson.ts @@ -10,6 +10,7 @@ import type { PullRequestActor, PullRequestCheck, PullRequestComment, + PullRequestLabel, PullRequestMergeMethod, PullRequestMergeability, PullRequestState, @@ -26,6 +27,8 @@ const RawIdentitySchema = Schema.Struct({ imageUrl: Schema.optional(Schema.NullOr(Schema.String)), }); +const RawLabelSchema = Schema.Struct({ name: Schema.optional(Schema.NullOr(Schema.String)) }); + const RawPullRequestSchema = Schema.Struct({ pullRequestId: Schema.Int, title: Schema.String, @@ -45,6 +48,8 @@ const RawPullRequestSchema = Schema.Struct({ mergeStatus: Schema.optional(Schema.NullOr(Schema.String)), createdBy: Schema.optional(Schema.NullOr(RawIdentitySchema)), reviewers: Schema.optional(Schema.NullOr(Schema.Array(RawIdentitySchema))), + /** `az repos pr list` fills this; `az repos pr show` returns null. */ + labels: Schema.optional(Schema.NullOr(Schema.Array(RawLabelSchema))), sourceRefName: TrimmedNonEmptyString, targetRefName: TrimmedNonEmptyString, creationDate: TrimmedNonEmptyString, @@ -158,6 +163,7 @@ export interface AzureDevOpsPullRequest { readonly body: string; readonly reviewRequestLogins: ReadonlyArray; readonly reviewers: ReadonlyArray; + readonly labels: ReadonlyArray; readonly location: AzureDevOpsRepositoryLocation | null; readonly autoMergeEnabled: boolean; readonly autoMergeMethod?: PullRequestMergeMethod; @@ -171,6 +177,15 @@ function toActor(raw: Schema.Schema.Type | null | unde : { login, name: trimmed(raw?.displayName), avatarUrl: trimmed(raw?.imageUrl) }; } +function toLabels( + raw: ReadonlyArray> | null | undefined, +): ReadonlyArray { + return (raw ?? []).flatMap((label) => { + const name = trimmed(label.name); + return name === null ? [] : [{ name, color: null }]; + }); +} + function toState(raw: Schema.Schema.Type): PullRequestState { switch (raw.status?.trim().toLowerCase()) { case "completed": @@ -259,6 +274,7 @@ function toPullRequest( body: raw.description ?? "", reviewRequestLogins: reviewers.map((reviewer) => reviewer.login), reviewers, + labels: toLabels(raw.labels), location: toLocation(raw), autoMergeEnabled: (raw.autoCompleteSetBy ?? null) !== null, ...(autoMergeMethod === undefined ? {} : { autoMergeMethod }), @@ -271,6 +287,8 @@ const decodePullRequest = decodeJsonResult(RawPullRequestSchema); const decodeThreadPage = decodeJsonResult(RawThreadPageSchema); const decodeThreadEntry = Schema.decodeUnknownExit(RawThreadSchema); const decodeViewer = decodeJsonResult(RawViewerSchema); +const decodeLabelPage = decodeJsonResult(Schema.Struct({ value: Schema.Array(Schema.Unknown) })); +const decodeLabelEntry = Schema.decodeUnknownExit(RawLabelSchema); const decodePolicyEvaluations = decodeJsonResult(Schema.Array(RawPolicyEvaluationSchema)); type DecodeFailure = Cause.Cause; @@ -320,6 +338,21 @@ export function decodeViewerJson(raw: string): Result.Result, DecodeFailure> { + const decoded = decodeLabelPage(raw); + if (!Result.isSuccess(decoded)) return Result.fail(decoded.failure); + return Result.succeed( + toLabels( + decoded.success.value.flatMap((entry) => { + const label = decodeLabelEntry(entry); + return Exit.isFailure(label) ? [] : [label.value]; + }), + ), + ); +} + export function decodeThreadsJson( raw: string, ): Result.Result, DecodeFailure> { From 16548ab8a4a4af0e437845ee38091b4a95693be4 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 17 Nov 2026 01:11:11 -0800 Subject: [PATCH 009/133] fix(azure-devops): issue list loads work items through workitemsbatch (#38019) --- .../server/AzureDevOpsIssueTracker.test.ts | 54 ++++++++++++------- .../src/server/AzureDevOpsIssueTracker.ts | 27 +++++----- .../src/server/azureDevOpsIssueJson.ts | 2 +- 3 files changed, 49 insertions(+), 34 deletions(-) diff --git a/packages/source-control-azure-devops/src/server/AzureDevOpsIssueTracker.test.ts b/packages/source-control-azure-devops/src/server/AzureDevOpsIssueTracker.test.ts index 9cd89ca8a630..9c70956d3f6c 100644 --- a/packages/source-control-azure-devops/src/server/AzureDevOpsIssueTracker.test.ts +++ b/packages/source-control-azure-devops/src/server/AzureDevOpsIssueTracker.test.ts @@ -222,27 +222,41 @@ describe("AzureDevOpsIssueTracker", () => { const api = yield* AzureDevOpsIssueTracker.make.pipe( Effect.provide( Layer.mock(AzureDevOpsCli.AzureDevOpsCli)({ - execute: ({ args }) => - args[args.indexOf("--resource") + 1] === "wiql" - ? fs.readFileString(args[args.indexOf("--in-file") + 1]!).pipe( - Effect.orDie, - Effect.map((body) => { - bodies.push(body); - return TestSourceControlHost.processOutput( - encode({ workItems: [{ id: 9 }, { id: 7 }, { id: 3 }] }), - ); - }), - ) - : Effect.sync(() => { - if (args[args.indexOf("--resource") + 1] !== "workitems") { - return TestSourceControlHost.processOutput(answer(args)); - } - hydrated.push(args.find((arg) => arg.startsWith("ids=")) ?? ""); - // The page as REST answers it: an envelope, in an order of its own. + execute: ({ args }) => { + const resource = args[args.indexOf("--resource") + 1]; + if (resource === "workitems") { + // `az devops invoke` resolves `wit/workitems` to the create route + // (`.../workitems/${type}`) and fails before sending anything. + return Effect.fail( + new AzureDevOpsCli.AzureDevOpsCommandFailedError({ + operation: "execute", + command: "az", + cwd: "/w", + argumentCount: args.length, + cause: "KeyError: 'type'", + }), + ); + } + if (resource !== "wiql" && resource !== "workitemsbatch") { + return Effect.succeed(TestSourceControlHost.processOutput(answer(args))); + } + return fs.readFileString(args[args.indexOf("--in-file") + 1]!).pipe( + Effect.orDie, + Effect.map((body) => { + if (resource === "wiql") { + bodies.push(body); return TestSourceControlHost.processOutput( - encode({ count: 2, value: [WORK_ITEM, { ...WORK_ITEM, id: 9 }] }), + encode({ workItems: [{ id: 9 }, { id: 7 }, { id: 3 }] }), ); - }), + } + hydrated.push((JSON.parse(body) as { ids: number[] }).ids.join(",")); + // The page as REST answers it: an envelope, in an order of its own. + return TestSourceControlHost.processOutput( + encode({ count: 2, value: [WORK_ITEM, { ...WORK_ITEM, id: 9 }] }), + ); + }), + ); + }, }), ), ); @@ -260,7 +274,7 @@ describe("AzureDevOpsIssueTracker", () => { cursor: "2026-07-01T00:00:00Z|7", }); // The rows come back in WIQL's order, and the cursor is the last one of the page. - expect(hydrated).toEqual(["ids=9,7"]); + expect(hydrated).toEqual(["9,7"]); expect(page.items.map((item) => item.key)).toEqual(["9", "7"]); expect(page.nextCursor).toBe("2026-07-01T00:00:00Z|7"); expect(bodies).toHaveLength(1); diff --git a/packages/source-control-azure-devops/src/server/AzureDevOpsIssueTracker.ts b/packages/source-control-azure-devops/src/server/AzureDevOpsIssueTracker.ts index 78c52b32a5ff..e04d5149daf7 100644 --- a/packages/source-control-azure-devops/src/server/AzureDevOpsIssueTracker.ts +++ b/packages/source-control-azure-devops/src/server/AzureDevOpsIssueTracker.ts @@ -661,22 +661,23 @@ export const make: Effect.Effect< Effect.flatMap((ids) => ids.length === 0 ? Effect.succeed({ items: [], nextCursor: null }) - : read({ + : invokeWithBody({ cwd: input.cwd, operation: "listIssues", - args: invokeArgs({ - ...scope, - resource: "workitems", - query: [ - `ids=${ids - .slice(0, limit) - .map((row) => row.id) - .join(",")}`, - `fields=${LIST_FIELDS.join(",")}`, - ], - }), - decode: (raw) => decodeWorkItemsJson(raw, closed), + // az resolves `wit/workitems` to the create route (`workitems/${type}`) + // and fails before sending; `workitemsbatch` has a single route. + args: invokeArgs({ ...scope, resource: "workitemsbatch", method: "POST" }), + body: { + ids: ids.slice(0, limit).map((row) => row.id), + fields: LIST_FIELDS, + }, }).pipe( + Effect.flatMap((raw) => { + const decoded = decodeWorkItemsJson(raw, closed); + return Result.isSuccess(decoded) + ? Effect.succeed(decoded.success) + : Effect.fail(unreadable("listIssues", decoded.failure)); + }), Effect.map((hydrated) => { // The cursor is the last row WIQL sorted, so its order is restored. const position = new Map(ids.map((row, index) => [String(row.id), index])); diff --git a/packages/source-control-azure-devops/src/server/azureDevOpsIssueJson.ts b/packages/source-control-azure-devops/src/server/azureDevOpsIssueJson.ts index 9f2ffc27be71..6b932648d3a5 100644 --- a/packages/source-control-azure-devops/src/server/azureDevOpsIssueJson.ts +++ b/packages/source-control-azure-devops/src/server/azureDevOpsIssueJson.ts @@ -219,7 +219,7 @@ export function workItemStates( return states.some((state) => state.name === item.state.name) ? states : [...states, item.state]; } -/** The `{ count, value }` page `wit/workitems` answers; a row this cannot place is skipped. */ +/** The `{ count, value }` page `wit/workitemsbatch` answers; a row this cannot place is skipped. */ export function decodeWorkItemsJson( raw: string, closed: ClosedStates, From d6419d92a0e2b90202d147d77816ee35989f43ed Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Tue, 17 Nov 2026 10:11:23 +0100 Subject: [PATCH 010/133] fix(web): links to repeated headings work while a reply streams (#38017) Co-authored-by: Grok 4.7 Co-authored-by: Julius Marminge --- .../src/components/chat/markdownFragments.ts | 2 +- .../chat/markdownStreamBlocks.test.tsx | 50 ++++++++++++++++--- .../components/chat/markdownStreamBlocks.ts | 43 ++++++++++++++-- 3 files changed, 85 insertions(+), 10 deletions(-) diff --git a/apps/web/src/components/chat/markdownFragments.ts b/apps/web/src/components/chat/markdownFragments.ts index 90a419039053..9acacb8c65fe 100644 --- a/apps/web/src/components/chat/markdownFragments.ts +++ b/apps/web/src/components/chat/markdownFragments.ts @@ -68,7 +68,7 @@ type HeadingHastNode = { children?: HeadingHastNode[]; }; -function githubHeadingSlug(text: string): string { +export function githubHeadingSlug(text: string): string { return text .trim() .toLowerCase() diff --git a/apps/web/src/components/chat/markdownStreamBlocks.test.tsx b/apps/web/src/components/chat/markdownStreamBlocks.test.tsx index 2574f25fc043..38ecff766650 100644 --- a/apps/web/src/components/chat/markdownStreamBlocks.test.tsx +++ b/apps/web/src/components/chat/markdownStreamBlocks.test.tsx @@ -5,16 +5,25 @@ import { } from "@t3tools/shared/markdownPipeline"; import { renderToStaticMarkup } from "react-dom/server"; import ReactMarkdown from "react-markdown"; +import remarkMath from "remark-math"; +import type { PluggableList } from "unified"; import { describe, expect, it } from "vite-plus/test"; import { splitMarkdownBlocks } from "./markdownStreamBlocks"; +import { rehypeHeadingIds } from "./markdownFragments"; + +const MATH_PLUGINS: PluggableList = [[remarkMath, { singleDollarTextMath: true }]]; // Whitespace between top-level blocks collapses in the rendered message. -const html = (source: string) => +const renderMarkdown = (source: string, math = false) => renderToStaticMarkup( {source} , @@ -22,9 +31,27 @@ const html = (source: string) => .replace(/>\s+<") .trim(); +const html = (source: string) => renderMarkdown(source); + +const punctuatedHeadings = ["Step 1: Install", "Done:", "apps/web", "Fix (web)", "What's next?"]; + describe("splitMarkdownBlocks", () => { it.each([ "# Title\n\nFirst paragraph with `code` and **bold**.\n\nSecond [link](https://example.com).", + "## Step 1: Install\n\n## Step 1: Install\n\n[second](#step-1-install-1)", + "## /home/a/b.ts\n\n## home/a/b.ts", + "## see https://x.com/a\n\n## see httpsxcoma", + "## Done:\n\n## Done", + "## `Setup`\n\n## Setup", + "## a ` x ` b\n\n## a x b", + "# Setup\n\n# $$ Setup $$\n\n[second](#setup-1)", + "# Setup\n\n# Setup\n\n[Second setup](#setup-1)", + "\ufeff# Setup\n\n# Setup\n\n[second](#setup-1)", + "> Setup\n> ===\n\n> Setup\n> ===", + "# onetwo\n\none\ntwo\n===", + "# Setup\n\n# Setup\n\n[second](#setup-1)", + "# Setup\n\npara\n\n- a\n\n ```\n b\nx\n\nSetup\n===\n", + "Setup\n===\n\n> ## **Setup**\n\n- # [Setup](https://example.com)\n\n```sh\n# Setup\n```", "- one\n- two\n\n- loose three\n\n continued\n\nAfter the list.", "1. first\n\n2. second\n\nText\n\n3) restarted", "```ts\nconst a = 1;\n\n\nconst b = 2;\n```\n\nafter\n\n~~~\nx\n\n~~~~\n\ny\n~~~\n\nend", @@ -39,18 +66,29 @@ describe("splitMarkdownBlocks", () => { ])("renders each block as the whole text renders it, at every streamed prefix: %j", (text) => { for (let end = 0; end <= text.length; end++) { const source = text.slice(0, end); - const blocks = splitMarkdownBlocks(source); - expect(blocks?.join("")).toBe(source); - expect(blocks!.map(html).join("")).toBe(html(source)); + const blocks = splitMarkdownBlocks(source) ?? [source]; + expect(blocks.join("")).toBe(source); + expect(blocks.map(html).join("")).toBe(html(source)); + expect(blocks.map((block) => renderMarkdown(block, true)).join("")).toBe( + renderMarkdown(source, true), + ); } }); + it.each(punctuatedHeadings)("keeps splitting headings with prose punctuation: %s", (heading) => { + expect(splitMarkdownBlocks(`## ${heading}\n\nNext paragraph.`)).toEqual([ + `## ${heading}\n\n`, + "Next paragraph.", + ]); + }); + it("splits only between closed blocks", () => { expect(splitMarkdownBlocks("a\n\n```\nb\n\nc\n```\n\n- d\n\n- e\n\nf")).toEqual([ "a\n\n", "```\nb\n\nc\n```\n\n- d\n\n- e\n\n", "f", ]); + expect(splitMarkdownBlocks("a\n\n---\n\nb")).toEqual(["a\n\n", "---\n\n", "b"]); }); it.each([ diff --git a/apps/web/src/components/chat/markdownStreamBlocks.ts b/apps/web/src/components/chat/markdownStreamBlocks.ts index 107d5d0143c7..36decaa30183 100644 --- a/apps/web/src/components/chat/markdownStreamBlocks.ts +++ b/apps/web/src/components/chat/markdownStreamBlocks.ts @@ -1,3 +1,5 @@ +import { githubHeadingSlug } from "./markdownFragments"; + // Definitions, footnotes, raw HTML, container directives and display math can tie blocks together. const DOCUMENT_WIDE_SYNTAX = /^ {0,3}(?:\[[^\]\n]+\]:|<[A-Za-z!?/]|:::|\$\$)|\[\^/m; // A backtick fence's info string cannot contain a backtick, so "```a``` is inline" is a code span. @@ -7,13 +9,22 @@ const CONTINUATION_PATTERN = /^(?:[ \t]|(?:[-*+]|\d{1,9}[.)])(?:[ \t]|$))/; // Claude insight fences render as one callout, so they stay in one block until the closing rule. const INSIGHT_OPEN_PATTERN = /^( {0,3})(`?)★ Insight[ \t]+─{3,}\2[ \t]*$/u; const INSIGHT_CLOSE_PATTERN = /^( {0,3})(`?)─{3,}\2[ \t]*$/u; +// An ATX heading, also inside a list item or blockquote; group 1 is its text. +const ATX_HEADING_PATTERN = + /^(?:[ \t]*(?:>|[-*+](?=[ \t])|\d{1,9}[.)](?=[ \t])))*[ \t]*#{1,6}(?:[ \t]+(.*?))?(?:[ \t]+#+)?[ \t]*$/; +// Setext headings may span a paragraph and containers, so leave their parsing to the renderer. +const SETEXT_UNDERLINE_PATTERN = + /^(?:[ \t]*(?:>|[-*+](?=[ \t])|\d{1,9}[.)](?=[ \t])))*[ \t]*(?:=+|-+)[ \t]*$/; /** * Cuts Markdown at blank lines that close every open block, so each piece renders exactly as it - * would inside the whole text. Returns null when the text uses syntax that spans blocks. + * would inside the whole text. Returns null when the text uses syntax that spans blocks, such as + * headings with the same slug, whose ids are numbered across the whole text. */ export function splitMarkdownBlocks(text: string): string[] | null { - if (text.includes("\r") || DOCUMENT_WIDE_SYNTAX.test(text)) return null; + // remark-parse strips a leading BOM before recognizing the first heading. + if (text.startsWith("\ufeff") || text.includes("\r") || DOCUMENT_WIDE_SYNTAX.test(text)) + return null; const blocks: string[] = []; let blockStart = 0; let lineStart = 0; @@ -21,11 +32,35 @@ export function splitMarkdownBlocks(text: string): string[] | null { let fenceIndent = 0; let afterBlankLine = false; let insightIndent: string | null = null; + const headingKeys = new Set(); + const needsWholeHeading = (headingText: string | undefined) => { + if (headingText === undefined) return false; + // Inline syntax and path/directive colons need the renderer before their slug is known. + if (/[`*_~[\]<&\\!$]|:(?!\s|$)/.test(headingText)) return true; + const key = githubHeadingSlug(headingText); + if (!key) return false; + if (headingKeys.has(key)) return true; + headingKeys.add(key); + return false; + }; + const headingNeedsWholeDocument = (line: string, mayUnderline = true) => + (mayUnderline && SETEXT_UNDERLINE_PATTERN.test(line)) || + needsWholeHeading(ATX_HEADING_PATTERN.exec(line)?.[1]); + // Only a line right after paragraph text can underline it; elsewhere "---" is a thematic break. + let afterContentLine = false; for (const line of text.split("\n")) { const opener = FENCE_PATTERN.exec(line)?.[1]; + const mayUnderline = afterContentLine; + afterContentLine = false; if (fence !== null) { // A line left of an indented fence may end the list item holding it, which isn't tracked. - if (/\S/.test(line.slice(0, fenceIndent))) break; + if (/\S/.test(line.slice(0, fenceIndent))) { + const rest = text.slice(lineStart).split("\n"); + for (const restLine of rest) { + if (headingNeedsWholeDocument(restLine)) return null; + } + break; + } if ( opener && opener[0] === fence[0] && @@ -40,6 +75,8 @@ export function splitMarkdownBlocks(text: string): string[] | null { } else if (line.trim() === "") { afterBlankLine = true; } else { + if (headingNeedsWholeDocument(line, mayUnderline)) return null; + afterContentLine = opener === undefined; if ( afterBlankLine && insightIndent === null && From d051d9822fcb96f939db109988df8635326d6554 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Tue, 17 Nov 2026 10:27:15 +0100 Subject: [PATCH 011/133] fix(web): leaving Appearance cancels a pending theme install (#38021) Co-authored-by: Grok 4.7 Co-authored-by: Julius Marminge --- .../ThemeImportDialog.browser.test.tsx | 37 ++++++++++++++++++- .../components/settings/ThemeImportDialog.tsx | 16 +++++++- apps/web/tsconfig.json | 2 +- 3 files changed, 51 insertions(+), 4 deletions(-) diff --git a/apps/web/src/components/settings/ThemeImportDialog.browser.test.tsx b/apps/web/src/components/settings/ThemeImportDialog.browser.test.tsx index 0cde5b8f1f47..8eecf79f5d33 100644 --- a/apps/web/src/components/settings/ThemeImportDialog.browser.test.tsx +++ b/apps/web/src/components/settings/ThemeImportDialog.browser.test.tsx @@ -2,7 +2,7 @@ import { StrictMode } from "react"; import { describe, expect, it, vi } from "vite-plus/test"; import { page, userEvent } from "vite-plus/test/browser"; -import { render } from "../../../test/render"; +import { act, render } from "../../../test/render"; import { CUSTOM_THEMES_STORAGE_KEY, getCustomThemes, @@ -12,7 +12,7 @@ import { themeColorToHex, THEME_FILE_VERSION, } from "../../themePalette"; -import type { OpenVsxThemeExtension } from "../../openVsxThemes"; +import { importOpenVsxThemeExtension, type OpenVsxThemeExtension } from "../../openVsxThemes"; import { ThemeImportDialog } from "./ThemeImportDialog"; const searchOpenVsxThemes = vi.hoisted(() => vi.fn()); @@ -222,3 +222,36 @@ describe("ThemeImportDialog JSONC imports", () => { ]); }); }); + +it("does not install a pending community theme after leaving Appearance", async () => { + using _themes = isolateThemes(); + searchOpenVsxThemes.mockReset(); + searchOpenVsxThemes.mockResolvedValue([extension]); + const download = Promise.withResolvers[]>(); + vi.mocked(importOpenVsxThemeExtension).mockReset(); + vi.mocked(importOpenVsxThemeExtension).mockReturnValue(download.promise); + await using screen = await render( + {}} + onImported={() => true} + onImportedMany={() => {}} + />, + ); + await userEvent.fill(page.getByLabelText("Search Open VSX themes"), "night"); + await page.getByRole("button", { name: "Install Nightfall" }).click(); + await screen.unmount(); + await act(async () => { + download.resolve([ + { + ...parseThemeFile(theme("Nightfall")), + collection: { id: extension.collectionId, label: extension.name }, + }, + ]); + await download.promise; + }); + expect( + getCustomThemes(), + "expect leaving Appearance to cancel its pending theme installation", + ).toEqual([]); +}); diff --git a/apps/web/src/components/settings/ThemeImportDialog.tsx b/apps/web/src/components/settings/ThemeImportDialog.tsx index 17fb7b43daae..106b85b87ec3 100644 --- a/apps/web/src/components/settings/ThemeImportDialog.tsx +++ b/apps/web/src/components/settings/ThemeImportDialog.tsx @@ -1,7 +1,7 @@ import { DownloadIcon, PlusIcon } from "lucide-react"; import type { ChangeEvent, DragEvent, UIEvent } from "react"; import { settlePromise } from "@t3tools/client-runtime/state/runtime"; -import { useRef, useState } from "react"; +import { useEffect, useRef, useState } from "react"; import { formatBytes } from "../../lib/formatBytes"; import { cn } from "../../lib/utils"; import { @@ -165,6 +165,20 @@ export function ThemeImportDialog({ session.controller.abort(); onOpenChange(false); }; + // Leaving the page ends the session as closing does. The abort waits a microtask + // so StrictMode's replayed cleanup, undone by its replayed setup, keeps it alive. + const { controller } = session; + const mountedController = useRef(null); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- unmounting must abort in-flight Open VSX installs + useEffect(() => { + mountedController.current = controller; + return () => { + mountedController.current = null; + queueMicrotask(() => { + if (mountedController.current !== controller) controller.abort(); + }); + }; + }, [controller]); return ( Date: Tue, 17 Nov 2026 10:28:50 +0100 Subject: [PATCH 012/133] fix(shared): stopping an MCP call releases a stalled JSON response body (#38025) Co-authored-by: Grok 4.7 Co-authored-by: Julius Marminge --- .../shared/src/mcpResponsePayloads.test.ts | 58 ++++++++++--------- packages/shared/src/mcpResponsePayloads.ts | 48 ++++++++++----- 2 files changed, 65 insertions(+), 41 deletions(-) diff --git a/packages/shared/src/mcpResponsePayloads.test.ts b/packages/shared/src/mcpResponsePayloads.test.ts index a18a798e95bd..d3366d671586 100644 --- a/packages/shared/src/mcpResponsePayloads.test.ts +++ b/packages/shared/src/mcpResponsePayloads.test.ts @@ -93,31 +93,37 @@ it.effect("picks the SSE reader from the media type alone, whatever its case", ( }), ); -it.effect("releases a stalled SSE response body when its consumer is interrupted", () => - Effect.gen(function* () { - const reading = Promise.withResolvers(); - let controller!: ReadableStreamDefaultController; - const body = new ReadableStream( - { - start(value) { - controller = value; - }, - pull() { - reading.resolve(); +it.effect.each(["text/event-stream", "application/json"])( + "releases a stalled %s response body when its consumer is interrupted", + (contentType) => + Effect.gen(function* () { + const reading = Promise.withResolvers(); + let controller!: ReadableStreamDefaultController; + const body = new ReadableStream( + { + start(value) { + controller = value; + }, + pull() { + reading.resolve(); + }, }, - }, - { highWaterMark: 0 }, - ); - const response = new Response(body, { headers: { "content-type": "text/event-stream" } }); - const consumer = yield* Stream.runDrain(responsePayloads(response, String)).pipe( - Effect.forkChild, - ); - yield* Effect.promise(() => reading.promise); - yield* Fiber.interrupt(consumer); - try { - expect(body.locked, "interrupted SSE response must release its body").toBe(false); - } finally { - if (body.locked) controller.close(); - } - }), + { highWaterMark: 0 }, + ); + const response = new Response(body, { headers: { "content-type": contentType } }); + const consumer = yield* Stream.runDrain(responsePayloads(response, String)).pipe( + Effect.forkChild, + ); + yield* Effect.promise(() => reading.promise); + yield* Fiber.interrupt(consumer); + try { + expect( + () => controller.enqueue(new TextEncoder().encode("late response bytes")), + "interrupted MCP response must stop accepting body bytes", + ).toThrow(TypeError); + expect(body.locked, "interrupted MCP response must release its body").toBe(false); + } finally { + if (body.locked) controller.close(); + } + }), ); diff --git a/packages/shared/src/mcpResponsePayloads.ts b/packages/shared/src/mcpResponsePayloads.ts index c591cf69372a..8c9a38cecf18 100644 --- a/packages/shared/src/mcpResponsePayloads.ts +++ b/packages/shared/src/mcpResponsePayloads.ts @@ -28,6 +28,30 @@ async function* sseDataLines( } } +async function readText(reader: ReadableStreamDefaultReader): Promise { + const decoder = new TextDecoder(); + let text = ""; + while (true) { + const { done, value } = await reader.read(); + if (done) return text + decoder.decode(); + text += decoder.decode(value, { stream: true }); + } +} + +// Interrupting a read cannot settle the promise parked on read(), so the reader is cancelled +// from a finalizer instead; that settles the read and closes the body. +const scopedReader = (body: ReadableStream) => + Effect.acquireRelease( + Effect.sync(() => body.getReader()), + (reader) => + Effect.promise(() => + reader + .cancel() + .catch(() => undefined) + .then(() => reader.releaseLock()), + ), + ); + export const discardResponseBody = (response: Response): Effect.Effect => Effect.promise(() => response.body?.cancel().catch(() => undefined) ?? Promise.resolve()); @@ -38,27 +62,21 @@ export function responsePayloads( if (response.status === 202 || response.status === 204) { return Stream.unwrap(discardResponseBody(response).pipe(Effect.as(Stream.empty))); } + const body = response.body; + if (body === null) return Stream.empty; const mediaType = (response.headers.get("content-type") ?? "").split(";", 1)[0]!.trim(); if (mediaType.toLowerCase() === "text/event-stream") { - const body = response.body; - if (body === null) return Stream.empty; - // Interrupting fromAsyncIterable cannot return a generator parked on read(), so the - // reader is cancelled from a finalizer instead; that settles the read and closes the body. return Stream.unwrap( - Effect.acquireRelease( - Effect.sync(() => body.getReader()), - (reader) => - Effect.promise(() => - reader - .cancel() - .catch(() => undefined) - .then(() => reader.releaseLock()), - ), - ).pipe(Effect.map((reader) => Stream.fromAsyncIterable(sseDataLines(reader), onError))), + scopedReader(body).pipe( + Effect.map((reader) => Stream.fromAsyncIterable(sseDataLines(reader), onError)), + ), ).pipe(Stream.mapEffect((data) => Effect.try({ try: () => JSON.parse(data), catch: onError }))); } return Stream.unwrap( - Effect.tryPromise({ try: () => response.text(), catch: onError }).pipe( + scopedReader(body).pipe( + Effect.flatMap((reader) => + Effect.tryPromise({ try: () => readText(reader), catch: onError }), + ), Effect.flatMap((text) => text.trim().length === 0 ? Effect.succeed(Stream.empty) From 25da86c29b8df671ec85aa3523aa581a1a1e3e72 Mon Sep 17 00:00:00 2001 From: Martin Bergo Date: Tue, 17 Nov 2026 10:29:37 +0100 Subject: [PATCH 013/133] fix(server): process group metrics no longer warn at every startup (#38026) Co-authored-by: Julius Marminge --- .../ProcessGroupMetrics.test.ts | 68 ++++++++++++------- .../resourceTelemetry/ProcessGroupMetrics.ts | 6 +- 2 files changed, 48 insertions(+), 26 deletions(-) diff --git a/apps/server/src/resourceTelemetry/ProcessGroupMetrics.test.ts b/apps/server/src/resourceTelemetry/ProcessGroupMetrics.test.ts index f10937c4ebd4..ee9541ec0324 100644 --- a/apps/server/src/resourceTelemetry/ProcessGroupMetrics.test.ts +++ b/apps/server/src/resourceTelemetry/ProcessGroupMetrics.test.ts @@ -1,5 +1,6 @@ import { assert, describe, it } from "@effect/vitest"; import type { ResourceTelemetryProcess, ResourceTelemetrySnapshot } from "@t3tools/contracts"; +import * as Clock from "effect/Clock"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Logger from "effect/Logger"; @@ -69,27 +70,20 @@ describe("groupProcesses", () => { }); describe("ProcessGroupMetrics.layer", () => { - it.effect("logs the first failed sample and the recovery, not every repeat", () => { + const notRunning = new ResourceTelemetry.ResourceTelemetryRefreshFailed({ + operation: "refresh", + cause: new Error("Resource monitor is unavailable: sidecar is not running"), + }); + const logsAfter = ( + refresh: ResourceTelemetry.ResourceTelemetry["Service"]["refresh"], + afterStart: Effect.Effect, + ) => { const logs: Array = []; const logger = Logger.make(({ logLevel, message }) => { logs.push(`${logLevel.toUpperCase()} ${String([message].flat()[0])}`); }); + const telemetry = { refresh } as unknown as ResourceTelemetry.ResourceTelemetry["Service"]; return Effect.gen(function* () { - const outcomes = yield* Ref.make>(["fail", "fail", "ok"]); - const refresh = Ref.modify(outcomes, ([next = "ok", ...rest]) => [next, rest] as const).pipe( - Effect.flatMap((next) => - next === "fail" - ? Effect.fail( - new ResourceTelemetry.ResourceTelemetryRefreshFailed({ - operation: "refresh", - cause: new Error("Resource monitor binary was not found for darwin/arm64."), - }), - ) - : Effect.succeed({ processes: [] } as unknown as ResourceTelemetrySnapshot), - ), - ); - const telemetry = { refresh } as unknown as ResourceTelemetry.ResourceTelemetry["Service"]; - yield* Layer.build( ProcessGroupMetrics.layer.pipe( Layer.provide(Layer.succeed(ResourceTelemetry.ResourceTelemetry, telemetry)), @@ -100,13 +94,8 @@ describe("ProcessGroupMetrics.layer", () => { ), ), ); - yield* TestClock.adjust("3 minutes"); - - assert.deepStrictEqual(logs, [ - "WARN process group metrics are not exported: sample failed", - "DEBUG process group metrics sample failed", - "INFO process group metrics sample recovered", - ]); + yield* afterStart; + return logs; }).pipe( Effect.scoped, Effect.provide( @@ -116,5 +105,36 @@ describe("ProcessGroupMetrics.layer", () => { ), ), ); - }); + }; + const emptySnapshot = { processes: [] } as unknown as ResourceTelemetrySnapshot; + + it.effect("logs the first failed sample and the recovery, not every repeat", () => + Effect.gen(function* () { + const outcomes = yield* Ref.make>(["fail", "fail", "ok"]); + const refresh = Ref.modify(outcomes, ([next = "ok", ...rest]) => [next, rest] as const).pipe( + Effect.flatMap((next) => + next === "fail" ? Effect.fail(notRunning) : Effect.succeed(emptySnapshot), + ), + ); + const logs = yield* logsAfter(refresh, TestClock.adjust("3 minutes")); + assert.deepStrictEqual(logs, [ + "WARN process group metrics are not exported: sample failed", + "DEBUG process group metrics sample failed", + "INFO process group metrics sample recovered", + ]); + }), + ); + + it.effect("does not report the sidecar as failed while it is still starting", () => + Effect.gen(function* () { + // The sidecar answers once its handshake completes, a few seconds after the server starts. + const refresh = Clock.currentTimeMillis.pipe( + Effect.flatMap((now) => + now >= 5_000 ? Effect.succeed(emptySnapshot) : Effect.fail(notRunning), + ), + ); + const logs = yield* logsAfter(refresh, TestClock.adjust("1 minute")); + assert.deepStrictEqual(logs, []); + }), + ); }); diff --git a/apps/server/src/resourceTelemetry/ProcessGroupMetrics.ts b/apps/server/src/resourceTelemetry/ProcessGroupMetrics.ts index b3a02e94e244..d5b86f65effb 100644 --- a/apps/server/src/resourceTelemetry/ProcessGroupMetrics.ts +++ b/apps/server/src/resourceTelemetry/ProcessGroupMetrics.ts @@ -134,10 +134,12 @@ export const layer = Layer.effectDiscard( Effect.annotateLogs({ operation: error.operation }), ); }; - yield* sample().pipe( + // The first sample waits one interval: the resource monitor sidecar starts with the server + // and cannot answer until its handshake completes. + yield* Effect.sleep(SAMPLE_INTERVAL).pipe( + Effect.andThen(sample()), Effect.andThen(recordSuccess), Effect.catch(recordFailure), - Effect.andThen(Effect.sleep(SAMPLE_INTERVAL)), Effect.forever, Effect.forkScoped, ); From 42a5aade8485122a09b5f4feda9e9fb275dee675 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 17 Nov 2026 01:32:13 -0800 Subject: [PATCH 014/133] fix(server): saved secrets only reach the destination they were saved for (#38037) --- apps/server/src/auth/RpcAuthorization.test.ts | 69 +++++++++++++++++++ apps/server/src/auth/RpcAuthorization.ts | 10 +++ apps/server/src/serverSettings.test.ts | 19 +++++ apps/server/src/serverSettings.ts | 6 +- apps/server/src/settingsSecrets.ts | 30 ++++++++ .../src/textGeneration/TextGenerators.test.ts | 5 +- .../src/textGeneration/TextGenerators.ts | 6 +- packages/contracts/src/auth.ts | 1 + packages/contracts/src/settings.ts | 4 +- packages/contracts/src/settingsSecretValue.ts | 7 ++ 10 files changed, 153 insertions(+), 4 deletions(-) diff --git a/apps/server/src/auth/RpcAuthorization.test.ts b/apps/server/src/auth/RpcAuthorization.test.ts index 0cd838f12934..8afe47e715a9 100644 --- a/apps/server/src/auth/RpcAuthorization.test.ts +++ b/apps/server/src/auth/RpcAuthorization.test.ts @@ -355,9 +355,78 @@ describe("settings mutation authorization", () => { patch: { requireConnectDeviceApproval: false }, }).pipe(Effect.flip), ).toMatchObject({ requiredPermission: AuthAccessWriteScope }); + // A reference names any secret the store holds, and the host entry names where it goes. + expect( + yield* client[WS_METHODS.serverUpdateSettings]({ + patch: { + simlockDeviceHosts: [ + { + kind: "simlock", + id: "simlock_evil", + label: "Gateway", + gatewayUrl: "https://attacker.example", + agentToken: { + provider: SecretProviderId.make("personal"), + reference: "op://Private/OpenAI/credential", + }, + maxLeases: 2, + maxLeaseMinutes: 60, + }, + ], + }, + }).pipe(Effect.flip), + ).toMatchObject({ requiredPermission: AuthProvidersManageScope }); expect(handled).toBe(false); }), ); + + it.effect("does not let a settings grant send a named secret to a gateway it picks", () => + Effect.gen(function* () { + const group = WsRpcGroup.omit( + ...[...WsRpcGroup.requests.keys()].filter( + ( + tag, + ): tag is Exclude< + keyof typeof RPC_REQUIRED_SCOPES, + typeof WS_METHODS.deviceSimlockIdentity + > => tag !== WS_METHODS.deviceSimlockIdentity, + ), + ); + let handled = 0; + const client = yield* RpcTest.makeClient(group).pipe( + Effect.provide( + Layer.mergeAll( + group.toLayerHandler(WS_METHODS.deviceSimlockIdentity, () => + Effect.sync(() => { + handled++; + return { + gatewayUrl: "https://attacker.example", + signedInAs: "agent", + tokenSource: "entered" as const, + }; + }), + ), + RpcAuthorization.layer([AuthSettingsWriteScope]), + ), + ), + ); + yield* client[WS_METHODS.deviceSimlockIdentity]({ + gatewayUrl: "https://attacker.example", + agentToken: "typed-token", + }); + expect(handled).toBe(1); + expect( + yield* client[WS_METHODS.deviceSimlockIdentity]({ + gatewayUrl: "https://attacker.example", + agentToken: { + provider: SecretProviderId.make("personal"), + reference: "op://Private/OpenAI/credential", + }, + }).pipe(Effect.flip), + ).toMatchObject({ requiredPermission: AuthProvidersManageScope }); + expect(handled).toBe(1); + }), + ); }); it.effect("requires task permission before attaching a prepared worktree to a thread", () => diff --git a/apps/server/src/auth/RpcAuthorization.ts b/apps/server/src/auth/RpcAuthorization.ts index 715622cd00cc..a765c2847632 100644 --- a/apps/server/src/auth/RpcAuthorization.ts +++ b/apps/server/src/auth/RpcAuthorization.ts @@ -2,6 +2,7 @@ import { CLIENT_GUARDED_RPC_SCOPES, type DeviceListInput, clientRpcRequiredScopes, + containsSecretReference, authScopeRequiredResponse, AssetCreateUrlInput, AuthAccessReadScope, @@ -282,6 +283,15 @@ const requiredScopesForRpcCall = ( ]; } if (method === WS_METHODS.serverUpdateSettings) return requiredScopesForSettingsUpdate(payload); + // These send the credential they are given to a URL the caller names, as a saved setting would. + if ( + (method === WS_METHODS.deviceSimlockIdentity || + method === WS_METHODS.deviceEasAccount || + method === WS_METHODS.serverListTextGeneratorModels) && + containsSecretReference(payload) + ) { + return [AuthSettingsWriteScope, AuthProvidersManageScope]; + } if (method === WS_METHODS.projectsMutate) { return requiredScopesForProjectMutation(decodeProjectMutation(payload)); } diff --git a/apps/server/src/serverSettings.test.ts b/apps/server/src/serverSettings.test.ts index 03b89e495553..10d0b3fe6c1e 100644 --- a/apps/server/src/serverSettings.test.ts +++ b/apps/server/src/serverSettings.test.ts @@ -16,6 +16,7 @@ import { ServerSettings, ServerSettingsPatch, UsageLimitSourceId, + type SimlockDeviceHostConfig, } from "@t3tools/contracts"; import { createModelSelection } from "@t3tools/shared/model"; import { assert, it } from "@effect/vitest"; @@ -1859,6 +1860,24 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("server settings" assert.deepEqual(configOf(echoed, antigravity)?.apiKey, antigravityReference); assert.deepEqual(configOf(echoed, openCode)?.serverPassword, openCodeReference); assert.isTrue(Option.isSome(yield* stored("github", "tokens", "ghe.acme.test"))); + // A saved token goes only to the gateway it was saved for, however it is echoed. + const moved = (agentToken: SimlockDeviceHostConfig["agentToken"]) => + serverSettings.updateSettings({ + simlockDeviceHosts: [ + { + ...echoed.simlockDeviceHosts[0]!, + gatewayUrl: "https://elsewhere.test", + agentToken, + }, + ], + }); + assert.equal((yield* moved(SECRET_REDACTED)).simlockDeviceHosts[0]?.agentToken, ""); + yield* serverSettings.updateSettings({ simlockDeviceHosts: echoed.simlockDeviceHosts }); + assert.equal((yield* moved(simlockReference)).simlockDeviceHosts[0]?.agentToken, ""); + assert.equal( + (yield* moved("typed-token")).simlockDeviceHosts[0]?.agentToken, + "typed-token", + ); }).pipe(Effect.provide(layerServerSettingsWithSecrets())), ); diff --git a/apps/server/src/serverSettings.ts b/apps/server/src/serverSettings.ts index 81106d27b7c7..e720fea50886 100644 --- a/apps/server/src/serverSettings.ts +++ b/apps/server/src/serverSettings.ts @@ -66,6 +66,7 @@ import { mapSettingsSecrets, mapSettingsSecretValues, withoutRemovedSecretProviderReferences, + withoutRedirectedSimlockTokens, SECRET_REDACTED, type SettingsSecret, } from "./settingsSecrets.ts"; @@ -1203,7 +1204,10 @@ const make = Effect.gen(function* () { } // An older client echoes a reference as the redacted marker; restore it before vetting so // a removed provider's reference is cleared below rather than restored by persistence. - const updated = withEchoedSecretReferences(current, yield* update(current)); + const updated = withoutRedirectedSimlockTokens( + current, + withEchoedSecretReferences(current, yield* update(current)), + ); // Vet before secrets: a variable the policy hides from clients is not one they removed. const vetted = managed.vetWrite(current, yield* normalizeServerSettings(updated), patch); if (vetted._tag === "Locked") { diff --git a/apps/server/src/settingsSecrets.ts b/apps/server/src/settingsSecrets.ts index a38072d19813..d433621f3b1d 100644 --- a/apps/server/src/settingsSecrets.ts +++ b/apps/server/src/settingsSecrets.ts @@ -292,3 +292,33 @@ export function withoutRemovedSecretProviderReferences( ), }; } + +const gatewayOrigin = (url: string) => (URL.canParse(url) ? new URL(url).origin : url); + +/** + * `next` with a Simlock host's kept token cleared when its gateway moved to another origin: a + * saved token goes only to the gateway it was saved for. A newly entered token stays. + */ +export function withoutRedirectedSimlockTokens( + current: ServerSettings, + next: ServerSettings, +): ServerSettings { + const saved = new Map(current.simlockDeviceHosts.map((host) => [host.id, host])); + const kept = (token: SettingsSecretValue, savedToken: SettingsSecretValue) => + token === SECRET_REDACTED || + (isSecretReference(token) && + isSecretReference(savedToken) && + token.provider === savedToken.provider && + token.reference === savedToken.reference); + return { + ...next, + simlockDeviceHosts: next.simlockDeviceHosts.map((host) => { + const previous = saved.get(host.id); + return previous && + gatewayOrigin(previous.gatewayUrl) !== gatewayOrigin(host.gatewayUrl) && + kept(host.agentToken, previous.agentToken) + ? { ...host, agentToken: "" } + : host; + }), + }; +} diff --git a/apps/server/src/textGeneration/TextGenerators.test.ts b/apps/server/src/textGeneration/TextGenerators.test.ts index 0806789b97fc..14aa50572b81 100644 --- a/apps/server/src/textGeneration/TextGenerators.test.ts +++ b/apps/server/src/textGeneration/TextGenerators.test.ts @@ -182,10 +182,13 @@ it.effect("checks unsaved settings, keeping the saved key behind a redaction mar expect((yield* list("draft", { apiKey: "typed-key" })).models).toEqual([ { id: "model-a", name: "model-a" }, ]); + yield* list(ID, { apiKey: SECRET_REDACTED, baseUrl: "https://api.test/v1" }); + // The saved key goes only to the endpoint it was saved for. yield* list(ID, { apiKey: SECRET_REDACTED }); expect(seen).toEqual([ { url: "https://new.test/v1/models", auth: "Bearer typed-key" }, - { url: "https://new.test/v1/models", auth: "Bearer saved-key" }, + { url: "https://api.test/v1/models", auth: "Bearer saved-key" }, + { url: "https://new.test/v1/models", auth: null }, ]); // Listing alone proves nothing about the key on some APIs; a test asks the model itself. diff --git a/apps/server/src/textGeneration/TextGenerators.ts b/apps/server/src/textGeneration/TextGenerators.ts index 8e93c0839240..f9ac96432f81 100644 --- a/apps/server/src/textGeneration/TextGenerators.ts +++ b/apps/server/src/textGeneration/TextGenerators.ts @@ -134,7 +134,11 @@ export const make = Effect.gen(function* () { input.config === undefined ? saved : input.config.apiKey === SECRET_REDACTED - ? { ...input.config, apiKey: saved?.apiKey ?? "" } + ? // The saved key goes only to the endpoint it was saved for. + { + ...input.config, + apiKey: saved?.baseUrl === input.config.baseUrl ? saved.apiKey : "", + } : input.config; if (config === undefined) { return yield* new TextGeneratorRequestError({ diff --git a/packages/contracts/src/auth.ts b/packages/contracts/src/auth.ts index fd0c93025dbf..132cc7322337 100644 --- a/packages/contracts/src/auth.ts +++ b/packages/contracts/src/auth.ts @@ -31,6 +31,7 @@ export type ServerAuthSessionMethod = typeof ServerAuthSessionMethod.Type; export const AuthOrchestrationReadScope = "orchestration:read" as const; export const AuthOrchestrationOperateScope = "orchestration:operate" as const; export const AuthSettingsWriteScope = "settings:write" as const; +// Also decides where credentials go: secret providers, references, and key-bearing endpoints. export const AuthProvidersManageScope = "providers:manage" as const; export const AuthEnvironmentMaintainScope = "environment:maintain" as const; export const AuthPreviewOperateScope = "preview:operate" as const; diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index 36b1b538d486..678f58294c66 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -25,7 +25,7 @@ import { import { UsageLimitSourceId } from "./usageLimitSourceId.ts"; import { UsageModelFilter } from "./usage.ts"; import { SecretProviderId, SecretProviderSlug } from "./secretReference.ts"; -import { SettingsSecretValue } from "./settingsSecretValue.ts"; +import { containsSecretReference, SettingsSecretValue } from "./settingsSecretValue.ts"; import { EnvironmentMachineKind, ThreadEnvMode, WorktreeSubmodules } from "./environment.ts"; import { KeybindingShortcut } from "./keybindings.ts"; import { @@ -2020,6 +2020,8 @@ export function requiredScopesForServerSettingsPatch( changesSettings = true; } } + // A reference can name any secret the store holds; choosing where one goes is provider authority. + if (containsSecretReference(patch)) changesProviders = true; // Removing a secret provider also clears the settings fields that read from it. if (Object.values(patch.secretProviders ?? {}).some((entry) => entry === null)) { changesSettings = true; diff --git a/packages/contracts/src/settingsSecretValue.ts b/packages/contracts/src/settingsSecretValue.ts index 93d720ba6555..f644c9b2d298 100644 --- a/packages/contracts/src/settingsSecretValue.ts +++ b/packages/contracts/src/settingsSecretValue.ts @@ -18,6 +18,13 @@ export type SettingsSecretValue = typeof SettingsSecretValue.Type; export const isSecretReference = Schema.is(SecretReference); +/** Whether a reference appears anywhere in `value`, such as a settings patch or an RPC payload. */ +export function containsSecretReference(value: unknown): boolean { + if (value === null || typeof value !== "object") return false; + if (isSecretReference(value)) return true; + return Object.values(value).some(containsSecretReference); +} + /** The literal a credential setting holds, or `""` when it names a secret instead. */ export function settingsSecretLiteral(value: SettingsSecretValue | undefined): string { return typeof value === "string" ? value : ""; From 16a8876dd77f3fba72a5d1458e083442de3b1ff9 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 17 Nov 2026 01:36:38 -0800 Subject: [PATCH 015/133] fix(server): bound favicon source scans (#37870) --- .../project/ProjectFaviconResolver.test.ts | 15 +++++++ .../src/project/ProjectFaviconResolver.ts | 40 +++++++++++++++---- 2 files changed, 47 insertions(+), 8 deletions(-) diff --git a/apps/server/src/project/ProjectFaviconResolver.test.ts b/apps/server/src/project/ProjectFaviconResolver.test.ts index 143db2a86629..973ef659655e 100644 --- a/apps/server/src/project/ProjectFaviconResolver.test.ts +++ b/apps/server/src/project/ProjectFaviconResolver.test.ts @@ -215,6 +215,21 @@ it.layer(layerTest)("ProjectFaviconResolverLive", (it) => { }), ); + it.effect("skips source metadata beyond the favicon scan limit", () => + Effect.gen(function* () { + const resolver = yield* ProjectFaviconResolver.ProjectFaviconResolver; + const cwd = yield* makeTempDir; + yield* writeTextFile( + cwd, + "index.html", + ``, + ); + yield* writeTextFile(cwd, "public/brand/logo.svg", "brand"); + + expect(yield* resolver.resolvePath(cwd)).toBeNull(); + }), + ); + it.effect("resolves icon hrefs from object-literal route metadata", () => Effect.gen(function* () { const resolver = yield* ProjectFaviconResolver.ProjectFaviconResolver; diff --git a/apps/server/src/project/ProjectFaviconResolver.ts b/apps/server/src/project/ProjectFaviconResolver.ts index e09d4aad362a..e9b8f6d6a963 100644 --- a/apps/server/src/project/ProjectFaviconResolver.ts +++ b/apps/server/src/project/ProjectFaviconResolver.ts @@ -16,6 +16,7 @@ import * as WorkspacePaths from "../workspace/WorkspacePaths.ts"; import * as T3ProjectFileLoader from "./T3ProjectFileLoader.ts"; const FAVICON_CACHE_CAPACITY = 512; +const ICON_SOURCE_SCAN_BYTES = 128 * 1024; const FAVICON_POSITIVE_CACHE_TTL = Duration.minutes(10); const FAVICON_NEGATIVE_CACHE_TTL = Duration.minutes(1); @@ -72,9 +73,9 @@ const ICON_SOURCE_FILES = [ "src/index.html", ] as const; -// Anchor HTML at ]*\brel=["'](?:icon|shortcut icon)["'])(?=[^>]*\bhref=["']([^"'?]+))[^>]*>/i; +const HTML_LINK_RE = /]*>/gi; +const HTML_ICON_REL_RE = /\brel=["'](?:icon|shortcut icon)["']/i; +const HTML_ICON_HREF_RE = /\bhref=["']([^"'?]+)/i; const ICON_REL_RE = /\brel\s*:\s*["'](?:icon|shortcut icon)["']/i; const ICON_HREF_RE = /\bhref\s*:\s*["']([^"'?]+)/i; @@ -116,8 +117,11 @@ export class ProjectFaviconResolver extends Context.Service< >()("t3/project/ProjectFaviconResolver") {} function extractIconHref(source: string): string | null { - const htmlMatch = source.match(LINK_ICON_HTML_RE); - if (htmlMatch?.[1]) return htmlMatch[1]; + for (const [tag] of source.matchAll(HTML_LINK_RE)) { + if (!HTML_ICON_REL_RE.test(tag)) continue; + const hrefMatch = tag.match(HTML_ICON_HREF_RE); + if (hrefMatch?.[1]) return hrefMatch[1]; + } for (const run of source.split("}")) { if (!ICON_REL_RE.test(run)) continue; const hrefMatch = run.match(ICON_HREF_RE); @@ -213,7 +217,27 @@ export const make = Effect.gen(function* () { }), ), ); - const source = yield* optionOnNotFound(fileSystem.readFileString(sourcePath.absolutePath)).pipe( + const stats = yield* optionOnNotFound(fileSystem.stat(sourcePath.absolutePath)).pipe( + Effect.mapError( + (cause) => + new ProjectFaviconResolutionError({ + operation: "stat-candidate", + workspaceRoot: projectCwd, + relativePath: sourceFile, + absolutePath: sourcePath.absolutePath, + cause, + }), + ), + ); + if (Option.isNone(stats) || stats.value.type !== "File") { + return null; + } + const source = yield* optionOnNotFound( + fileSystem.open(sourcePath.absolutePath, { flag: "r" }).pipe( + Effect.flatMap((file) => file.readAlloc(ICON_SOURCE_SCAN_BYTES)), + Effect.scoped, + ), + ).pipe( Effect.mapError( (cause) => new ProjectFaviconResolutionError({ @@ -225,10 +249,10 @@ export const make = Effect.gen(function* () { }), ), ); - if (Option.isNone(source)) { + if (Option.isNone(source) || Option.isNone(source.value)) { return null; } - const href = extractIconHref(source.value); + const href = extractIconHref(new TextDecoder().decode(source.value.value)); if (!href) { return null; } From f1cd57bbf9572a592bed46f69dae57c9b10e4848 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 17 Nov 2026 01:36:56 -0800 Subject: [PATCH 016/133] fix(git): bound merge credit parsing work (#37869) --- .../src/server/mergeMessage.test.ts | 1 + .../src/server/mergeMessage.ts | 41 +++++++++++++------ 2 files changed, 29 insertions(+), 13 deletions(-) diff --git a/packages/source-control-core/src/server/mergeMessage.test.ts b/packages/source-control-core/src/server/mergeMessage.test.ts index 0151f09a5c09..a857f2d6dc91 100644 --- a/packages/source-control-core/src/server/mergeMessage.test.ts +++ b/packages/source-control-core/src/server/mergeMessage.test.ts @@ -14,6 +14,7 @@ describe("removeAgentCredits", () => { "* Co-authored-by: Codex ", "co-authored-by: Cursor ", "Co-authored-by: Copilot ", + "Co-Authored-By:\tGitHub Copilot ", "", "🤖 Generated with [Claude Code](https://claude.ai/code)", ].join("\n"), diff --git a/packages/source-control-core/src/server/mergeMessage.ts b/packages/source-control-core/src/server/mergeMessage.ts index 159c074260cd..ebbfffb1c79e 100644 --- a/packages/source-control-core/src/server/mergeMessage.ts +++ b/packages/source-control-core/src/server/mergeMessage.ts @@ -11,6 +11,22 @@ const AGENT_EMAILS = new Set([ const GENERATED_BY_AGENT = /^(?:🤖\s*)?generated (?:with|by)\s+(?:claude(?: code)?|codex|cursor|github copilot|copilot|opencode|grok|antigravity)[.!]?$/i; +const CO_AUTHOR_PREFIX = /^co-authored-by:/i; + +function isAgentAuthor(text: string): boolean { + const prefix = CO_AUTHOR_PREFIX.exec(text); + if (prefix === null || !text.endsWith(">")) return false; + const emailStart = text.lastIndexOf("<"); + if (emailStart < prefix[0].length) return false; + const email = text.slice(emailStart + 1, -1).toLowerCase(); + if (!AGENT_EMAILS.has(email)) return false; + // GitHub's generic noreply address is also used by people; require Copilot's name. + return ( + email !== "noreply@github.com" || + /^(?:github )?copilot$/i.test(text.slice(prefix[0].length, emailStart).trim()) + ); +} + export function removeAgentCredits(message: string): string { let fence: string | undefined; let removed = false; @@ -34,20 +50,19 @@ export function removeAgentCredits(message: string): string { } if (fence !== undefined) return true; const text = line.trim().replace(/^(?:[-*]\s+)/, ""); - const author = /^co-authored-by:\s*(.*?)\s*<([^<>]+)>\s*$/i.exec(text); - // GitHub's generic noreply address is also used by people; require Copilot's name. - const email = author?.[2]?.toLowerCase(); - const agentAuthor = - email !== undefined && - AGENT_EMAILS.has(email) && - (email !== "noreply@github.com" || /^github copilot$|^copilot$/i.test(author![1]!)); - const footer = text.replace( - /\[([^\]]+)\]\(https:\/\/(?:claude\.ai|claude\.com|www\.anthropic\.com|chatgpt\.com|openai\.com|cursor\.com|github\.com|opencode\.ai|x\.ai|antigravity\.google)(?:\/[^\s)]*)?\)/gi, - "$1", - ); - if (!agentAuthor && !GENERATED_BY_AGENT.test(footer)) return true; + if (!isAgentAuthor(text)) { + const footer = text.replace( + /\[([^[\]\r\n]+)\]\(https:\/\/(?:claude\.ai|claude\.com|www\.anthropic\.com|chatgpt\.com|openai\.com|cursor\.com|github\.com|opencode\.ai|x\.ai|antigravity\.google)(?:\/[^\s)[\]]*)?\)/gi, + "$1", + ); + if (!GENERATED_BY_AGENT.test(footer)) return true; + } removed = true; return false; }); - return removed ? lines.join(newline).replace(/(?:\r?\n[ \t]*)+$/, "") : message; + if (!removed) return message; + while (lines.length > 1 && /^[ \t]*$/.test(lines.at(-1)!)) { + lines.pop(); + } + return lines.join(newline); } From d1f7683d7ecc244271748edc720693a9d7045f39 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 17 Nov 2026 01:37:07 -0800 Subject: [PATCH 017/133] fix(server): close media streams on session invalidation (#37871) --- .../src/device/DeviceHubProxy.stream.test.ts | 19 ++++++++++ apps/server/src/device/DeviceHubProxy.test.ts | 36 +++++++++++++++++- apps/server/src/device/DeviceHubProxy.ts | 38 ++++++++++++++----- .../src/preview/ServerBrowserStream.test.ts | 27 ++++++++++++- .../server/src/preview/ServerBrowserStream.ts | 20 ++++++++-- 5 files changed, 124 insertions(+), 16 deletions(-) diff --git a/apps/server/src/device/DeviceHubProxy.stream.test.ts b/apps/server/src/device/DeviceHubProxy.stream.test.ts index 6ff2a3e30c4c..3a00e38d26f5 100644 --- a/apps/server/src/device/DeviceHubProxy.stream.test.ts +++ b/apps/server/src/device/DeviceHubProxy.stream.test.ts @@ -2,6 +2,7 @@ import { expect, it } from "@effect/vitest"; import * as NodeWS from "@effect/platform-node/NodeWS"; import * as NodeNet from "node:net"; import * as Context from "effect/Context"; +import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; @@ -14,6 +15,7 @@ import { LOCAL_DEVICE_HOST_ID, } from "@t3tools/contracts"; import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts"; +import * as SessionStore from "../auth/SessionStore.ts"; import * as DeviceService from "./DeviceService.ts"; import * as DeviceHubProxy from "./DeviceHubProxy.ts"; @@ -34,13 +36,23 @@ it.effect("preserves binary input and admission frames through the real socket p yield* Effect.promise(() => new Promise((resolve) => hub.once("listening", resolve))); const address = hub.address(); if (typeof address !== "object" || !address) throw new Error("Missing hub port"); + const upstreamClosed = Promise.withResolvers(); hub.on("connection", (socket) => { + socket.once("close", upstreamClosed.resolve); socket.send(Uint8Array.of(0x83)); socket.on("message", (data, binary) => socket.send(data, { binary })); }); + const invalidated = yield* Deferred.make(); const services = yield* Layer.build( HttpRouter.serve(DeviceHubProxy.layer, { disableListenLog: true }).pipe( Layer.provideMerge(NodeHttpServer.layerTest), + Layer.provide( + Layer.mock(SessionStore.SessionStore, { + cookieName: "test", + legacyCookieName: undefined, + awaitInvalidation: () => Deferred.await(invalidated), + }), + ), Layer.provide( Layer.succeed(EnvironmentAuth.EnvironmentAuth, { authenticateWebSocketUpgrade: () => @@ -88,6 +100,12 @@ it.effect("preserves binary input and admission frames through the real socket p }); yield* Effect.promise(() => received.promise); expect(frames).toEqual([[0x83], [0x03, 1], [0x03, 2]]); + + const closed = new Promise((resolve) => + client.addEventListener("close", () => resolve(), { once: true }), + ); + yield* Deferred.succeed(invalidated, undefined); + yield* Effect.promise(() => Promise.all([closed, upstreamClosed.promise])); }), ); @@ -117,6 +135,7 @@ it.live("closes an upstream socket that is still connecting without an unhandled ); const connection = yield* Effect.promise(() => dialed.promise); const abandoned = new Promise((resolve) => connection.once("close", () => resolve())); + connection.resume(); yield* Fiber.interrupt(reading); yield* Effect.promise(() => abandoned); }), diff --git a/apps/server/src/device/DeviceHubProxy.test.ts b/apps/server/src/device/DeviceHubProxy.test.ts index 3daa305bdfb7..d7fee1a2271d 100644 --- a/apps/server/src/device/DeviceHubProxy.test.ts +++ b/apps/server/src/device/DeviceHubProxy.test.ts @@ -10,6 +10,7 @@ import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import { HttpClient, HttpClientResponse, HttpRouter } from "effect/http"; import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts"; +import * as SessionStore from "../auth/SessionStore.ts"; import type * as DeviceHost from "./DeviceHost.ts"; import * as DeviceService from "./DeviceService.ts"; import * as DeviceHubProxy from "./DeviceHubProxy.ts"; @@ -24,6 +25,8 @@ const fixture = ( fail = false, authError?: EnvironmentAuth.ServerAuthCredentialError | EnvironmentAuth.ServerAuthInternalError, upstream?: DeviceHost.DeviceHostReady["upstream"], + stream?: ReadableStream, + invalidated?: Promise, ) => { let finalized = 0; const requests: string[] = []; @@ -41,7 +44,7 @@ const fixture = ( if (fail) return yield* Effect.die(new Error("upstream failed")); return HttpClientResponse.fromWeb( request, - new Response("frame", { headers: { "set-cookie": "upstream=1" } }), + new Response(stream ?? "frame", { headers: { "set-cookie": "upstream=1" } }), ); }), ); @@ -97,6 +100,13 @@ const fixture = ( }), ), Layer.provideMerge(Layer.succeed(HttpClient.HttpClient, client)), + Layer.provideMerge( + Layer.mock(SessionStore.SessionStore, { + cookieName: "test", + legacyCookieName: undefined, + awaitInvalidation: () => (invalidated ? Effect.promise(() => invalidated) : Effect.never), + }), + ), ), { disableLogger: true }, ); @@ -116,6 +126,30 @@ describe("device hub proxy", () => { expect(finalized()).toBe(1); }); + it("stops an open HTTP stream and releases its upstream on session invalidation", async () => { + const invalidated = Promise.withResolvers(); + const stream = new ReadableStream({ + start: (controller) => controller.enqueue(new Uint8Array([1])), + }); + const { handler, finalized } = fixture( + [AuthOrchestrationReadScope], + false, + undefined, + undefined, + stream, + invalidated.promise, + ); + const response = await handler( + new Request("http://t3.test/api/device-hub/vendor/serve-sim/helper/device/stream.avcc"), + ); + expect(response.status).toBe(200); + const reader = response.body!.getReader(); + expect(await reader.read()).toEqual({ done: false, value: new Uint8Array([1]) }); + invalidated.resolve(); + expect((await reader.read()).done).toBe(true); + expect(finalized()).toBe(1); + }); + it.each(["/vendor/serve-sim/helper/ws", "/vendor/serve-emu/ws"])( "rejects input socket %s for a read-only session", async (path) => { diff --git a/apps/server/src/device/DeviceHubProxy.ts b/apps/server/src/device/DeviceHubProxy.ts index 0d606df1d513..9778cf084b01 100644 --- a/apps/server/src/device/DeviceHubProxy.ts +++ b/apps/server/src/device/DeviceHubProxy.ts @@ -5,6 +5,7 @@ import { AuthOrchestrationReadScope, AuthOrchestrationOperateScope } from "@t3to import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; +import * as Stream from "effect/Stream"; import { HttpClient, HttpClientRequest, @@ -14,9 +15,11 @@ import { HttpServerResponse, } from "effect/http"; import * as Socket from "effect/socket/Socket"; +import * as NodeHttpServerRequest from "@effect/platform-node/NodeHttpServerRequest"; import * as NodeSocket from "@effect/platform-node/NodeSocket"; -import { authenticateMediaRequest } from "../auth/http.ts"; +import { authenticateMediaRequest, failEnvironmentInternal } from "../auth/http.ts"; +import * as SessionStore from "../auth/SessionStore.ts"; import * as DeviceService from "./DeviceService.ts"; import { repeatStillFrame } from "./mjpegStillFrame.ts"; @@ -101,6 +104,7 @@ const proxyWebSocket = Effect.fn("DeviceHubProxy.proxyWebSocket")(function* ( protocols: ReadonlyArray = [], headers: Readonly> = {}, ) { + const transport = NodeHttpServerRequest.toIncomingMessage(request).socket; const client = yield* request.upgrade; const upstream = yield* Socket.makeWebSocket(upstreamUrl, { openTimeout: "10 seconds", @@ -116,7 +120,10 @@ const proxyWebSocket = Effect.fn("DeviceHubProxy.proxyWebSocket")(function* ( pumpFrames(client, writeToUpstream), ); }), - ).pipe(Effect.ignoreCause); + ).pipe( + Effect.onInterrupt(() => Effect.sync(() => transport.destroy())), + Effect.ignoreCause, + ); return HttpServerResponse.empty(); }); @@ -132,6 +139,7 @@ const pumpFrames = const proxyHttp = Effect.fn("DeviceHubProxy.proxyHttp")(function* ( request: HttpServerRequest.HttpServerRequest, upstreamUrl: string, + invalidated: Effect.Effect, extraHeaders: Readonly> = {}, ) { const httpClient = HttpClient.withScope(yield* HttpClient.HttpClient); @@ -171,7 +179,7 @@ const proxyHttp = Effect.fn("DeviceHubProxy.proxyHttp")(function* ( const body = headers["content-type"]?.startsWith("multipart/x-mixed-replace") ? repeatStillFrame(response.stream) : response.stream; - return HttpServerResponse.stream(body, { + return HttpServerResponse.stream(body.pipe(Stream.interruptWhen(invalidated)), { status: response.status, headers, ...(headers["content-type"] ? { contentType: headers["content-type"] } : {}), @@ -200,9 +208,16 @@ const handler = Effect.gen(function* () { const controlsDevice = (upgrade && hubPath !== "/api/devices/ws") || (!readOnly && /\/api\/(stream-(mode|settings)|fold)$/.test(hubPath)); - yield* authenticateMediaRequest( + const session = yield* authenticateMediaRequest( controlsDevice ? AuthOrchestrationOperateScope : AuthOrchestrationReadScope, ); + const sessions = yield* SessionStore.SessionStore; + const invalidated = sessions.awaitInvalidation(session.sessionId).pipe( + Effect.catchTags({ + SessionCredentialVerificationError: (error) => + failEnvironmentInternal("internal_error", error).pipe(Effect.ignore), + }), + ); const devices = yield* DeviceService.DeviceService; const ready = yield* devices.currentReadiness(url.value.searchParams.get("hostId") ?? undefined); if (!ready) { @@ -231,14 +246,17 @@ const handler = Effect.gen(function* () { } const upstreamUrl = routed?.url ?? `${ready.hub.origin}${hubPath}${search}`; if (upgrade) { - return yield* proxyWebSocket( - request, - upstreamUrl.replace(/^http/, "ws"), - routed?.protocols, - routed?.headers, + return yield* Effect.raceFirst( + proxyWebSocket( + request, + upstreamUrl.replace(/^http/, "ws"), + routed?.protocols, + routed?.headers, + ), + invalidated.pipe(Effect.as(HttpServerResponse.empty())), ); } - return yield* proxyHttp(request, upstreamUrl, routed?.headers); + return yield* proxyHttp(request, upstreamUrl, invalidated, routed?.headers); }); export const layer = HttpRouter.add("*", `${DeviceService.DEVICE_HUB_ROUTE_PREFIX}/*`, handler); diff --git a/apps/server/src/preview/ServerBrowserStream.test.ts b/apps/server/src/preview/ServerBrowserStream.test.ts index c0a9fbc923ff..d49724c97890 100644 --- a/apps/server/src/preview/ServerBrowserStream.test.ts +++ b/apps/server/src/preview/ServerBrowserStream.test.ts @@ -12,6 +12,7 @@ import { type AuthEnvironmentScope, } from "@t3tools/contracts"; import * as Context from "effect/Context"; +import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; @@ -21,6 +22,7 @@ import * as Schema from "effect/Schema"; import { HttpRouter, HttpServer } from "effect/http"; import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts"; +import * as SessionStore from "../auth/SessionStore.ts"; import * as PreviewBrowserHost from "./PreviewBrowserHost.ts"; import * as ServerBrowser from "./ServerBrowser.ts"; import { routeLayer } from "./ServerBrowserStream.ts"; @@ -30,6 +32,7 @@ const platformLayer = NodeHttpPlatform.layer.pipe(Layer.provideMerge(NodeService const makeAuth = ( scopes: ReadonlyArray, error?: EnvironmentAuth.ServerAuthCredentialError, + awaitInvalidation: SessionStore.SessionStore["Service"]["awaitInvalidation"] = () => Effect.never, ) => { const requests: string[] = []; const layer = Layer.mock(EnvironmentAuth.EnvironmentAuth, { @@ -45,7 +48,17 @@ const makeAuth = ( }); }, }); - return { layer, requests }; + return { + layer: Layer.merge( + layer, + Layer.mock(SessionStore.SessionStore, { + cookieName: "test", + legacyCookieName: undefined, + awaitInvalidation, + }), + ), + requests, + }; }; const mutations = [ @@ -157,6 +170,7 @@ it.effect("sends replies ahead of stale frames and only the newest frame after a Effect.gen(function* () { const output = yield* Queue.make(); const released: number[] = []; + const invalidated = yield* Deferred.make(); const frame = (id: number): ServerBrowser.ServerBrowserViewerOutput => ({ _tag: "frame", data: new Uint8Array([id]), @@ -178,7 +192,10 @@ it.effect("sends replies ahead of stale frames and only the newest frame after a { disableListenLog: true }, ).pipe( Layer.provideMerge(NodeHttpServer.layerTest), - Layer.provide(makeAuth([AuthOrchestrationReadScope]).layer), + Layer.provide( + makeAuth([AuthOrchestrationReadScope], undefined, () => Deferred.await(invalidated)) + .layer, + ), ), ); const server = Context.get(services, HttpServer.HttpServer); @@ -222,6 +239,12 @@ it.effect("sends replies ahead of stale frames and only the newest frame after a yield* Effect.promise(() => next.promise); expect(received).toEqual([1, "probe", 4]); expect(released).toEqual([2, 3, 1]); + + const closed = new Promise((resolve) => + socket.addEventListener("close", () => resolve(), { once: true }), + ); + yield* Deferred.succeed(invalidated, undefined); + yield* Effect.promise(() => closed); }), ); diff --git a/apps/server/src/preview/ServerBrowserStream.ts b/apps/server/src/preview/ServerBrowserStream.ts index e46a0c76adb5..649af3b31d0d 100644 --- a/apps/server/src/preview/ServerBrowserStream.ts +++ b/apps/server/src/preview/ServerBrowserStream.ts @@ -20,7 +20,8 @@ import { } from "effect/http"; import * as Socket from "effect/socket/Socket"; -import { authenticateMediaRequest } from "../auth/http.ts"; +import { authenticateMediaRequest, failEnvironmentInternal } from "../auth/http.ts"; +import * as SessionStore from "../auth/SessionStore.ts"; import { assetResponseHeaders } from "../http.ts"; import * as PreviewBrowserHost from "./PreviewBrowserHost.ts"; import * as ServerBrowser from "./ServerBrowser.ts"; @@ -79,7 +80,8 @@ const makeHandler = Effect.fnUntraced(function* (browser: ServerBrowser.ServerBr if (threadId.length === 0 || tabId.length === 0) { return HttpServerResponse.text("Not Found", { status: 404 }); } - return yield* Effect.scoped( + const sessions = yield* SessionStore.SessionStore; + const stream = Effect.scoped( Effect.gen(function* () { const attached = yield* browser .attachViewer({ @@ -198,7 +200,9 @@ const makeHandler = Effect.fnUntraced(function* (browser: ServerBrowser.ServerBr const receiveInput = reader.pull.pipe( Effect.flatMap((chunks) => Effect.forEach(chunks, receive, { discard: true })), ); - return yield* Effect.raceFirst(Effect.forever(sendOutput), Effect.forever(receiveInput)); + return yield* Effect.raceFirst(Effect.forever(sendOutput), Effect.forever(receiveInput)).pipe( + Effect.onInterrupt(() => Effect.sync(() => transport.destroy())), + ); }), ).pipe( Effect.catchTags({ @@ -209,6 +213,16 @@ const makeHandler = Effect.fnUntraced(function* (browser: ServerBrowser.ServerBr }), Effect.orElseSucceed(() => HttpServerResponse.empty()), ); + return yield* Effect.raceFirst( + stream, + sessions.awaitInvalidation(session.sessionId).pipe( + Effect.as(HttpServerResponse.empty()), + Effect.catchTags({ + SessionCredentialVerificationError: (error) => + failEnvironmentInternal("internal_error", error), + }), + ), + ); }); const hostSetup = (cause: unknown): PreviewStreamHostSetup | undefined => From d35ec21cdd029ce6f97fa963e9a3263662fb1320 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Tue, 17 Nov 2026 10:43:55 +0100 Subject: [PATCH 018/133] fix(server): agents can open Linear issues by URL (#37968) Co-authored-by: Julius Marminge --- apps/server/src/issue/IssueService.test.ts | 59 ++++++++++++++++++- apps/server/src/issue/IssueService.ts | 56 ++++++++++++++---- .../src/server/LinearIssueTracker.test.ts | 34 +++++++++++ .../src/server/LinearIssueTracker.ts | 7 +++ .../src/server/IssueTracker.ts | 3 + 5 files changed, 147 insertions(+), 12 deletions(-) diff --git a/apps/server/src/issue/IssueService.test.ts b/apps/server/src/issue/IssueService.test.ts index ccbeb8727972..5a5d9753c36d 100644 --- a/apps/server/src/issue/IssueService.test.ts +++ b/apps/server/src/issue/IssueService.test.ts @@ -37,7 +37,12 @@ function fakeStandaloneTracker( ...fakeTracker({ getViewer: () => Effect.succeed("usr_julius"), getIssue: (input) => - Effect.succeed({ ...issue(input.key), displayKey: input.key, viewer: "usr_julius" }), + Effect.succeed({ + ...issue(input.key), + url: `https://linear.app/acme/issue/${input.key}/canonical-title`, + displayKey: input.key, + viewer: "usr_julius", + }), ...overrides, }), kind: LINEAR, @@ -48,6 +53,18 @@ function fakeStandaloneTracker( scopeNoun: "team", credential: { label: "Personal API key", helpUrl: null }, }, + parseIssueUrl: (url) => { + const links = new Map([ + ["https://linear.app/acme/issue/ENG-1/old-title", "acme"], + ["https://linear.app/acme/issue/ENG-1/issue-title", "acme"], + ["https://linear.app/acme/issue/ENG-1/canonical-title", "acme"], + ["https://linear.app/other-workspace/issue/ENG-1/old-title", "other-workspace"], + ]); + const workspace = links.get(url.href); + return workspace === undefined + ? null + : { host: "linear.app", workspace, scope: "ENG", key: "ENG-1" }; + }, probeCredential: () => Effect.succeed({ account: "julius", scopes: [] }), }; } @@ -437,6 +454,31 @@ describe("IssueService", () => { }); describe("IssueService with a standalone tracker", () => { + it.effect("rejects a URL from another workspace with the same team and issue key", () => + Effect.gen(function* () { + const service = yield* makeService({ + projects: [project({ id: "web" })], + trackers: [fakeStandaloneTracker()], + bindings: { web: { tracker: LINEAR, scope: "ENG" } }, + }); + expect( + yield* service.resolveUrl("https://linear.app/acme/issue/ENG-1/old-title"), + ).toMatchObject({ key: "ENG-1", writable: true }); + const refused = yield* service + .resolveUrl("https://linear.app/other-workspace/issue/ENG-1/old-title") + .pipe(Effect.result); + expect(refused).toMatchObject({ + _tag: "Failure", + failure: { + _tag: "IssueOperationError", + operation: "resolveUrl", + reason: "not-found", + detail: "This issue URL does not belong to the connected workspace.", + }, + }); + }), + ); + it.effect("lists a bound project's standalone scope beside its git host and serves both", () => Effect.gen(function* () { const listed: string[] = []; @@ -490,6 +532,21 @@ describe("IssueService with a standalone tracker", () => { }), ).toMatchObject({ host: "github.com", writable: true }); + const resolved = yield* bound + .resolveUrl("https://linear.app/acme/issue/ENG-1/issue-title", "web" as ProjectId) + .pipe(Effect.result); + expect(resolved).toMatchObject({ + _tag: "Success", + success: { + projectId: "web", + tracker: LINEAR, + host: "linear.app", + scope: "ENG", + key: "ENG-1", + writable: true, + }, + }); + // Unbound, the standalone scope is gone and its references are unsupported. listed.length = 0; const unbound = yield* makeService({ projects, trackers }); diff --git a/apps/server/src/issue/IssueService.ts b/apps/server/src/issue/IssueService.ts index e2312582dbc1..7da9674d1cdd 100644 --- a/apps/server/src/issue/IssueService.ts +++ b/apps/server/src/issue/IssueService.ts @@ -36,7 +36,9 @@ import { IssueTrackerError, isStandaloneIssueTracker, type IssueTrackerApi, + type StandaloneIssueTrackerApi, } from "@t3tools/source-control-core/server/IssueTracker"; +import { parseUrl } from "@t3tools/shared/url"; import * as IssueTrackerBindings from "../persistence/IssueTrackerBindings.ts"; import * as ProjectService from "../project/ProjectService.ts"; @@ -91,6 +93,16 @@ function resolveGitHostBinding(project: OrchestrationProjectShell): ProjectTrack }; } +function findStandaloneIssueUrl(trackers: ReadonlyArray, value: string) { + const url = parseUrl(value); + if (url === null) return null; + for (const api of trackers) { + const link = api.parseIssueUrl(url); + if (link !== null) return { api, tracker: api.kind, link }; + } + return null; +} + /** Lower case, so a scope keeps its cursor whichever project's spelling of it is read. */ function listCursorKey(host: string, scope: string): string { return `${host} ${scope.toLowerCase()}`; @@ -145,15 +157,14 @@ export class IssueService extends Context.Service< readonly update: (input: IssueUpdateInput) => Effect.Effect; readonly setState: (input: IssueSetStateInput) => Effect.Effect; readonly react: (input: IssueReactionInput) => Effect.Effect; - /** - * The reference behind an issue URL: served by the project whose binding is that host and - * scope, else read-only through any project on the same tracker and host. `preferredProjectId` - * wins among equals, so a thread's own project serves its own issues. - */ /** The tracker and container a project's own issues live in. */ readonly projectScope: ( projectId: ProjectId, ) => Effect.Effect; + /** + * Resolve through a matching project, preferring `preferredProjectId`; other scopes are read-only. + * Standalone links must match the workspace in the issue's canonical URL from the connected tracker. + */ readonly resolveUrl: ( url: string, preferredProjectId?: ProjectId, @@ -627,7 +638,12 @@ const make = Effect.gen(function* () { const resolveUrl: IssueService["Service"]["resolveUrl"] = Effect.fn("IssueService.resolveUrl")( function* (url, preferredProjectId) { - const parsed = sourceControlDefinitions.parseIssueUrl(url); + const gitHost = sourceControlDefinitions.parseIssueUrl(url); + const standalone = gitHost === null ? findStandaloneIssueUrl(registry.standalone, url) : null; + const parsed = + gitHost === null + ? standalone + : { tracker: IssueTrackerKind.make(gitHost.definition.kind), link: gitHost.link }; if (parsed === null) { return yield* new IssueOperationError({ operation: "resolveUrl", @@ -635,24 +651,42 @@ const make = Effect.gen(function* () { detail: "This is not a recognised issue URL.", }); } - const { definition, link } = parsed; + const { tracker, link } = parsed; // A link names its server's port; a binding does only when its remote or web URL did. const authority = new URL(url).host.toLowerCase(); const { supported } = yield* listProjects({ host: link.host, authority }); - const onHost = supported.filter( - (project) => project.tracker === IssueTrackerKind.make(definition.kind), - ); + const onHost = supported.filter((project) => project.tracker === tracker); const onAuthority = onHost.filter((project) => project.host === authority); const onTracker = onAuthority.length > 0 ? onAuthority : onHost; const preferFirst = (projects: ReadonlyArray) => projects.find((project) => project.project.id === preferredProjectId) ?? projects[0]; const own = preferFirst( - onTracker.filter((project) => project.scope.toLowerCase() === link.scope), + onTracker.filter((project) => project.scope.toLowerCase() === link.scope.toLowerCase()), ); const lender = own ?? preferFirst(onTracker); if (lender === undefined) { return yield* new IssueUnavailableError({ reason: "tracker-unsupported" }); } + if (standalone !== null) { + // Team keys repeat across workspaces; only the credential's canonical issue URL identifies one. + const issue = yield* lender.api + .getIssue({ + cwd: lender.project.workspaceRoot, + host: lender.host, + scope: link.scope, + key: link.key, + }) + .pipe(Effect.mapError(toIssueError("resolveUrl"))); + const canonicalUrl = parseUrl(issue.url); + const canonical = canonicalUrl === null ? null : standalone.api.parseIssueUrl(canonicalUrl); + if (canonical === null || canonical.workspace !== standalone.link.workspace) { + return yield* new IssueOperationError({ + operation: "resolveUrl", + reason: "not-found", + detail: "This issue URL does not belong to the connected workspace.", + }); + } + } return { projectId: lender.project.id, tracker: lender.tracker, diff --git a/packages/issue-tracker-linear/src/server/LinearIssueTracker.test.ts b/packages/issue-tracker-linear/src/server/LinearIssueTracker.test.ts index 9490b449cce4..ccaaa62d1488 100644 --- a/packages/issue-tracker-linear/src/server/LinearIssueTracker.test.ts +++ b/packages/issue-tracker-linear/src/server/LinearIssueTracker.test.ts @@ -127,6 +127,40 @@ function fakeLinear( const target = { cwd: "/w/web", host: "linear.app", scope: "ENG" }; describe("LinearIssueTracker", () => { + it.effect("parses Linear issue links with their workspace and team", () => + Effect.gen(function* () { + const api = yield* fakeLinear({}).tracker; + for (const suffix of ["", "/issue-title", "/old-title?view=all#comment"]) { + expect(api.parseIssueUrl(new URL(`https://linear.app/acme/issue/ENG-1${suffix}`))).toEqual({ + host: "linear.app", + workspace: "acme", + scope: "ENG", + key: "ENG-1", + }); + } + expect( + api.parseIssueUrl(new URL("https://linear.app/other-workspace/issue/ENG-1")), + ).toMatchObject({ + workspace: "other-workspace", + key: "ENG-1", + }); + for (const url of [ + "http://linear.app/acme/issue/ENG-1", + "https://example.com/acme/issue/ENG-1", + "https://linear.app.example.com/acme/issue/ENG-1", + "https://linear.app:444/acme/issue/ENG-1", + "https://linear.app/acme/team/ENG-1", + "https://linear.app//issue/ENG-1", + "https://linear.app/acme/issue/", + "https://linear.app/acme/issue/ENG-0", + "https://linear.app/acme/issue/eng-1", + "https://linear.app/acme/issue/ENG-1extra", + ]) { + expect(api.parseIssueUrl(new URL(url)), url).toBeNull(); + } + }), + ); + it.effect("lists a team's issues as summaries keyed by identifier", () => Effect.gen(function* () { const { tracker, requests } = fakeLinear({ diff --git a/packages/issue-tracker-linear/src/server/LinearIssueTracker.ts b/packages/issue-tracker-linear/src/server/LinearIssueTracker.ts index daa4954bdc0d..9721a47471fd 100644 --- a/packages/issue-tracker-linear/src/server/LinearIssueTracker.ts +++ b/packages/issue-tracker-linear/src/server/LinearIssueTracker.ts @@ -418,6 +418,13 @@ export const make: Effect.Effect { + if (url.protocol !== "https:" || url.host.toLowerCase() !== DESCRIPTOR.host) return null; + const [, workspace, resource, key] = url.pathname.split("/"); + if (!workspace || resource !== "issue" || key === undefined) return null; + const scope = /^([A-Z][A-Z0-9_]*)-[1-9][0-9]*$/.exec(key)?.[1]; + return scope === undefined ? null : { host: DESCRIPTOR.host, workspace, scope, key }; + }, probeCredential: (token) => linear.viewer(token).pipe( diff --git a/packages/source-control-core/src/server/IssueTracker.ts b/packages/source-control-core/src/server/IssueTracker.ts index e4fd95c287d4..34b0c2e257d6 100644 --- a/packages/source-control-core/src/server/IssueTracker.ts +++ b/packages/source-control-core/src/server/IssueTracker.ts @@ -26,6 +26,7 @@ import type { StandaloneIssueTrackerDescriptor, } from "@t3tools/contracts"; import { IssueTrackerKind as IssueTrackerKindSchema } from "@t3tools/contracts"; +import type { IssueLink } from "../shared/definition.ts"; /** * The one failure shape every tracker reports, so the service can decide what a failure means @@ -196,6 +197,8 @@ export interface IssueTrackerApi { */ export interface StandaloneIssueTrackerApi extends IssueTrackerApi { readonly standalone: StandaloneIssueTrackerDescriptor; + /** Retains the workspace identity so canonical URLs can disambiguate repeated scope keys. */ + readonly parseIssueUrl: (url: URL) => (IssueLink & { readonly workspace: string }) | null; /** * Who a credential signs in as and which scopes it reaches, asked of the tracker itself. Run on * a credential before it is stored, and on the stored one to report connection status. From 135d7a980120790f9b0611a58bae5d9e9feed6f6 Mon Sep 17 00:00:00 2001 From: Aditya Kumar Puri <113080776+puri-adityakumar@users.noreply.github.com> Date: Tue, 17 Nov 2026 15:23:54 +0530 Subject: [PATCH 019/133] fix(server): a background task's result still shows when the turn before fails (#38035) Co-authored-by: Julius Marminge --- .../src/orchestration-v2/Orchestrator.ts | 40 +++-- .../src/orchestration-v2/runtimeLayer.test.ts | 141 ++++++++++++++++++ 2 files changed, 171 insertions(+), 10 deletions(-) diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 0f6b0e1f20b6..2fcd3c22369a 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -2363,7 +2363,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio return true; }); - const startNextQueuedRun = Effect.fn("Orchestrator.startNextQueuedRun")( + const startNextQueuedRunOnce = Effect.fn("Orchestrator.startNextQueuedRun")( function* ( threadId: ThreadId, options?: { @@ -2483,17 +2483,29 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio projectOverride !== undefined ? !projectOverride : machineInstance !== undefined && !resolveProviderInstanceEnabled(machineInstance); - if ( - worktreeMissing || - instanceDisabledForProject || - (failureClass !== undefined && - failureClass !== "validation_error" && - failedRun?.providerInstanceId === queuedRun.providerInstanceId) - ) { + const providerFailed = + failureClass !== undefined && + failureClass !== "validation_error" && + failedRun?.providerInstanceId === queuedRun.providerInstanceId; + if (worktreeMissing || instanceDisabledForProject || providerFailed) { + // A buffered wake prompts nothing: it replays output the CLI already produced. + const wakes = + worktreeMissing || instanceDisabledForProject + ? [] + : queuedRunsInDeliveryOrder(projection).filter((run) => { + const message = projection.messages.find( + (candidate) => candidate.id === run.userMessageId, + ); + return ( + run.queueHeld !== true && + message !== undefined && + isBufferedProviderNotification(message) + ); + }); const now = yield* DateTime.now; yield* writeSystemEvents( projection.runs - .filter((run) => run.status === "queued") + .filter((run) => run.status === "queued" && !wakes.some((wake) => wake.id === run.id)) .map((run) => ({ type: "run.updated" as const, threadId, @@ -2503,7 +2515,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio payload: { ...run, queueHeld: true }, })), ); - return; + return wakes.length > 0; } // Move queued ordinals after runs that started while they waited to preserve transcript and checkpoint order. // Started runs have prompts; cancelled queued messages do not. @@ -3235,6 +3247,14 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ), ); + // A provider failure hold leaves buffered wakes unheld, so a second pass starts the first one. + const startNextQueuedRun = (...args: Parameters) => + startNextQueuedRunOnce(...args).pipe( + Effect.flatMap((wakeLeftUnheld) => + wakeLeftUnheld === true ? startNextQueuedRunOnce(args[0]) : Effect.void, + ), + ); + // Under load a resumed provider can time out before taking the prompt; the restart still owes the turn. const retryContinuationStart = Effect.fn("Orchestrator.retryContinuationStart")(function* ( threadId: ThreadId, diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index 2720a0c3f419..82fd3381e20d 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -10524,6 +10524,147 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => { }), ); + it.effect("starts a provider wake queued behind a run that fails, holding the rest", () => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const eventSink = yield* EventSink.EventSinkV2; + const threadId = ThreadId.make("queue-hold-provider-wake-after-failure"); + const messageId = (key: string) => MessageId.make(`${threadId}:${key}`); + yield* orchestrator.dispatch({ + type: "thread.create", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make(`${threadId}:create`), + threadId, + projectId: ProjectId.make(`${threadId}:project`), + title: "Wake behind a failed run", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: process.cwd(), + }); + yield* orchestrator.dispatch({ + type: "message.dispatch", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make(`${threadId}:message:active`), + threadId, + messageId: messageId("active"), + text: "Active", + attachments: [], + modelSelection, + dispatchMode: { type: "start_immediately" }, + }); + yield* orchestrator.dispatch({ + type: "message.dispatch", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make(`${threadId}:message:queued`), + threadId, + messageId: messageId("queued"), + text: "Queued by the user", + attachments: [], + modelSelection, + dispatchMode: { type: "queue_after_active" }, + }); + // The CLI started this execution itself as the active turn ended. + yield* orchestrator.dispatch({ + type: "message.dispatch", + createdBy: "agent", + creationSource: "provider", + commandId: CommandId.make(`${threadId}:message:wake`), + threadId, + messageId: messageId("wake"), + text: "Background task completed.", + notification: { + source: { kind: "background_task" }, + outcome: "updated", + summary: "Background activity updated", + }, + attachments: [], + modelSelection, + dispatchMode: { type: "queue_after_active" }, + }); + const { runs } = yield* orchestrator.getThreadProjection(threadId); + const runFor = (key: string) => runs.find((run) => run.userMessageId === messageId(key))!; + const [active, wake, queued] = [runFor("active"), runFor("wake"), runFor("queued")]; + assert.equal(wake.status, "queued"); + assert.notEqual(wake.queueHeld, true); + const afterSequence = yield* orchestrator.getThreadEventSequence(threadId); + const firstUpdateOf = (runId: RunId) => + eventSink.stream({ threadId, afterSequence }).pipe( + Stream.filter( + (stored) => stored.event.type === "run.updated" && stored.event.payload.id === runId, + ), + Stream.runHead, + Effect.forkScoped, + ); + const wakeUpdate = yield* firstUpdateOf(wake.id); + const queuedUpdate = yield* firstUpdateOf(queued.id); + const now = yield* DateTime.now; + yield* eventSink.write({ + events: [ + { + id: EventId.make(`${threadId}:active:error`), + type: "turn-item.updated", + threadId, + runId: active.id, + nodeId: active.rootNodeId!, + providerInstanceId: active.providerInstanceId, + occurredAt: now, + payload: { + id: TurnItemId.make(`${threadId}:active:error`), + type: "error", + threadId, + runId: active.id, + nodeId: active.rootNodeId, + providerThreadId: active.providerThreadId, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: 2, + status: "failed", + title: "Provider failure", + startedAt: now, + completedAt: now, + updatedAt: now, + failure: { + class: "provider_error", + message: "Provider request failed with HTTP 502", + code: null, + retryable: null, + }, + }, + }, + { + id: EventId.make(`${threadId}:active:failed`), + type: "run.updated", + threadId, + runId: active.id, + providerInstanceId: active.providerInstanceId, + occurredAt: now, + payload: { ...active, status: "failed", startedAt: now, completedAt: now }, + }, + ], + }); + const queuedEvent = Option.getOrUndefined(yield* Fiber.join(queuedUpdate))?.event; + assert.deepInclude( + queuedEvent?.type === "run.updated" ? queuedEvent.payload : undefined, + { status: "queued", queueHeld: true }, + "the user's queued message waits after the provider failure", + ); + const wakeEvent = Option.getOrUndefined(yield* Fiber.join(wakeUpdate))?.event; + const wakeRun = wakeEvent?.type === "run.updated" ? wakeEvent.payload : undefined; + assert.notEqual( + wakeRun?.queueHeld, + true, + "the provider wake replays output the CLI already produced, so the failure must not hold it", + ); + assert.equal(wakeRun?.status, "starting"); + }), + ); + it.effect("edits and removes queued runs", () => Effect.gen(function* () { const orchestrator = yield* Orchestrator.OrchestratorV2; From 10784e01f8b5158ef0f6d61ebd19a8963c45579d Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 17 Nov 2026 01:57:18 -0800 Subject: [PATCH 020/133] fix: expired-session error card asks to pair again and names the rejected request's trace (#38041) --- apps/server/src/http.test.ts | 38 +++++++++++++++++++ apps/server/src/http.ts | 14 +++++++ apps/server/src/server.ts | 3 +- .../src/connection/diagnosis.test.ts | 14 +++++++ .../src/connection/diagnosis.ts | 12 ++++-- 5 files changed, 76 insertions(+), 5 deletions(-) diff --git a/apps/server/src/http.test.ts b/apps/server/src/http.test.ts index 4b97ddb453a4..7b747647984d 100644 --- a/apps/server/src/http.test.ts +++ b/apps/server/src/http.test.ts @@ -234,6 +234,44 @@ describe("untraced requests", () => { expect(serverSpans).toEqual(["GET", "GET", "GET"]); }).pipe(Effect.provide(NodeServices.layer)), ); + + it.effect("starts a separate trace for each request, not the server's lifetime trace", () => + Effect.gen(function* () { + const requestSpans: Array = []; + const layerTracer = Layer.succeed( + Tracer.Tracer, + Tracer.make({ + span: (options) => { + const span = new Tracer.NativeSpan(options); + if (options.kind === "server") requestSpans.push(span); + return span; + }, + }), + ); + const layerRoutes = Layer.effectDiscard( + Effect.gen(function* () { + const router = yield* HttpRouter.HttpRouter; + yield* router.add("GET", "/api/environment", HttpServerResponse.empty()); + }), + ); + const services = yield* Layer.build( + HttpRouter.serve(layerRoutes, { disableListenLog: true, disableLogger: true }).pipe( + ServerHttp.withRootRequestSpans, + Layer.provideMerge(NodeHttpServer.layerTest), + ), + ).pipe(Effect.withSpan("server.lifetime"), Effect.provide(layerTracer)); + // Without a traceparent header, the server alone decides each request's parent. + const client = Context.get(services, HttpClient.HttpClient); + + for (let i = 0; i < 2; i++) { + yield* client + .execute(HttpClientRequest.get("/api/environment")) + .pipe(Effect.provideService(HttpClient.TracerPropagationEnabled, false)); + } + expect(requestSpans.map((span) => span.parent._tag)).toEqual(["None", "None"]); + expect(new Set(requestSpans.map((span) => span.traceId)).size).toBe(2); + }).pipe(Effect.provide(NodeServices.layer)), + ); }); const layerFileResponse = Layer.mergeAll(NodeHttpPlatform.layer, NodeServices.layer); diff --git a/apps/server/src/http.ts b/apps/server/src/http.ts index c12a683be3af..fcd7b3c361ee 100644 --- a/apps/server/src/http.ts +++ b/apps/server/src/http.ts @@ -9,6 +9,7 @@ import { injectMcpAppCookieBootstrap, injectMcpAppThemeBootstrap } from "@t3tool import { FILE_PREVIEW_SCROLL_SCRIPT } from "@t3tools/shared/htmlRender"; import { decodeOtlpTraceRecords } from "@t3tools/shared/observability"; import * as ByteSize from "effect/ByteSize"; +import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; @@ -16,6 +17,7 @@ import * as Option from "effect/Option"; import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; import * as Stream from "effect/Stream"; +import * as Tracer from "effect/Tracer"; import { cast, pipe } from "effect/Function"; import { HttpClient, @@ -432,6 +434,18 @@ const layerUntracedRequests = Layer.succeed(HttpMiddleware.TracerDisabledWhen)(( export const withUntracedRequests = Layer.provide(layerUntracedRequests); +// Request spans otherwise parent to the server's lifetime span, so every request shares one trace id. +export const withRootRequestSpans = (layer: Layer.Layer) => + Layer.fromBuild((memoMap, scope) => + Layer.buildWithMemoMap(layer, memoMap, scope).pipe( + // ParentSpan is optional to every reader, so removing it leaves R satisfied. + Effect.updateContext( + (context: Context.Context) => + Context.omit(Tracer.ParentSpan)(context) as Context.Context, + ), + ), + ); + export const layerAssetRoute = HttpRouter.add( "GET", `${ASSET_ROUTE_PREFIX}/*`, diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 9aa178a39980..29e3143cbc63 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -32,7 +32,7 @@ import * as HostPowerMonitor from "./background/HostPowerMonitor.ts"; import * as NonBlockingSpawner from "./process/NonBlockingSpawner.ts"; import * as KeepAwake from "./background/KeepAwake.ts"; import * as ServerConfig from "./config.ts"; -import { withUntracedRequests } from "./http.ts"; +import { withRootRequestSpans, withUntracedRequests } from "./http.ts"; import * as ServerHttp from "./http.ts"; import { guardHttpResponseWriteErrors, @@ -1340,6 +1340,7 @@ const layerMakeServer = Layer.unwrap( routerConfig: HTTP_ROUTER_CONFIG, }).pipe( withUntracedRequests, + withRootRequestSpans, Layer.tap(() => Deferred.succeed(routesReady, undefined).pipe(Effect.orDie)), ); const layerServerApplication = Layer.mergeAll( diff --git a/packages/client-runtime/src/connection/diagnosis.test.ts b/packages/client-runtime/src/connection/diagnosis.test.ts index 240197567c12..94396c7cc4f8 100644 --- a/packages/client-runtime/src/connection/diagnosis.test.ts +++ b/packages/client-runtime/src/connection/diagnosis.test.ts @@ -1,3 +1,4 @@ +import { EnvironmentAuthInvalidError } from "@t3tools/contracts"; import { RelayEnvironmentEndpointUnavailableError, type RelayProtectedError, @@ -163,6 +164,19 @@ describe("presentConnectionDiagnosis", () => { expect(diagnosis?.steps.join(" ")).toContain("t3 auth connect-device approve K7QM-2XFD"); }); + it("tells a host that refused this device's login to sign in again, not to start T3 Code", () => { + const failure = mapRemoteEnvironmentError( + new EnvironmentAuthInvalidError({ + code: "auth_invalid", + reason: "invalid_credential", + traceId: "trace-1", + }), + ); + const steps = diagnose(backoff(failure), "direct")?.steps.join(" "); + expect(steps).not.toContain("Make sure T3 Code is running"); + expect(steps).toMatch(/pair|sign in/i); + }); + it("does not report hops as working when the failure names none", () => { const failure = new ConnectionBlockedError({ reason: "authentication", diff --git a/packages/client-runtime/src/connection/diagnosis.ts b/packages/client-runtime/src/connection/diagnosis.ts index f4ed87e8b5f4..cd102c08e872 100644 --- a/packages/client-runtime/src/connection/diagnosis.ts +++ b/packages/client-runtime/src/connection/diagnosis.ts @@ -235,10 +235,14 @@ function steps(host: string, located: Located, failure: ConnectionAttemptError | ] : [`Make sure ${host} is awake and online.`, checkHost]; case "server": - return [ - `Make sure T3 Code is running on ${host}.`, - "Retry. If it keeps failing, copy the diagnostics.", - ]; + return failure?.reason === "authentication" + ? [ + `This device's sign-in to ${host} expired or was revoked. Pair it again with a new pairing link from ${host}.`, + ] + : [ + `Make sure T3 Code is running on ${host}.`, + "Retry. If it keeps failing, copy the diagnostics.", + ]; } } From 215bd59a9851d439b3c04e5532d2d584d6883142 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Tue, 17 Nov 2026 11:02:42 +0100 Subject: [PATCH 021/133] fix(server): Windows uninstall fails when its cleanup shell cannot start (#38043) Co-authored-by: Grok 4.7 Co-authored-by: Julius Marminge --- apps/server/src/cli/uninstall.test.ts | 66 ++++++++++++++++++- apps/server/src/cli/uninstall.ts | 15 +++-- .../src/process/windowsVerbatimSpawn.test.ts | 15 +++++ .../src/process/windowsVerbatimSpawn.ts | 25 +++++-- 4 files changed, 107 insertions(+), 14 deletions(-) create mode 100644 apps/server/src/process/windowsVerbatimSpawn.test.ts diff --git a/apps/server/src/cli/uninstall.test.ts b/apps/server/src/cli/uninstall.test.ts index b93ad204fe64..c22760da5345 100644 --- a/apps/server/src/cli/uninstall.test.ts +++ b/apps/server/src/cli/uninstall.test.ts @@ -1,3 +1,5 @@ +// @effect-diagnostics nodeBuiltinImport:off - The test observes a real cleanup-shell spawn failure. +import * as NodeChildProcess from "node:child_process"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, it } from "@effect/vitest"; import * as Config from "effect/Config"; @@ -10,7 +12,7 @@ import * as TestConsole from "effect/testing/TestConsole"; import { Command } from "effect/cli"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as NetService from "@t3tools/shared/Net"; -import { afterEach, vi } from "vite-plus/test"; +import { afterEach, expect, vi } from "vite-plus/test"; import packageJson from "../../package.json" with { type: "json" }; import * as BootService from "../cloud/bootService.ts"; @@ -22,8 +24,70 @@ import { uninstallCommand, } from "./uninstall.ts"; +vi.mock("node:child_process", { spy: true }); + afterEach(() => vi.restoreAllMocks()); +it.live("reports failure when the Windows cleanup shell cannot start", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-uninstall-shell-" }); + const runtimeDir = path.join(baseDir, "runtime"); + yield* fs.makeDirectory(runtimeDir); + vi.spyOn(BootService, "layer").mockReturnValue( + Layer.succeed( + BootService.BootService, + BootService.BootService.of({ + status: Effect.succeed({ + supported: false, + installed: false, + current: false, + unitPath: "", + logPath: "", + }), + withStopped: (operation) => operation, + restart: Effect.die("unexpected restart"), + install: () => Effect.die("unexpected install"), + uninstall: Effect.die("unexpected uninstall"), + }), + ), + ); + const actual = yield* Effect.promise(() => + vi.importActual("node:child_process"), + ); + const spawn = actual.spawn; + const failedSpawn = new Promise((resolve) => { + vi.spyOn(NodeChildProcess, "spawn").mockImplementation((...args) => { + const child = spawn(...args); + // Observe the real spawn error without letting it terminate the test runner. + child.once("error", resolve); + return child; + }); + }); + const result = yield* Command.runWith(uninstallCommand, { version: packageJson.version })([ + "--base-dir", + baseDir, + "--yes", + ]).pipe( + Effect.result, + Effect.provideService(HostProcess.Environment, { + ComSpec: path.join(baseDir, "missing-cmd.exe"), + }), + Effect.provideService(HostProcess.Platform, "win32"), + Effect.provideService(HostProcess.IsExecutable, false), + Effect.provide( + Layer.mergeAll( + ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })), + Layer.fresh(TestConsole.layer), + ), + ), + ); + yield* Effect.promise(() => failedSpawn); + expect(result._tag, "an unavailable cleanup shell must fail uninstall").toBe("Failure"); + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NetService.layer))), +); + it.layer(Layer.mergeAll(NodeServices.layer, NetService.layer))("t3 uninstall command", (it) => { it.effect("names another home's service it leaves installed", () => Effect.gen(function* () { diff --git a/apps/server/src/cli/uninstall.ts b/apps/server/src/cli/uninstall.ts index 609ece726566..a0d47c738491 100644 --- a/apps/server/src/cli/uninstall.ts +++ b/apps/server/src/cli/uninstall.ts @@ -22,6 +22,7 @@ import { } from "../cloud/pinnedRuntime.ts"; import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts"; import * as CliService from "./service.ts"; +import { awaitDetachedSpawn } from "../process/windowsVerbatimSpawn.ts"; import { findWindowsShim } from "./update.ts"; export class CliUninstallError extends Schema.TaggedError()( @@ -277,13 +278,13 @@ const runUninstall = Effect.fn("cli.uninstall.run")(function* (input: { if (platform === "win32") { const runtimeDir = plan.runtimeDir; const comspec = environment["ComSpec"] ?? environment["COMSPEC"] ?? "cmd.exe"; - yield* Effect.try({ - try: () => spawnWindowsRemoval(comspec, runtimeDir).unref(), - catch: () => - new CliUninstallError({ - reason: `Could not schedule removal of ${runtimeDir}. Delete it yourself once this window is closed.`, - }), - }); + const notScheduled = () => + new CliUninstallError({ + reason: `Could not schedule removal of ${runtimeDir}. Delete it yourself once this window is closed.`, + }); + yield* awaitDetachedSpawn(() => spawnWindowsRemoval(comspec, runtimeDir)).pipe( + Effect.mapError(notScheduled), + ); yield* Console.log(`${runtimeDir} will be removed once t3 exits.`); } else { yield* fs diff --git a/apps/server/src/process/windowsVerbatimSpawn.test.ts b/apps/server/src/process/windowsVerbatimSpawn.test.ts new file mode 100644 index 000000000000..03c90a5d2fa3 --- /dev/null +++ b/apps/server/src/process/windowsVerbatimSpawn.test.ts @@ -0,0 +1,15 @@ +import { it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import { expect } from "vite-plus/test"; + +import { awaitDetachedSpawn } from "./windowsVerbatimSpawn.ts"; + +it.effect("reports a synchronous spawn exception as a failure", () => + Effect.gen(function* () { + const error = new Error("invalid spawn options"); + const result = yield* awaitDetachedSpawn(() => { + throw error; + }).pipe(Effect.result); + expect(result).toMatchObject({ _tag: "Failure", failure: error }); + }), +); diff --git a/apps/server/src/process/windowsVerbatimSpawn.ts b/apps/server/src/process/windowsVerbatimSpawn.ts index 15075c22455b..c060a78dfc47 100644 --- a/apps/server/src/process/windowsVerbatimSpawn.ts +++ b/apps/server/src/process/windowsVerbatimSpawn.ts @@ -1,6 +1,7 @@ // @effect-diagnostics nodeBuiltinImport:off - Effect's spawner has no windowsVerbatimArguments option. import * as NodeChildProcess from "node:child_process"; +import * as Cause from "effect/Cause"; import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; @@ -9,13 +10,16 @@ export type WindowsVerbatimSpawner = ( args: ReadonlyArray, ) => Effect.Effect; -const spawnDetachedVerbatim: WindowsVerbatimSpawner = (command, args) => +/** Succeeds once a detached child has started and no longer holds this process open; fails if it cannot start. */ +export const awaitDetachedSpawn = (spawn: () => NodeChildProcess.ChildProcess) => Effect.callback((resume) => { - const child = NodeChildProcess.spawn(command, args, { - detached: true, - stdio: "ignore", - windowsVerbatimArguments: true, - }); + let child: NodeChildProcess.ChildProcess; + try { + child = spawn(); + } catch (error) { + resume(Effect.fail(error instanceof Error ? error : new Cause.UnknownError(error))); + return; + } child.once("error", (error) => resume(Effect.fail(error))); child.once("spawn", () => { child.unref(); @@ -23,6 +27,15 @@ const spawnDetachedVerbatim: WindowsVerbatimSpawner = (command, args) => }); }); +const spawnDetachedVerbatim: WindowsVerbatimSpawner = (command, args) => + awaitDetachedSpawn(() => + NodeChildProcess.spawn(command, args, { + detached: true, + stdio: "ignore", + windowsVerbatimArguments: true, + }), + ); + export const WindowsVerbatimSpawn = Context.Reference( "t3/process/WindowsVerbatimSpawn", { defaultValue: () => spawnDetachedVerbatim }, From 134580067f3c811f32630667bd57f048d0bff9ee Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Tue, 17 Nov 2026 11:18:48 +0100 Subject: [PATCH 022/133] fix(mobile): recovering a failed task keeps a paste that lands while it saves (#38031) Co-authored-by: Grok 4.7 Co-authored-by: Julius Marminge --- .../src/state/recover-failed-thread-draft.ts | 39 ++++++-- .../src/state/threadOutboxDelivery.test.ts | 95 +++++++++++++++++++ apps/mobile/src/state/use-composer-drafts.ts | 13 ++- 3 files changed, 134 insertions(+), 13 deletions(-) diff --git a/apps/mobile/src/state/recover-failed-thread-draft.ts b/apps/mobile/src/state/recover-failed-thread-draft.ts index 25573ee3363c..ca7e3bfefa35 100644 --- a/apps/mobile/src/state/recover-failed-thread-draft.ts +++ b/apps/mobile/src/state/recover-failed-thread-draft.ts @@ -1,5 +1,7 @@ import type { QueuedThreadMessage } from "./thread-outbox-model"; +import type { DraftComposerAttachment } from "../lib/composerImages"; import { scopedThreadKey } from "../lib/scopedEntities"; +import { abortComposerDraftOperations } from "./composerDraftOperations"; import { restoredNewTaskDraftKey } from "./new-task-draft-key"; import { appendComposerDraftAttachments, @@ -13,22 +15,43 @@ export async function recoverFailedThreadDraft(message: QueuedThreadMessage): Pr const sourceKey = scopedThreadKey(message.environmentId, message.threadId); const targetKey = restoredNewTaskDraftKey(message.messageId); const source = getComposerDraftSnapshot(sourceKey); - if (source.text.length === 0 && source.attachments.length === 0) return; + if (source.text.length === 0 && source.attachments.length === 0) { + abortComposerDraftOperations(sourceKey); + return; + } await mergeComposerDraftContent(targetKey, { text: source.text, context: source.context, attachments: [], }); - const existingIds = new Set( - getComposerDraftSnapshot(targetKey).attachments.map((attachment) => attachment.id), - ); + // Recovery may exceed caps; preserve every file and leave trimming to the editor. + appendComposerDraftAttachments(targetKey, attachmentsMissingFrom(targetKey, source.attachments), { + restore: true, + }); + await flushComposerDrafts(); + abortComposerDraftOperations(sourceKey); + // A paste still preparing can land in the source during the saves; move it with its reference. + const sourceIds = new Set(source.attachments.map((attachment) => attachment.id)); appendComposerDraftAttachments( targetKey, - source.attachments.filter((attachment) => !existingIds.has(attachment.id)), - { restore: true }, + attachmentsMissingFrom( + targetKey, + getComposerDraftSnapshot(sourceKey).attachments.filter( + (attachment) => !sourceIds.has(attachment.id), + ), + ), + { restore: true, appendReference: true }, ); - // Recovery may exceed caps; preserve every file and leave trimming to the editor. - await flushComposerDrafts(); clearComposerDraftContent(sourceKey); } + +function attachmentsMissingFrom( + draftKey: string, + attachments: ReadonlyArray, +) { + const existingIds = new Set( + getComposerDraftSnapshot(draftKey).attachments.map((attachment) => attachment.id), + ); + return attachments.filter((attachment) => !existingIds.has(attachment.id)); +} diff --git a/apps/mobile/src/state/threadOutboxDelivery.test.ts b/apps/mobile/src/state/threadOutboxDelivery.test.ts index aa6e04c1867c..e77ce11e2c72 100644 --- a/apps/mobile/src/state/threadOutboxDelivery.test.ts +++ b/apps/mobile/src/state/threadOutboxDelivery.test.ts @@ -6,6 +6,7 @@ import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; import { CommandId, + ComposerContextId, EnvironmentId, MessageId, ProjectId, @@ -158,6 +159,7 @@ import { pendingThreadCreationOutcomesAtom } from "./pending-thread-creation"; import { clearThreadComposerError, threadComposerErrorsAtom } from "./thread-composer-error"; import type { QueuedThreadMessage } from "./thread-outbox-model"; import * as composerDrafts from "./use-composer-drafts"; +import { startComposerDraftOperation } from "./composerDraftOperations"; import { recoverFailedThreadDraft } from "./recover-failed-thread-draft"; import { editingQueuedMessageIdsAtom } from "./use-thread-outbox"; import { @@ -789,6 +791,99 @@ describe("thread outbox recovery rollback", () => { ); }); + it("keeps a late attachment and its reference when recovery fills the context limit", async () => { + const message: QueuedThreadMessage = { + ...queuedMessage({ messageId: "failed-full-context", text: "Original prompt" }), + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.6-sol" }, + creation: { + projectId: ProjectId.make("project-1"), + workspaceMode: "local", + branch: null, + worktreePath: null, + }, + }; + const sourceKey = `${message.environmentId}:${message.threadId}`; + const targetKey = "new-task:restored-failed-full-context"; + await composerDrafts.waitForComposerDraftsLoaded(); + const contextDraft = (start: number) => { + const records = Array.from({ length: 100 }, (_, index) => ({ + version: 1 as const, + contextId: ComposerContextId.make(`skill-${start + index}`), + kind: "skill" as const, + label: "Skill", + name: "skill", + })); + return { + text: records + .map((record) => `[Skill](t3-context://v1/skill/${record.contextId})`) + .join(" "), + context: { version: 1 as const, records }, + attachments: [], + }; + }; + appAtomRegistry.set(composerDrafts.composerDraftsAtom, { + [targetKey]: contextDraft(0), + [sourceKey]: contextDraft(100), + }); + const saving = Promise.withResolvers(); + const resume = Promise.withResolvers(); + const write = harness.draftFile.File.prototype.write; + const writeSpy = vi + .spyOn(harness.draftFile.File.prototype, "write") + .mockImplementationOnce(async function (value) { + write(value); + saving.resolve(); + await resume.promise; + }); + const attachment = { + id: "late-paste", + type: "image" as const, + name: "pasted.png", + mimeType: "image/png", + sizeBytes: 1, + dataUrl: "data:image/png;base64,AA==", + previewUri: "data:image/png;base64,AA==", + }; + try { + const recovering = recoverFailedThreadDraft(message); + await saving.promise; + composerDrafts.appendComposerDraftAttachments(sourceKey, [attachment], { + appendReference: true, + }); + resume.resolve(); + await recovering; + const restored = composerDrafts.getComposerDraftSnapshot(targetKey); + expect(restored.attachments).toContainEqual(attachment); + expect(restored.context?.records).toHaveLength(201); + const imageRecord = restored.context?.records.find( + (record) => "attachmentId" in record && record.attachmentId === attachment.id, + ); + expect(imageRecord).toBeDefined(); + expect(restored.text).toContain(`/${imageRecord!.contextId})`); + expect(composerDrafts.getComposerDraftSnapshot(sourceKey).attachments).toEqual([]); + } finally { + resume.resolve(); + writeSpy.mockRestore(); + await composerDrafts.flushComposerDrafts(); + } + }); + + it("cancels a paste that finishes preparing after recovery returns", async () => { + const message = queuedMessage({ messageId: "failed-unfinished-paste", text: "Original" }); + const sourceKey = `${message.environmentId}:${message.threadId}`; + appAtomRegistry.set(composerDrafts.composerDraftsAtom, { + [sourceKey]: { text: "Follow-up", attachments: [] }, + }); + const paste = startComposerDraftOperation(sourceKey); + try { + await recoverFailedThreadDraft(message); + expect(paste.signal.aborted).toBe(true); + } finally { + paste.finish(); + await composerDrafts.flushComposerDrafts(); + } + }); + it("keeps setup edits recoverable when saving their recovery draft fails", async () => { const message = queuedMessage({ messageId: "failed-save", text: "Original prompt" }); const sourceKey = `${message.environmentId}:${message.threadId}`; diff --git a/apps/mobile/src/state/use-composer-drafts.ts b/apps/mobile/src/state/use-composer-drafts.ts index 0306d5e7db5e..0030f6f691b9 100644 --- a/apps/mobile/src/state/use-composer-drafts.ts +++ b/apps/mobile/src/state/use-composer-drafts.ts @@ -403,6 +403,7 @@ function draftWithInsertedContext( draft: ComposerDraft, content: { text: string; context: OrchestrationMessageContext }, target?: ComposerDraftInsertion, + maxContextRecords = COMPOSER_CONTEXT_MAX_RECORDS, ): ComposerDraft | null { const { start, end } = contextInsertionRange(draftKey, draft, target); const before = draft.text.slice(0, start); @@ -412,7 +413,7 @@ function draftWithInsertedContext( const records = new Map(draft.context?.records.map((record) => [record.contextId, record])); for (const record of content.context.records) records.set(record.contextId, record); const context = referencedComposerContext(text, { version: 1, records: [...records.values()] }); - if ((context?.records.length ?? 0) > COMPOSER_CONTEXT_MAX_RECORDS) return null; + if ((context?.records.length ?? 0) > maxContextRecords) return null; rememberComposerDraftSelection( draftKey, text, @@ -1465,9 +1466,10 @@ export function appendComposerDraftAttachments( options?.maxAttachments ?? PROVIDER_SEND_TURN_MAX_ATTACHMENTS, ) - retained.attachments.length, ); - const contextCapacity = options?.appendReference - ? Math.max(0, COMPOSER_CONTEXT_MAX_RECORDS - (retained.context?.records.length ?? 0)) - : attachments.length; + const contextCapacity = + options?.appendReference && !options.restore + ? Math.max(0, COMPOSER_CONTEXT_MAX_RECORDS - (retained.context?.records.length ?? 0)) + : attachments.length; const accepted = attachments.slice(0, Math.min(remaining, contextCapacity)); rejected = attachments.slice(accepted.length); if (accepted.length === 0) { @@ -1483,7 +1485,8 @@ export function appendComposerDraftAttachments( text: records.map(formatComposerContextReference).join(" "), context: { version: 1, records }, }, - options?.insertion, + options.insertion, + options.restore ? Infinity : COMPOSER_CONTEXT_MAX_RECORDS, ); if (!inserted) { rejected = attachments; From 786cf6a7368f7d3ab577b5a8253604b7d74b83ef Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 17 Nov 2026 02:38:33 -0800 Subject: [PATCH 023/133] fix(release): weak glibc version needs no longer raise the .deb libc6 floor (#38061) --- scripts/linux-glibc.test.ts | 11 +++++++++++ scripts/linux-glibc.ts | 3 ++- 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/scripts/linux-glibc.test.ts b/scripts/linux-glibc.test.ts index 7efcf1a4819a..7807fd6fa928 100644 --- a/scripts/linux-glibc.test.ts +++ b/scripts/linux-glibc.test.ts @@ -40,6 +40,17 @@ Version definition section '.gnu.version_d' contains 1 entry: ).toBeUndefined(); }); +// Rust std links pidfd_spawnp@GLIBC_2.39 weakly; the loader only warns when a weak version is missing. +it("does not count weak requirements", () => { + expect( + parseGlibcNeeds(`Version needs section '.gnu.version_r' contains 1 entry: + 0x0010: Version: 1 File: libc.so.6 Cnt: 2 + 0x0150: Name: GLIBC_2.34 Flags: none Version: 2 + 0x0160: Name: GLIBC_2.39 Flags: WEAK Version: 10 +`), + ).toBe("2.34"); +}); + it.each(["GLIBC_PRIVATE", "GLIBC_ABI_UNKNOWN"])("rejects unhandled requirement %s", (name) => { expect(() => parseGlibcNeeds(`Version needs section '.gnu.version_r' contains 1 entry: diff --git a/scripts/linux-glibc.ts b/scripts/linux-glibc.ts index 9cc56eee36f5..85c5834481af 100644 --- a/scripts/linux-glibc.ts +++ b/scripts/linux-glibc.ts @@ -25,7 +25,8 @@ export function parseGlibcNeeds(output: string): string | undefined { if (line.startsWith("Version ")) inNeeds = line.startsWith("Version needs section "); if (!inNeeds) continue; const name = /\bName:\s+(GLIBC_\S+)/.exec(line)?.[1]; - if (!name) continue; + // The loader only warns when a WEAK version is missing, so it does not raise the floor. + if (!name || /\bFlags:[^:]*\bWEAK\b/.test(line)) continue; // DT_RELR's named ABI requirement was introduced in glibc 2.36. const version = name === "GLIBC_ABI_DT_RELR" ? "2.36" : /^GLIBC_(\d+(?:\.\d+)+)$/.exec(name)?.[1]; From 6ef2c05410b43a06eea6493a0dc66c1c92f5592f Mon Sep 17 00:00:00 2001 From: Fuksss Date: Tue, 17 Nov 2026 11:49:19 +0100 Subject: [PATCH 024/133] fix(server): t3_thread_send_attachments says why a send was refused (#38058) Co-authored-by: Julius Marminge --- apps/server/src/mcp/OrchestratorMcpService.ts | 4 +- .../src/mcp/toolkits/attachment/handlers.ts | 7 +- apps/server/src/mcp/toolkits/core.test.ts | 94 +++++++++++++++++++ 3 files changed, 101 insertions(+), 4 deletions(-) diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index 092d9f324106..95e269c64c97 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -240,13 +240,13 @@ export class OrchestratorMcpService extends Context.Service< OrchestratorMcpServiceShape >()("t3/mcp/OrchestratorMcpService") {} -const isThreadManagementError = Schema.is(ThreadManagementService.ThreadManagementError); +export const isThreadManagementError = Schema.is(ThreadManagementService.ThreadManagementError); function failure(code: OrchestratorMcpFailure["code"], message: string): OrchestratorMcpFailure { return new OrchestratorMcpFailure({ code, message }); } -function threadManagementFailure(error: unknown): OrchestratorMcpFailure { +export function threadManagementFailure(error: unknown): OrchestratorMcpFailure { if (!isThreadManagementError(error)) return failure("orchestration_error", errorMessage(error)); switch (error._tag) { case "ThreadManagementThreadNotFoundError": diff --git a/apps/server/src/mcp/toolkits/attachment/handlers.ts b/apps/server/src/mcp/toolkits/attachment/handlers.ts index 032ab3a1d0ed..25d0ac7fad15 100644 --- a/apps/server/src/mcp/toolkits/attachment/handlers.ts +++ b/apps/server/src/mcp/toolkits/attachment/handlers.ts @@ -12,7 +12,8 @@ import * as Upload from "../../../assets/AttachmentUpload.ts"; import * as Claims from "../../../orchestration-v2/AttachmentClaims.ts"; import * as ThreadMessageIntake from "../../../orchestration-v2/ThreadMessageIntake.ts"; import * as McpToolAccess from "../../McpToolAccess.ts"; -import { newCommandId, readThread, unavailable } from "../../threadAccess.ts"; +import { isThreadManagementError, threadManagementFailure } from "../../OrchestratorMcpService.ts"; +import { dispatchFailure, newCommandId, readThread, unavailable } from "../../threadAccess.ts"; import { AttachmentToolkit } from "./tools.ts"; export function resolveAttachmentReferences( @@ -118,7 +119,9 @@ export const layer = McpToolAccess.toLayer( code: "orchestration_error", message: error.message, }) - : unavailable(), + : isThreadManagementError(error) + ? threadManagementFailure(error) + : dispatchFailure(error), ), ); return { diff --git a/apps/server/src/mcp/toolkits/core.test.ts b/apps/server/src/mcp/toolkits/core.test.ts index a520e74fd836..af2501b295c5 100644 --- a/apps/server/src/mcp/toolkits/core.test.ts +++ b/apps/server/src/mcp/toolkits/core.test.ts @@ -1420,6 +1420,100 @@ it.effect("only the caller that prepared a pending upload can discard it", () => ), ); +const sendTargetId = ThreadId.make("send-target-thread"); +const sendCommand = { + commandId: CommandId.make("mcp-core-send"), + commandType: "message.dispatch", +}; + +it.effect.each([ + { + outcome: "says that the missing workspace could not be recreated", + refusal: new ThreadManagement.ThreadManagementWorktreeRestoreError({ + threadId: sendTargetId, + cause: new Error("The branch no longer exists."), + }), + reply: { + _tag: "OrchestratorMcpFailure", + code: "thread_not_sendable", + message: + "Couldn't recreate the missing workspace of thread send-target-thread, so the message was not sent. The branch no longer exists.", + }, + }, + { + outcome: "passes on the text reason of an orchestrator rejection", + refusal: new OrchestratorCommandRejectedError({ + ...sendCommand, + cause: "Thread send-target-thread is deleted.", + }), + reply: { + _tag: "OrchestratorMcpFailure", + code: "orchestration_error", + message: "Thread send-target-thread is deleted.", + }, + }, + { + outcome: "keeps an internal dispatch cause private", + refusal: new OrchestratorDispatchError({ + ...sendCommand, + cause: new Error("private-storage-path"), + }), + reply: { + _tag: "OrchestratorMcpFailure", + code: "orchestration_error", + message: "The operation could not be completed.", + }, + }, +])("t3_thread_send_attachments $outcome", ({ refusal, reply }) => { + const stored = ChatImageAttachment.make({ + type: "image", + id: "owned-image", + name: "original.png", + mimeType: "image/png", + sizeBytes: 12, + }); + return Effect.gen(function* () { + const server = yield* McpServer.McpServer; + const result = yield* server + .callTool({ + name: "t3_thread_send_attachments", + arguments: { threadId: sendTargetId, message: "See the file.", attachments: [stored] }, + }) + .pipe( + Effect.provideService(McpInvocationContext.McpInvocationContext, scope), + Effect.provideService(McpSchema.McpServerClient, client), + ); + expect(declaredFailure(result)).toEqual(reply); + }).pipe( + Effect.provide( + McpHttpServer.layerAttachmentToolkit.pipe( + Layer.provideMerge(McpHttpServer.layerInProcessMcpServer), + Layer.provide( + Layer.mock(ThreadManagement.ThreadManagementService)({ + getThreadShell: (id) => Effect.succeed(McpToolAccessTestkit.liveThreadShell(id)), + getProjectThreadRecords: () => + Effect.succeed({ + ...McpToolAccessTestkit.idleThreadProjection( + McpToolAccessTestkit.liveThreadShell(sendTargetId), + ), + messages: [{ attachments: [stored] }], + } as never), + sendToThread: () => Effect.fail(refusal), + }), + ), + Layer.provide(AssetSigner.layer.pipe(Layer.provideMerge(ServerSecretStore.layer))), + Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-mcp-attachment-" })), + Layer.provide( + DocumentText.layer.pipe( + Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), + ), + ), + Layer.provide(NodeCrypto.layer), + ), + ), + ); +}); + it.effect( "t3_thread_list settled:false with an empty statuses list lists the unsettled threads", () => { From 1379dd0bc6fd02191974afef60b5c4f42dec23bb Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 17 Nov 2026 03:15:22 -0800 Subject: [PATCH 025/133] fix(server): keep awake blocks Windows sleep when the server runs in WSL (#38072) --- apps/server/src/background/KeepAwake.ts | 47 +++++++++++++++++++++---- 1 file changed, 41 insertions(+), 6 deletions(-) diff --git a/apps/server/src/background/KeepAwake.ts b/apps/server/src/background/KeepAwake.ts index 5c9c3efc502e..429e49b9c994 100644 --- a/apps/server/src/background/KeepAwake.ts +++ b/apps/server/src/background/KeepAwake.ts @@ -1,5 +1,6 @@ import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as ChildProcess from "effect/process/ChildProcess"; import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; @@ -17,14 +18,38 @@ import * as Settings from "../serverSettings.ts"; // Bridges gaps between back-to-back runs, so a long-idle machine does not sleep mid-queue. const RELEASE_GRACE = Duration.seconds(60); +// ES_CONTINUOUS | ES_SYSTEM_REQUIRED, held by the calling thread until the script ends. +const WINDOWS_HOLD_SCRIPT = `$t = Add-Type -Name Power -Namespace T3 -PassThru -MemberDefinition '[DllImport("kernel32.dll")] public static extern uint SetThreadExecutionState(uint f);'; [void]$t::SetThreadExecutionState([uint32]2147483649)`; + /** Each command holds its inhibitor until it exits, and exits on its own if the server dies. */ function inhibitorCommand( platform: NodeJS.Platform, serverPid: number, -): { readonly command: string; readonly args: ReadonlyArray } | undefined { + isWsl: boolean, +): + | { + readonly command: string; + readonly args: ReadonlyArray; + readonly stdin: "ignore" | "pipe"; + } + | undefined { + // logind inside the WSL VM cannot block Windows sleep. Windows cannot wait on a Linux pid, so + // the hold ends when its stdin pipe closes, which also happens if the server dies. + if (isWsl) { + return { + command: "powershell.exe", + args: [ + "-NoProfile", + "-NonInteractive", + "-Command", + `${WINDOWS_HOLD_SCRIPT}; [void][Console]::In.ReadToEnd()`, + ], + stdin: "pipe", + }; + } switch (platform) { case "darwin": - return { command: "caffeinate", args: ["-i", "-w", String(serverPid)] }; + return { command: "caffeinate", args: ["-i", "-w", String(serverPid)], stdin: "ignore" }; case "linux": return { command: "systemd-inhibit", @@ -38,6 +63,7 @@ function inhibitorCommand( "-f", "/dev/null", ], + stdin: "ignore", }; case "win32": return { @@ -46,9 +72,9 @@ function inhibitorCommand( "-NoProfile", "-NonInteractive", "-Command", - // ES_CONTINUOUS | ES_SYSTEM_REQUIRED, held by this thread until Wait-Process returns. - `$t = Add-Type -Name Power -Namespace T3 -PassThru -MemberDefinition '[DllImport("kernel32.dll")] public static extern uint SetThreadExecutionState(uint f);'; [void]$t::SetThreadExecutionState([uint32]2147483649); Wait-Process -Id ${serverPid}`, + `${WINDOWS_HOLD_SCRIPT}; Wait-Process -Id ${serverPid}`, ], + stdin: "ignore", }; default: return undefined; @@ -96,7 +122,16 @@ class KeepAwakeInhibitorExited extends Schema.TaggedError release.toLowerCase().includes("microsoft")), + Effect.orElseSucceed(() => false), + )); + const command = inhibitorCommand(platform, process.pid, isWsl); if (command === undefined) return; const settings = yield* Settings.ServerSettingsService; const events = yield* OrchestrationEventStore.OrchestrationEventStore; @@ -158,7 +193,7 @@ export const layer = Layer.effectDiscard( ChildProcess.make(command.command, command.args, { detached: false, shell: false, - stdin: "ignore", + stdin: command.stdin, stdout: "ignore", stderr: "ignore", }), From 0b3ebcf268e65a84d797939a2b8c334db973fc8a Mon Sep 17 00:00:00 2001 From: cosier <86030128+matthewcosier@users.noreply.github.com> Date: Tue, 17 Nov 2026 22:20:49 +1100 Subject: [PATCH 026/133] fix(web): sent messages keep the spaces typed at the start of a line (#38079) Co-authored-by: Julius Marminge --- .../components/ChatMarkdown.browser.test.tsx | 44 +- .../chat/MessagesTimeline.browser.test.tsx | 26 ++ apps/web/src/index.css | 8 + apps/web/src/markdown-clipboard.ts | 4 + packages/shared/src/markdownGithubAlerts.ts | 2 +- .../shared/src/markdownLeadingWhitespace.ts | 381 ++++++++++++++++++ .../shared/src/markdownListIndentation.ts | 10 + packages/shared/src/markdownPipeline.test.ts | 240 +++++++++++ packages/shared/src/markdownPipeline.ts | 8 + packages/shared/src/threadFindText.test.ts | 17 + .../sent-message-keeps-leading-spaces.e2e.ts | 35 ++ 11 files changed, 773 insertions(+), 2 deletions(-) create mode 100644 packages/shared/src/markdownLeadingWhitespace.ts create mode 100644 scripts/scenarios/sent-message-keeps-leading-spaces.e2e.ts diff --git a/apps/web/src/components/ChatMarkdown.browser.test.tsx b/apps/web/src/components/ChatMarkdown.browser.test.tsx index bce40138b971..e3ed31ee6902 100644 --- a/apps/web/src/components/ChatMarkdown.browser.test.tsx +++ b/apps/web/src/components/ChatMarkdown.browser.test.tsx @@ -2,6 +2,7 @@ import { MISSING_FILE_ACCESS_MESSAGE } from "@t3tools/client-runtime/state/asset import { EnvironmentId, ThreadId } from "@t3tools/contracts"; import { AsyncResult } from "effect/reactivity"; import { type ReactElement } from "react"; +import remarkGfm from "remark-gfm"; import { describe, expect, it, vi } from "vite-plus/test"; import { page, userEvent } from "vite-plus/test/browser"; @@ -10,7 +11,10 @@ import "../index.css"; import { filesystemEnvironment } from "../state/filesystem"; import { useRightPanelStore } from "../rightPanelStore"; -import { remarkEnableOrderedListNumbers } from "@t3tools/shared/markdownPipeline"; +import { + CHAT_USER_MARKDOWN_REMARK_PLUGINS, + remarkEnableOrderedListNumbers, +} from "@t3tools/shared/markdownPipeline"; import { setMarkdownTaskChecked } from "@t3tools/shared/markdownTaskList"; import { HostImageUrlContext } from "./chat/hostImageUrl"; import { getSyntaxHighlighterPromise } from "~/lib/syntaxHighlighting"; @@ -703,6 +707,44 @@ describe("ChatMarkdown copy", () => { expect(select(labelText, bodyText, "Back up".length)).toBe("Warning\n\nBack up"); }); + it.each([ + { text: " Plan\nnext" }, + { text: "Plan\n Deep\n Deeper" }, + { text: "Plan\n\tTabbed\n \t Mixed" }, + { text: "- item\n more\n deeper\n- next" }, + { text: "Plan\n Step one\n Detail a", from: "Step one" }, + ])( + "copies and selects user lines the same whether their typed indentation shows: $text", + async (copy) => { + setup(); + const copied = async (extraRemarkPlugins: typeof CHAT_USER_MARKDOWN_REMARK_PLUGINS) => { + await using screen = await renderText(copy.text, { + className: "user-message-markdown", + lineBreaks: true, + parseRawHtml: false, + extraRemarkPlugins, + }); + const range = document.createRange(); + range.selectNodeContents(screen.container); + if (copy.from) { + const walker = document.createTreeWalker(screen.container, NodeFilter.SHOW_TEXT); + let line = walker.nextNode(); + while (line && !line.textContent!.includes(copy.from)) line = walker.nextNode(); + // Start mid-line, three characters into the line's text. + range.setStart(line!, line!.textContent!.indexOf(copy.from) + 3); + } + const selection = window.getSelection()!; + selection.removeAllRanges(); + selection.addRange(range); + // A drag or anything else that reads the selection gets its text, not the copy payload. + return { payload: chatMarkdownClipboardPayload(selection), selected: selection.toString() }; + }; + const shown = await copied(CHAT_USER_MARKDOWN_REMARK_PLUGINS); + // The user pipeline as it was before typed indentation was shown. + expect(shown).toEqual(await copied([[remarkGfm, { singleTilde: false }]])); + }, + ); + it("copies part of inline code without prose escapes", async () => { setup(); await using screen = await renderText("Read `items[0]*_x` and a*b*c."); diff --git a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx index ac3316d17b16..013d478127b4 100644 --- a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx @@ -49,6 +49,8 @@ import { ViewedImagesTimelineRow } from "./TimelineWorkEntryRow"; import { remarkThoughtPreview, THOUGHT_PREVIEW_MAX_LENGTH } from "./TimelineWorkEntryRow.logic"; import { TimelineRowCtx } from "./timelineRowContext"; import { parseMarkdownWithMath } from "@t3tools/shared/markdownMath"; +import { searchableMessageSegments } from "@t3tools/shared/threadFindText"; +import { countThreadSearchOccurrences } from "@t3tools/shared/threadSearch"; import { collectThreadFindRanges } from "./threadFindHighlights"; import { toastManager } from "../ui/toast"; import type { CitedHistory } from "./citationProcedure"; @@ -865,6 +867,30 @@ describe("MessagesTimeline messages", () => { expect((globalThis as { __t3Xss?: number }).__t3Xss).toBeUndefined(); }); + it("shows the spaces typed at the start of user lines, where find also matches them", async () => { + const source = "Plan\n Step one\n\tDetail"; + await using screen = await renderTimeline([ + message(source), + message(source, { role: "assistant" }, "assistant-1"), + ]); + const [user, assistant] = screen.container.querySelectorAll( + "[data-timeline-row-kind=message]", + ); + expect(user?.querySelector("[data-user-message-body]")?.innerText).toBe(source); + expect(assistant?.querySelector(".chat-markdown")?.innerText).toBe( + "Plan Step one Detail", + ); + const query = " Step one"; + const indexed = searchableMessageSegments({ role: "user", text: source, streaming: false }); + const ranges = collectThreadFindRanges(screen.container, query); + expect(ranges.map(({ rowId, range }) => [rowId, range.toString()])).toEqual([ + [user?.closest("[data-timeline-row-id]")?.getAttribute("data-timeline-row-id"), query], + ]); + expect( + indexed?.reduce((count, segment) => count + countThreadSearchOccurrences(segment, query), 0), + ).toBe(ranges.length); + }); + it("keeps single tildes in user paths literal without changing double tildes or assistant text", async () => { const source = "Install the skill as ~/folder-a/skills/x, then follow the guide (~/folder-a/guide.md)."; diff --git a/apps/web/src/index.css b/apps/web/src/index.css index 1ec48f9f6182..05541d3970d1 100644 --- a/apps/web/src/index.css +++ b/apps/web/src/index.css @@ -2015,6 +2015,14 @@ code { list-style-type: decimal; } +/* Spaces a user typed at the start of a line, which Markdown would otherwise drop. pre-wrap, not + pre, so an indent wider than the bubble wraps instead of pushing the line's text out of view. + Not selectable, so a selection, a drag or a copy carries the text as it did before. */ +.chat-markdown.user-message-markdown [data-leading-whitespace] { + white-space: pre-wrap; + user-select: none; +} + .chat-markdown li + li { margin-top: 0.25rem; } diff --git a/apps/web/src/markdown-clipboard.ts b/apps/web/src/markdown-clipboard.ts index 396607230518..ad102416f57f 100644 --- a/apps/web/src/markdown-clipboard.ts +++ b/apps/web/src/markdown-clipboard.ts @@ -545,6 +545,10 @@ export function chatMarkdownClipboardPayload( const container = document.createElement("div"); container.appendChild(range.cloneContents()); keepStartListNumbers(range, container); + // The indentation typed at a line start only shows; pasted, it would turn lines into code. + for (const indentation of container.querySelectorAll("[data-leading-whitespace]")) { + indentation.remove(); + } const ancestor = range.commonAncestorContainer; const ancestorElement = ancestor.nodeType === Node.ELEMENT_NODE ? (ancestor as Element) : ancestor.parentElement; diff --git a/packages/shared/src/markdownGithubAlerts.ts b/packages/shared/src/markdownGithubAlerts.ts index d4a701a30f56..b6bb0404620e 100644 --- a/packages/shared/src/markdownGithubAlerts.ts +++ b/packages/shared/src/markdownGithubAlerts.ts @@ -7,7 +7,7 @@ interface MarkdownAstNode { children?: MarkdownAstNode[]; } -const GITHUB_ALERT_MARKER = /^\[!(NOTE|TIP|IMPORTANT|WARNING|CAUTION)\](?:\r?\n|$)/i; +export const GITHUB_ALERT_MARKER = /^\[!(NOTE|TIP|IMPORTANT|WARNING|CAUTION)\](?:\r?\n|$)/i; function readGithubAlert(node: MarkdownAstNode): void { if (node.type !== "blockquote") return; diff --git a/packages/shared/src/markdownLeadingWhitespace.ts b/packages/shared/src/markdownLeadingWhitespace.ts new file mode 100644 index 000000000000..3b7752cefe9e --- /dev/null +++ b/packages/shared/src/markdownLeadingWhitespace.ts @@ -0,0 +1,381 @@ +import type { Root } from "mdast"; +import type { Transformer } from "unified"; + +import { GITHUB_ALERT_MARKER } from "./markdownGithubAlerts.ts"; + +interface MarkdownPoint { + readonly line: number; + readonly column: number; + readonly offset?: number | undefined; +} + +interface MarkdownNode { + readonly type: string; + value?: string; + position?: { readonly start: MarkdownPoint; readonly end: MarkdownPoint } | undefined; + children?: MarkdownNode[]; + data?: Record | undefined; +} + +type Container = + | { readonly kind: "quote" } + | { readonly kind: "item"; readonly node: MarkdownNode; indent?: number | null } + // Recovered list content starts past the item's indentation, so its lines measure from there. + | { readonly kind: "indent"; readonly indent: number }; + +interface Cursor { + offset: number; + column: number; + /** The character at `offset` is a tab whose first columns are already taken. */ + insideTab: boolean; +} + +interface Source { + readonly text: string; + readonly lineStarts: readonly number[]; +} + +const LINE_ENDING = /\r\n|\r|\n/g; +// Whitespace at a line start, or past a quote marker and its one optional space. +const MAY_KEEP_WHITESPACE = /(?:^|[\r\n])[ \t]|>(?:\t|[ \t]{2})/; +const LIST_MARKER = /[-*+]|\d{1,9}[.)]/y; +const INLINE_CONTAINERS = new Set(["emphasis", "strong", "delete", "link", "linkReference"]); +const nextTabStop = (column: number) => (Math.floor(column / 4) + 1) * 4; +const isBlank = (character: string | undefined) => character === " " || character === "\t"; + +function columnAt(source: Source, line: number, offset: number): number { + let column = 0; + for (let index = source.lineStarts[line - 1]!; index < offset; index++) { + column = source.text[index] === "\t" ? nextTabStop(column) : column + 1; + } + return column; +} + +/** Moves `width` columns through spaces and tabs, splitting a tab where it must. */ +function skipColumns(source: Source, cursor: Cursor, width: number): boolean { + let left = width; + while (left > 0) { + const character = source.text[cursor.offset]; + if (!isBlank(character)) return false; + const step = character === " " ? 1 : nextTabStop(cursor.column) - cursor.column; + if (step > left) { + cursor.column += left; + cursor.insideTab = true; + return true; + } + cursor.offset += 1; + cursor.column += step; + cursor.insideTab = false; + left -= step; + } + return true; +} + +/** + * Where the item's content starts on its own first line, and its column, measured from the marker + * as CommonMark does. A task's checkbox is content, whatever GFM makes the paragraph's position. + */ +function itemContent(source: Source, item: MarkdownNode): Cursor | undefined { + const start = item.position?.start; + if (start?.offset === undefined) return undefined; + LIST_MARKER.lastIndex = start.offset; + const marker = LIST_MARKER.exec(source.text)?.[0]; + if (!marker) return undefined; + const end = start.offset + marker.length; + const cursor: Cursor = { + offset: end, + column: columnAt(source, start.line, end), + insideTab: false, + }; + let offset = end; + let column = cursor.column; + while (isBlank(source.text[offset])) { + column = source.text[offset] === "\t" ? nextTabStop(column) : column + 1; + offset += 1; + } + const blankLine = offset >= source.text.length || /[\r\n]/.test(source.text[offset]!); + if (!blankLine && column - cursor.column <= 4) return { offset, column, insideTab: false }; + // A blank first line, or code after five or more columns, starts one column past the marker. + if (blankLine) return { ...cursor, column: cursor.column + 1 }; + skipColumns(source, cursor, 1); + return cursor; +} + +/** The end of the container markers and indentation on `line`, or nothing for a lazy line. */ +function containerEnd( + source: Source, + line: number, + chain: readonly Container[], + depth = chain.length, +): Cursor | undefined { + const cursor: Cursor = { offset: source.lineStarts[line - 1]!, column: 0, insideTab: false }; + for (let index = 0; index < depth; index++) { + const container = chain[index]!; + if (container.kind === "quote") { + // Up to three columns of indentation, the marker, then one optional space. + const indentation = { ...cursor }; + while (isBlank(source.text[cursor.offset]) && skipColumns(source, cursor, 1)) { + if (cursor.column - indentation.column > 3) return undefined; + } + if (cursor.insideTab || source.text[cursor.offset] !== ">") return undefined; + cursor.offset += 1; + cursor.column += 1; + if (isBlank(source.text[cursor.offset])) skipColumns(source, cursor, 1); + continue; + } + if (container.kind === "item" && container.node.position?.start.line === line) { + const content = itemContent(source, container.node); + if (!content) return undefined; + Object.assign(cursor, content); + continue; + } + const indent = + container.kind === "indent" ? container.indent : itemIndent(source, chain, index); + if (indent === undefined || !skipColumns(source, cursor, indent)) return undefined; + } + return cursor; +} + +/** The columns an item's continuation lines need past its parent's own markers. */ +function itemIndent( + source: Source, + chain: readonly Container[], + index: number, +): number | undefined { + const item = chain[index]; + if (item?.kind !== "item") return undefined; + if (item.indent === undefined) { + const line = item.node.position?.start.line; + const parent = line === undefined ? undefined : containerEnd(source, line, chain, index); + const content = itemContent(source, item.node); + item.indent = parent && content ? content.column - parent.column : null; + } + return item.indent ?? undefined; +} + +/** The spaces and tabs typed on `line` that CommonMark drops, past what is structure. */ +function typedWhitespace( + source: Source, + line: number, + paragraph: MarkdownNode, + chain: readonly Container[], +): string { + const cursor = containerEnd(source, line, chain); + if (!cursor) return ""; + const start = paragraph.position!.start; + let end = cursor.offset; + if (line === start.line) end = start.offset!; + else while (isBlank(source.text[end])) end++; + const typed = source.text.slice(cursor.offset, end); + if (end <= cursor.offset || !/^[ \t]+$/.test(typed)) return ""; + // A tab split by the container keeps the columns left of it, as spaces. + return cursor.insideTab + ? " ".repeat(nextTabStop(cursor.column) - cursor.column) + typed.slice(1) + : typed; +} + +function whitespaceNode(value: string): MarkdownNode { + return { + type: "text", + value, + // Converting to HTML trims a whitespace-only text, and the first text after a line break; + // the empty text takes that trim. + data: { + hName: "span", + hProperties: { dataLeadingWhitespace: "" }, + hChildren: [ + { type: "text", value: "" }, + { type: "text", value }, + ], + }, + }; +} + +/** Whether `node` starts with a space, tab or line ending, which a line start drops or hides. */ +function startsBlank(node: MarkdownNode): boolean { + if (typeof node.value === "string") return /^[ \t\r\n]/.test(node.value); + const first = node.children?.[0]; + return first !== undefined && startsBlank(first); +} + +// Split or trimmed texts drop their position: nothing later reads a text node's. +function withValue({ position: _position, ...text }: MarkdownNode, value: string): MarkdownNode { + return { ...text, value }; +} + +/** `node` with the start trim that converting to HTML gives whatever follows a line break. */ +function trimmedAfterBreak(node: MarkdownNode): MarkdownNode { + const value = node.value ?? ""; + if (node.type === "text" && /^[ \t]/.test(value)) { + return withValue(node, value.replace(/^[ \t]+/, "")); + } + // Code turns its line endings into spaces first. + if (node.type === "inlineCode" && /^[ \t\r\n]/.test(value)) { + return { ...node, value: value.replace(/^(?:[ \t]|\r?\n|\r)+/, "") }; + } + const head = node.children?.[0]; + if (INLINE_CONTAINERS.has(node.type) && node.type !== "linkReference" && head?.type === "text") { + return { ...node, children: [trimmedAfterBreak(head), ...node.children!.slice(1)] }; + } + return node; +} + +/** + * Converting to HTML trims the start of the node after a line break, and the span now takes that + * place, so the node after the span gets the same trim. A line whose content still starts with + * whitespace, which the browser hides at a line start, keeps no span, so it shows as without one. + */ +function settle(children: MarkdownNode[], at: number, afterBreak: boolean): void { + if (afterBreak && children[at + 1]) children[at + 1] = trimmedAfterBreak(children[at + 1]!); + let index = at + 1; + while (children[index]?.type === "text" && children[index]!.value === "") index++; + const content = children[index]; + if (!content || content.type === "break" || startsBlank(content)) children.splice(at, 1); +} + +function restoreParagraph( + source: Source, + paragraph: MarkdownNode, + chain: readonly Container[], + skipFirstLine: boolean, +): void { + const start = paragraph.position?.start; + if (start?.offset === undefined || !paragraph.children) return; + const typed = (at: number) => typedWhitespace(source, at, paragraph, chain); + const inserted = new Set(); + const indentation = (value: string) => { + const node = whitespaceNode(value); + inserted.add(node); + return node; + }; + // Nodes a plugin made without a position follow on from their siblings. + let line = start.line; + + const split = (text: MarkdownNode): MarkdownNode[] => { + const value = text.value ?? ""; + const endings = [...value.matchAll(LINE_ENDING)]; + // A character reference such as ` ` adds a line ending the source does not have. + if ( + endings.length === 0 || + (text.position && text.position.end.line - text.position.start.line !== endings.length) + ) { + return [text]; + } + const parts: MarkdownNode[] = []; + let cut = 0; + for (const ending of endings) { + line += 1; + const whitespace = typed(line); + if (!whitespace) continue; + const at = ending.index + ending[0].length; + parts.push(withValue(text, value.slice(cut, at)), indentation(whitespace)); + cut = at; + } + if (parts.length === 0) return [text]; + if (cut < value.length) parts.push(withValue(text, value.slice(cut))); + return parts; + }; + + const walk = (parent: MarkdownNode) => { + const children: MarkdownNode[] = []; + for (const child of parent.children ?? []) { + line = child.position?.start.line ?? line; + if (child.type === "text") { + children.push(...split(child)); + } else { + children.push(child); + if (child.type === "break") { + line = child.position?.end.line ?? line + 1; + const whitespace = typed(line); + if (whitespace) children.push(indentation(whitespace)); + } else if (INLINE_CONTAINERS.has(child.type)) { + walk(child); + } + } + line = child.position?.end.line ?? line; + } + // From the end, so settling one span leaves the earlier ones' places as they are. + for (let index = children.length - 1; index >= 0; index--) { + if (inserted.has(children[index]!)) settle(children, index, true); + } + parent.children = children; + }; + + const first = skipFirstLine ? "" : typed(start.line); + walk(paragraph); + if (first) { + paragraph.children.unshift(indentation(first)); + settle(paragraph.children, 0, false); + } +} + +// The alert plugin reads the marker from the first text, and drops the marker's line. +function startsWithAlertMarker(paragraph: MarkdownNode): boolean { + const first = paragraph.children?.[0]; + return first?.type === "text" && GITHUB_ALERT_MARKER.test(first.value ?? ""); +} + +function visit( + source: Source, + node: MarkdownNode, + chain: readonly Container[], + firstInQuote: boolean, +): void { + if (node.type === "paragraph") { + restoreParagraph(source, node, chain, firstInQuote && startsWithAlertMarker(node)); + return; + } + // Other containers, such as footnote definitions, keep CommonMark's reading. + const inner = + node.type === "root" || node.type === "list" + ? chain + : node.type === "blockquote" + ? [...chain, { kind: "quote" } as const] + : node.type === "listItem" + ? [...chain, { kind: "item", node } as const] + : undefined; + if (!inner) return; + node.children?.forEach((child, index) => + visit(source, child, inner, node.type === "blockquote" && index === 0), + ); +} + +/** + * CommonMark drops the spaces and tabs at the start of each line of a paragraph. This puts back + * what was typed past the structure CommonMark reads, such as a list item's indentation or a + * quote's marker, in spans the stylesheet keeps whitespace in. `source` is the text the node's + * offsets point into; `indent` is how far its lines are already indented. + */ +export function keepLeadingWhitespace( + node: { readonly type: string; readonly children?: readonly object[] | undefined }, + source: string, + indent = 0, +): void { + if (!MAY_KEEP_WHITESPACE.test(source)) return; + const lineStarts = [0]; + for (const ending of source.matchAll(LINE_ENDING)) + lineStarts.push(ending.index + ending[0].length); + const chain: Container[] = indent > 0 ? [{ kind: "indent", indent }] : []; + visit({ text: source, lineStarts }, node as MarkdownNode, chain, false); +} + +const enabledProcessors = new WeakSet(); + +/** + * Opts a processor in. User messages use it so the sent bubble shows each line as it was typed + * and the agent received it; agent replies and files keep CommonMark's reading. + */ +export function remarkEnableLeadingWhitespace(this: object): undefined { + enabledProcessors.add(this); +} + +export function keepsLeadingWhitespace(processor: object): boolean { + return enabledProcessors.has(processor); +} + +/** Sits before plugins that split text without positions, and before list recovery. */ +export function remarkKeepLeadingWhitespace(this: object): Transformer { + return (tree, file) => { + if (enabledProcessors.has(this)) keepLeadingWhitespace(tree, String(file)); + }; +} diff --git a/packages/shared/src/markdownListIndentation.ts b/packages/shared/src/markdownListIndentation.ts index 39342890d1c2..65146e868fe7 100644 --- a/packages/shared/src/markdownListIndentation.ts +++ b/packages/shared/src/markdownListIndentation.ts @@ -1,3 +1,4 @@ +import { keepLeadingWhitespace, keepsLeadingWhitespace } from "./markdownLeadingWhitespace.ts"; import { keepOrderedListNumbers, keepsOrderedListNumbers } from "./markdownOrderedListNumbers.ts"; interface MarkdownPosition { @@ -96,6 +97,15 @@ function blocksFromIndentedCode(node: MarkdownAstNode, parser: MarkdownParser): if (keepsOrderedListNumbers(parser)) { for (const block of recovered.blocks) keepOrderedListNumbers(block, recovered.source); } + if (keepsLeadingWhitespace(parser)) { + // The trimmed first line sets where the item's content starts. + const indent = /^[\t ]*/.exec(String(node.value))![0]; + const columns = [...indent].reduce( + (column, character) => (character === "\t" ? (Math.floor(column / 4) + 1) * 4 : column + 1), + 0, + ); + keepLeadingWhitespace({ type: "root", children: recovered.blocks }, recovered.source, columns); + } const first = recovered.blocks[0]; return { ...recovered, diff --git a/packages/shared/src/markdownPipeline.test.ts b/packages/shared/src/markdownPipeline.test.ts index 9671225731e2..d0e52cb9f717 100644 --- a/packages/shared/src/markdownPipeline.test.ts +++ b/packages/shared/src/markdownPipeline.test.ts @@ -1,6 +1,7 @@ import { expect, it } from "vite-plus/test"; import { type PluggableList, unified } from "unified"; import rehypeRaw from "rehype-raw"; +import remarkGfm from "remark-gfm"; import remarkParse from "remark-parse"; import remarkRehype from "remark-rehype"; import type { Link, Root, RootContent } from "mdast"; @@ -8,6 +9,7 @@ import { CHAT_MARKDOWN_REHYPE_PLUGINS, CHAT_MARKDOWN_REMARK_PLUGINS, CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS, + CHAT_USER_MARKDOWN_REMARK_PLUGINS, remarkAssistantInsights, remarkEnableOrderedListNumbers, } from "./markdownPipeline.ts"; @@ -637,6 +639,244 @@ it("keeps the number written on each ordered list item only when enabled", () => ).toEqual([undefined, undefined, undefined, undefined, undefined]); }); +type ShownNode = { + type: string; + tagName?: string; + value?: string; + properties?: Record; + children?: ShownNode[]; +}; +const SHOWN_BLOCKS = new Set([ + "p", + "li", + "blockquote", + "ul", + "ol", + "pre", + "h1", + "h2", + "table", + "tr", +]); + +/** The text a browser shows, by line: whitespace collapses except in `pre` and kept whitespace. */ +function shownText(tree: ShownNode): string { + let out = ""; + const visit = (node: ShownNode, keep: boolean) => { + if (node.type === "text") { + const value = node.value ?? ""; + // Only spaces, tabs and line endings collapse; a no-break space shows. + out += keep + ? value.replace(/ /g, "\u0001").replace(/\t/g, "\u0002") + : value.replace(/[ \t\r\n]/g, " "); + } + // An image shows as something, which its alt text stands in for. + if (node.properties?.alt !== undefined) out += String(node.properties.alt); + if (node.tagName === "br" || SHOWN_BLOCKS.has(node.tagName ?? "")) out += "\n"; + const inner = + keep || node.tagName === "pre" || node.properties?.dataLeadingWhitespace !== undefined; + node.children?.forEach((child) => visit(child, inner)); + if (SHOWN_BLOCKS.has(node.tagName ?? "")) out += "\n"; + }; + visit(tree, false); + return out + .split("\n") + .map((line) => line.replace(/ +/g, " ").replace(/^ | $/g, "")) + .filter(Boolean) + .join("\n") + .replace(/\u0001/g, " ") + .replace(/\u0002/g, "\t"); +} + +const hastRenderer = (plugins: PluggableList) => { + const processor = unified() + .use(remarkParse) + .use(plugins) + .use(remarkRehype, { allowDangerousHtml: true }); + return (markdown: string) => processor.runSync(processor.parse(markdown), markdown) as ShownNode; +}; +const userMessage = hastRenderer([ + ...CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS, + ...CHAT_USER_MARKDOWN_REMARK_PLUGINS, +]); +// The user pipeline as it was before leading whitespace was kept. +const commonMarkUserMessage = hastRenderer([ + ...CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS, + [remarkGfm, { singleTilde: false }], +]); +/** The tree with the restored indentation taken out, with the empty texts and positions it leaves. */ +const withoutRestoredWhitespace = ({ + position: _position, + ...node +}: ShownNode & { position?: unknown }): ShownNode => ({ + ...node, + ...(node.children && { + children: node.children + .filter( + (child) => + child.properties?.dataLeadingWhitespace === undefined && + !(child.type === "text" && child.value === ""), + ) + .map(withoutRestoredWhitespace), + }), +}); +/** Each link's text and where it goes. */ +const linkTargets = (node: ShownNode): [string, unknown][] => + node.properties?.href === undefined + ? (node.children ?? []).flatMap(linkTargets) + : [[shownText(node), node.properties.href]]; + +it("shows the spaces and tabs typed at the start of each line of a user message", () => { + const shown = (markdown: string) => shownText(userMessage(markdown)); + const outline = "Plan\n Step one\n Step two\n Detail a\n Detail b"; + expect(shown(outline)).toBe(outline); + expect(shown(outline.replaceAll("\n", "\r\n"))).toBe(outline); + expect(shown(" First line\nnext\n\n New paragraph")).toBe( + " First line\nnext\n New paragraph", + ); + expect(shown("Plan\n\tTabbed\n \t Mixed")).toBe("Plan\n\tTabbed\n \t Mixed"); + expect(shown("Plan \n After a hard break\\\n and an escaped one")).toBe( + "Plan\n After a hard break\n and an escaped one", + ); + // In a container, only whitespace past its own structure counts. + expect(shown("- item\n continued")).toBe("item\ncontinued"); + expect(shown("- item\n more")).toBe("item\n more"); + expect(shown("- item\ncontinued")).toBe("item\ncontinued"); + expect(shown("- item\n continued")).toBe("item\ncontinued"); + expect(shown("1. one\n two")).toBe("one\n two"); + expect(shown("- item\n\tsplit tab")).toBe("item\n split tab"); + expect(shown("- item\n\n second paragraph")).toBe("item\n second paragraph"); + // An item's content starts after its marker and the marker's spacing. A task's checkbox is + // content, so it does not move where continuation lines start, however the task begins. + expect(shown("- [ ] task\n under the task")).toBe("task\n under the task"); + for (const task of ["task", "**task**", "[task](https://example.com)", "`task`"]) { + expect(shown(`- [ ] ${task}\n detail`), task).toBe("task\n detail"); + } + expect(shown("- x\n y")).toBe("x\n y"); + expect(shown("- x\n y")).toBe("x\n y"); + expect(shown("-\tx\n\t y")).toBe("x\n y"); + expect(shown("10. x\n y")).toBe("x\n y"); + expect(shown("> a\n> b")).toBe("a\n b"); + expect(shown("> first")).toBe(" first"); + expect(shown("> a\n lazy")).toBe("a\nlazy"); + expect(shown("> - item\n> more")).toBe("item\n more"); + expect(shown("- > a\n > b")).toBe("a\n b"); + expect(shown("- a\n - b\n c")).toBe("a\nb\n c"); + // List recovery reparses over-indented content; its first line sets the indentation. + expect(shown("- first block\n continued\n deeper")).toBe( + "first block\ncontinued\n deeper", + ); + + // A space or tab written as a character reference after the indentation is dropped, as it is + // without the indentation; only the typed indentation is added. + for (const reference of [" ", " ", " ", " "]) { + expect(shown(`a\n ${reference}b`), reference).toBe("a\n b"); + expect(shown(`a \n\t${reference}b`), reference).toBe("a\n\tb"); + expect(shown(`a\\\r\n ${reference}${reference}b`), reference).toBe("a\n b"); + } + // Converting to HTML also drops the spaces that start code or a link's text after a line break. + expect(shown("a\n ` npm i`")).toBe("a\n npm i"); + expect(shown("a\n [ docs](https://example.com)")).toBe("a\n docs"); + // A line whose text starts with whitespace the browser hides keeps no indentation, as without it. + expect(shown(" b")).toBe("b"); + expect(shown("a\n *** b***")).toBe("a\nb"); + + // Only the indentation is added: formatting, code, links and alerts render as without it. + const inline = "Plan\n **bold** [link](https://example.com) `code` ~/a and ~~gone~~ /tmp/a.ts"; + const alert = "> [!NOTE]\n> indented body"; + expect(shown(inline)).toBe("Plan\n bold link code ~/a and gone /tmp/a.ts"); + expect(shown(alert)).toBe(" indented body"); + for (const markdown of [inline, alert]) { + expect(withoutRestoredWhitespace(userMessage(markdown)), markdown).toEqual( + withoutRestoredWhitespace(commonMarkUserMessage(markdown)), + ); + } + expect(linkTargets(userMessage(inline))).toEqual(linkTargets(commonMarkUserMessage(inline))); + expect(linkTargets(userMessage(inline)).map(([label]) => label)).toEqual(["link", "/tmp/a.ts"]); + + // A line ending written as a character reference is not a source line: it never takes a typed + // line's indentation, and no typed line's indentation moves onto it. + const decoded = shown("a b\n c").split("\n"); + expect(decoded.slice(0, 2)).toEqual(["a", "b"]); + expect(["c", " c"]).toContain(decoded[2]); + + // Code, and agent replies, keep CommonMark's reading. + for (const markdown of [ + "```\n code\n more\n```", + "Plan\n\n code\n deeper", + "- item\n\n code", + ]) { + expect(userMessage(markdown), markdown).toEqual(commonMarkUserMessage(markdown)); + } + for (const plugins of [CHAT_MARKDOWN_REMARK_PLUGINS, CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS]) { + expect(shownText(hastRenderer(plugins)(outline)).replaceAll("\n", " ")).toBe( + "Plan Step one Step two Detail a Detail b", + ); + } +}); + +it("adds only the typed indentation, and renders what follows it as without it", () => { + const starts = [ + "b", + "*b*", + "`b`", + "~~b~~", + "[b](https://example.com)", + "![b](https://example.com/b.png)", + "https://example.com/b", + "/tmp/b.ts", + "~/b", + "@b", + "$b", + "&b", + " b", + // Spaces and tabs written as character references, which a line start drops. + " b", + " b", + " b", + " b", + " b", + " * b", + " `b`", + " **b**", + // Content whose first character is a space. + "` b`", + "[ b](https://example.com)", + "** b**", + "*** b***", + "[ b]", + ]; + const lines = [ + (indent: string, start: string, join: string) => `a${join}${indent}${start}`, + (indent: string, start: string, join: string) => `> a${join}> ${indent}${start}`, + (indent: string, start: string, join: string) => `- a${join} ${indent}${start}`, + ]; + for (const indent of ["", " ", " ", "\t", " \t"]) { + for (const start of starts) { + // Without the indentation, an image alone on a CRLF line breaks twice: the image-line break + // leaves the CR behind, which breaks again. + const joins = start.startsWith("!") ? ["\n", " \n", "\\\n"] : ["\n", "\r\n", " \n", "\\\n"]; + const markdowns = [ + ...joins.flatMap((join) => lines.map((line) => line(indent, start, join))), + // A paragraph's first line takes at most three spaces before it reads as code. + ...(indent.includes("\t") ? [] : [`${indent}${start}`, `> ${indent}${start}`]), + ]; + for (const markdown of markdowns) { + const label = JSON.stringify(markdown); + expect(withoutRestoredWhitespace(userMessage(markdown)), label).toEqual( + withoutRestoredWhitespace(commonMarkUserMessage(markdown)), + ); + const shown = shownText(userMessage(markdown)).split("\n"); + const before = shownText(commonMarkUserMessage(markdown)).split("\n"); + expect(shown.length, label).toBe(before.length); + shown.forEach((line, index) => + expect([before[index], `${indent}${before[index]}`], label).toContain(line), + ); + } + } + } +}); + it("moves a 's color-scheme sources onto its , which the renderer resolves", () => { const processor = unified() .use(remarkParse) diff --git a/packages/shared/src/markdownPipeline.ts b/packages/shared/src/markdownPipeline.ts index ad77b6d928ae..728187e43ba9 100644 --- a/packages/shared/src/markdownPipeline.ts +++ b/packages/shared/src/markdownPipeline.ts @@ -21,6 +21,10 @@ import remarkGfm from "remark-gfm"; import { remarkGithubAlerts } from "./markdownGithubAlerts.ts"; import { remarkNormalizeListItemIndentation } from "./markdownListIndentation.ts"; import { remarkKeepOrderedListNumbers } from "./markdownOrderedListNumbers.ts"; +import { + remarkEnableLeadingWhitespace, + remarkKeepLeadingWhitespace, +} from "./markdownLeadingWhitespace.ts"; import { CODEX_ARTIFACT_TEMPLATE_HAST_PROPERTIES, remarkCodexDirectives, @@ -259,10 +263,12 @@ export const CHAT_MARKDOWN_REMARK_PLUGINS: PluggableList = [ remarkNormalizeLinksAndTagInlineCode, ]; +// Leading whitespace is kept only where each line renders as a line. export const CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS: PluggableList = [ remarkGfm, remarkEndAutolinksAtScriptPunctuation, remarkKeepAutolinkSuffixes, + remarkKeepLeadingWhitespace, remarkLinkAbsoluteFilePaths, remarkKeepWindowsPaths, remarkGithubAlerts, @@ -277,8 +283,10 @@ export const CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS: PluggableList = [ // Users type paths like ~/a and (~/b, which GFM's single-tilde strikethrough hides as . // Appended after the base list, this reconfigures its remark-gfm entry; ~~double~~ still strikes. +// Users also indent lines with spaces, which CommonMark drops from a paragraph. export const CHAT_USER_MARKDOWN_REMARK_PLUGINS: PluggableList = [ [remarkGfm, { singleTilde: false }], + remarkEnableLeadingWhitespace, ]; // Start tags an HTML parser closes an open `

` for. diff --git a/packages/shared/src/threadFindText.test.ts b/packages/shared/src/threadFindText.test.ts index 6228da3ee861..663ba33840db 100644 --- a/packages/shared/src/threadFindText.test.ts +++ b/packages/shared/src/threadFindText.test.ts @@ -29,6 +29,23 @@ it("indexes single tildes in user paths as typed", () => { ).toBe("Drop old"); }); +it("indexes the spaces typed at the start of a user's lines, as the bubble shows them", () => { + const text = "Plan\n Step one\n\tDetail"; + // Each line ending reads as one space, as the text after a rendered line break does. + expect(searchableMessageSegments({ role: "user", text, streaming: false })).toEqual([ + "Plan", + " Step one", + " \tDetail", + ]); + const indexed = (text: string) => + searchableMessageSegments({ role: "user", text, streaming: false }); + // A task's checkbox does not move where its continuation lines start. + expect(indexed("- [ ] task\n detail")).toEqual([" task", " detail"]); + // A space or tab written as a character reference is dropped there, as without the indentation. + expect(indexed("a\n b")).toEqual(["a", " b"]); + expect(indexed("a \n\t b")).toEqual(["a", " \tb"]); +}); + it("excludes structured context chips without joining text across them", () => { expect( searchableMessageSegments({ diff --git a/scripts/scenarios/sent-message-keeps-leading-spaces.e2e.ts b/scripts/scenarios/sent-message-keeps-leading-spaces.e2e.ts new file mode 100644 index 000000000000..3fb85beea592 --- /dev/null +++ b/scripts/scenarios/sent-message-keeps-leading-spaces.e2e.ts @@ -0,0 +1,35 @@ +/// +// The DOM lib types the function this scenario runs in the page. +import { expect } from "e2e"; + +import { test, WEB } from "./t3.ts"; + +const LINES = ["Plan", " Step one", " Step two", " Detail a", " Detail b"]; + +test( + "A sent message shows the spaces typed at the start of its lines", + WEB, + async ({ t3, app, browser, screen }) => { + const project = await t3.project("demo"); + const thread = await t3.thread({ project, title: "Outline", messages: ["Start"] }); + await t3.open(thread); + + const composer = screen.getByRole("textbox"); + for (const [index, line] of LINES.entries()) { + if (index > 0) await composer.press("Shift+Enter"); + await composer.pressSequentially(line); + } + await composer.press("Enter"); + await expect(screen.getByText("second fixture turn complete", { exact: false })).toBeVisible(); + await app.screenshot("sent"); + + // The visible text, which keeps whitespace only where the page shows it. + const shown = await browser.evaluate( + () => + [...document.querySelectorAll("[data-user-message-body]")] + .map((body) => body.innerText) + .find((text) => text.includes("Detail b")) ?? null, + ); + expect(shown).toBe(LINES.join("\n")); + }, +); From 33542a53be7c5dd952457c4c2b479813f5cab32e Mon Sep 17 00:00:00 2001 From: Martin Bergo Date: Tue, 17 Nov 2026 12:29:49 +0100 Subject: [PATCH 027/133] fix(server): delegating a task no longer records failed projection read spans (#38083) Co-authored-by: Martin Bergo <14320143+mInrOz@users.noreply.github.com> --- .../Orchestrator.control-reads.test.ts | 40 +++++++++++++------ .../src/orchestration-v2/Orchestrator.ts | 21 +++++----- 2 files changed, 37 insertions(+), 24 deletions(-) diff --git a/apps/server/src/orchestration-v2/Orchestrator.control-reads.test.ts b/apps/server/src/orchestration-v2/Orchestrator.control-reads.test.ts index ff96b2fbac1a..274c15a5f708 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.control-reads.test.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.control-reads.test.ts @@ -1252,19 +1252,35 @@ it.effect("keeps delegated child pull-request links independent of the parent", }); const parent = yield* projections.getThreadProjection(parentThreadId); const parentRun = parent.runs[0]!; - yield* orchestrator.dispatch({ - type: "delegated_task.request", - commandId: CommandId.make("delegate-parent-pr"), - parentThreadId, - parentRunId: parentRun.id, - parentNodeId: parentRun.rootNodeId!, - task: "Review the changes", - modelSelection, - runtimeMode: "full-access", - interactionMode: "default", - createdBy: "agent", - creationSource: "mcp", + const failedSpans: Array = []; + const tracer = Tracer.make({ + span(options) { + const span = new Tracer.NativeSpan(options); + const end = span.end.bind(span); + span.end = (time, exit) => { + end(time, exit); + if (Exit.isFailure(exit)) failedSpans.push(span.name); + }; + return span; + }, }); + yield* orchestrator + .dispatch({ + type: "delegated_task.request", + commandId: CommandId.make("delegate-parent-pr"), + parentThreadId, + parentRunId: parentRun.id, + parentNodeId: parentRun.rootNodeId!, + task: "Review the changes", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + createdBy: "agent", + creationSource: "mcp", + }) + .pipe(Effect.withTracer(tracer)); + // The child thread is created by this command; a failed span here reads as an error in traces. + assert.deepEqual(failedSpans, []); const updatedParent = yield* projections.getThreadProjection(parentThreadId); assert.deepEqual(updatedParent.subagents[0]!.modelSelection, modelSelection); const childThreadId = updatedParent.subagents[0]!.childThreadId!; diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 2fcd3c22369a..6e6c7fc862ff 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -1827,20 +1827,17 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio recent?: ProjectionRecordFilter["sinceLastCompaction"], ) { const pending = (yield* Ref.get(events)).filter((event) => event.threadId === threadId); - const stored = yield* Effect.option(readCommandProjection(threadId, recent)); + const created = pending.find( + ( + event, + ): event is Extract => + event.type === "thread.created", + ); + // A thread created here has no stored row: create and fork refuse used ids, delegation derives a fresh one. let projection: OrchestrationV2ThreadProjection; - if (Option.isSome(stored)) { - projection = stored.value; + if (created === undefined) { + projection = yield* readCommandProjection(threadId, recent); } else { - const created = pending.find( - ( - event, - ): event is Extract => - event.type === "thread.created", - ); - if (created === undefined) { - return yield* new OrchestratorProjectionError({ threadId }); - } projection = emptyProjection(created); } From 218c18bc028903bf5c6d17be60ede3cbc5fb6305 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 17 Nov 2026 03:40:46 -0800 Subject: [PATCH 028/133] fix(server): a host-narrowed issue list still names every tracker (#38085) --- apps/server/src/issue/IssueService.test.ts | 8 +++++ apps/server/src/issue/IssueService.ts | 6 +++- apps/web/src/components/issue/IssuesPage.tsx | 38 +++++++++++++++++--- 3 files changed, 46 insertions(+), 6 deletions(-) diff --git a/apps/server/src/issue/IssueService.test.ts b/apps/server/src/issue/IssueService.test.ts index 5a5d9753c36d..f42a1aea6f56 100644 --- a/apps/server/src/issue/IssueService.test.ts +++ b/apps/server/src/issue/IssueService.test.ts @@ -424,6 +424,14 @@ describe("IssueService", () => { }), ]); + // Narrowing to one host still names every tracker, so the client can switch between them. + const narrowed = yield* service.list({ state: "open", host: "github.com" }); + expect(narrowed.entries.every((entry) => entry.host === "github.com")).toBe(true); + expect(narrowed.trackers.map((tracker) => tracker.host)).toEqual([ + "github.com", + "gitlab.com", + ]); + // A continuation only reads the scopes it names. listed.length = 0; const failed = yield* service.list({ diff --git a/apps/server/src/issue/IssueService.ts b/apps/server/src/issue/IssueService.ts index 7da9674d1cdd..2832ab04d15b 100644 --- a/apps/server/src/issue/IssueService.ts +++ b/apps/server/src/issue/IssueService.ts @@ -312,12 +312,16 @@ const make = Effect.gen(function* () { ); const list: IssueService["Service"]["list"] = Effect.fn("IssueService.list")(function* (input) { - const { supported, unimplemented } = yield* listProjects(input); + // Trackers name every host so a client narrowed to one can switch to another; only the + // narrowed host's scopes are read. + const { supported, unimplemented } = yield* listProjects({ projectId: input.projectId }); + const host = input.host?.trim().toLowerCase(); const limit = input.limit ?? DEFAULT_LIST_LIMIT; // Worktrees of one repository are separate projects, and every repository of an Azure // DevOps project shares its work items; read each scope once. const scopes = new Map(); for (const project of supported) { + if (host !== undefined && project.host !== host) continue; const key = listCursorKey(project.host, project.scope); if (!scopes.has(key)) scopes.set(key, project); } diff --git a/apps/web/src/components/issue/IssuesPage.tsx b/apps/web/src/components/issue/IssuesPage.tsx index c3c340ce4002..94a1d4e905f9 100644 --- a/apps/web/src/components/issue/IssuesPage.tsx +++ b/apps/web/src/components/issue/IssuesPage.tsx @@ -137,9 +137,16 @@ function getShortcutContext() { }; } -function hostOptionsFor(groups: ReturnType, chosen: string | undefined) { +function hostOptionsFor(trackers: ReadonlyArray, chosen: string | undefined) { const hosts = new Map(); - for (const group of groups) hosts.set(group.tracker.host, group.tracker); + const ordered = [...trackers].sort((a, b) => + issueTrackerKey(a).localeCompare(issueTrackerKey(b)), + ); + for (const tracker of ordered) { + const existing = hosts.get(tracker.host); + if (existing === undefined || (!existing.configured && tracker.configured)) + hosts.set(tracker.host, tracker); + } return [ { value: "", label: "All", Icon: Plug2Icon }, // A remembered host no project is on any more stays listed, so the filter can be taken off. @@ -220,10 +227,31 @@ export function IssuesPage() { // Rows grouped per tracker account, so a tracker that cannot be read says so where its rows // would be, and each tracker's rows carry on from their own cursors. - const groups = groupIssues(held, debouncedQuery, projects, search.order ?? "updated"); - const filterScopes = issueFilterScopes(held, projects); + // The server names every tracker so the menu can switch hosts, but reads only the chosen one. + const chosenHost = search.host?.toLowerCase(); + const shown = chosenHost + ? new Map( + [...held].map(([environmentId, page]) => [ + environmentId, + { + ...page, + answer: { + ...page.answer, + trackers: page.answer.trackers.filter( + (tracker) => tracker.host.toLowerCase() === chosenHost, + ), + }, + }, + ]), + ) + : held; + const groups = groupIssues(shown, debouncedQuery, projects, search.order ?? "updated"); + const filterScopes = issueFilterScopes(shown, projects); - const hostOptions = hostOptionsFor(groups, search.host); + const hostOptions = hostOptionsFor( + [...held.values()].flatMap((page) => page.answer.trackers), + search.host, + ); const updateSearch = (patch: { [Key in keyof IssuesSearch]?: IssuesSearch[Key] | undefined }) => { const merged = { ...search, ...patch }; From 9830b857dea6aa402af0bcbaa77601e2284300d5 Mon Sep 17 00:00:00 2001 From: Yash Singh Date: Tue, 17 Nov 2026 05:57:42 -0600 Subject: [PATCH 029/133] feat(desktop): drag file pills into Explorer on Windows (#38096) Co-authored-by: Cursor --- apps/desktop/src/ipc/methods/fileDrag.test.ts | 10 +++++++--- apps/desktop/src/ipc/methods/fileDrag.ts | 3 ++- apps/web/src/useNativeFileDrag.ts | 6 +++--- 3 files changed, 12 insertions(+), 7 deletions(-) diff --git a/apps/desktop/src/ipc/methods/fileDrag.test.ts b/apps/desktop/src/ipc/methods/fileDrag.test.ts index 04b75c9be98a..7e140f9db544 100644 --- a/apps/desktop/src/ipc/methods/fileDrag.test.ts +++ b/apps/desktop/src/ipc/methods/fileDrag.test.ts @@ -15,7 +15,7 @@ import * as DesktopEnvironment from "../../app/DesktopEnvironment.ts"; import * as ElectronWindow from "../../electron/ElectronWindow.ts"; import { startFileDrag } from "./fileDrag.ts"; -it.effect("only drags existing absolute paths from the Mac host environment and app window", () => +it.effect("only drags existing absolute paths from the host environment and app window", () => Effect.gen(function* () { startDrag.mockClear(); getFileIcon.mockClear(); @@ -43,9 +43,13 @@ it.effect("only drags existing absolute paths from the Mac host environment and assert.isFalse(yield* run("host", filePath, "darwin", 2)); assert.strictEqual(startDrag.mock.calls.length, 0); assert.isTrue(yield* run("host", filePath)); - assert.deepEqual(startDrag.mock.calls, [[{ file: filePath, icon: "file-icon" }]]); + assert.isTrue(yield* run("host", filePath, "win32")); + assert.deepEqual(startDrag.mock.calls, [ + [{ file: filePath, icon: "file-icon" }], + [{ file: filePath, icon: "file-icon" }], + ]); yield* fs.remove(path.join(stateDir, "environment-id")); assert.isFalse(yield* run("host", filePath)); - assert.strictEqual(startDrag.mock.calls.length, 1); + assert.strictEqual(startDrag.mock.calls.length, 2); }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); diff --git a/apps/desktop/src/ipc/methods/fileDrag.ts b/apps/desktop/src/ipc/methods/fileDrag.ts index 9701dfafcda3..227849c5935b 100644 --- a/apps/desktop/src/ipc/methods/fileDrag.ts +++ b/apps/desktop/src/ipc/methods/fileDrag.ts @@ -16,7 +16,8 @@ export const startFileDrag = makeIpcMethod({ result: Schema.Boolean, handler: Effect.fn("desktop.ipc.fileDrag.start")(function* (input, event) { const environment = yield* DesktopEnvironment.DesktopEnvironment; - if (environment.platform !== "darwin" || !environment.path.isAbsolute(input.path)) return false; + if (environment.platform !== "darwin" && environment.platform !== "win32") return false; + if (!environment.path.isAbsolute(input.path)) return false; const hostEnvironmentId = yield* getHostEnvironmentId.handler(undefined); if (hostEnvironmentId === null || input.environmentId !== hostEnvironmentId) return false; const window = yield* (yield* ElectronWindow.ElectronWindow).main; diff --git a/apps/web/src/useNativeFileDrag.ts b/apps/web/src/useNativeFileDrag.ts index 3195b5ef677b..d0ad8c8efae0 100644 --- a/apps/web/src/useNativeFileDrag.ts +++ b/apps/web/src/useNativeFileDrag.ts @@ -1,5 +1,5 @@ import { splitFilePathPosition } from "@t3tools/shared/fileLinks"; -import { isMacPlatform } from "./lib/utils"; +import { isMacPlatform, isWindowsPlatform } from "./lib/utils"; import { useAtomValue } from "@effect/atom-react"; import { AuthOrchestrationOperateScope, type EnvironmentId } from "@t3tools/contracts"; import type { DragEvent } from "react"; @@ -16,7 +16,7 @@ export function useNativeFileDrag( const canOperate = useEnvironmentScope(environmentId ?? null, AuthOrchestrationOperateScope); const enabled = typeof window.desktopBridge?.startFileDrag === "function" && - isMacPlatform(navigator.platform) && + (isMacPlatform(navigator.platform) || isWindowsPlatform(navigator.platform)) && environmentId != null && environmentId === hostEnvironmentId && canOperate; @@ -33,7 +33,7 @@ export function useNativeFileDrag( const { path } = splitFilePathPosition(await resolvePath()); if (released) return; const started = await window.desktopBridge?.startFileDrag({ environmentId, path }); - if (!started) throw new Error("The file is unavailable on this Mac."); + if (!started) throw new Error("The file is unavailable on this computer."); })().catch((error: unknown) => { if (released) return; toastManager.add({ From 79aa7a7b5c56d9c9e65df4d3d2a0259b1ac37612 Mon Sep 17 00:00:00 2001 From: Martin Bergo Date: Tue, 17 Nov 2026 13:01:55 +0100 Subject: [PATCH 030/133] fix(server): failed OTLP exports no longer go unrecorded (#38091) Co-authored-by: Martin Bergo <14320143+mInrOz@users.noreply.github.com> Co-authored-by: Julius Marminge --- apps/server/src/observability/Metrics.ts | 11 +++ .../server/src/observability/Observability.ts | 8 +- .../observability/OtlpExportFailures.test.ts | 78 +++++++++++++++++++ .../src/observability/OtlpExportFailures.ts | 54 +++++++++++++ apps/server/src/serverLogger.ts | 2 + docs/operations/observability.md | 7 ++ 6 files changed, 158 insertions(+), 2 deletions(-) create mode 100644 apps/server/src/observability/OtlpExportFailures.test.ts create mode 100644 apps/server/src/observability/OtlpExportFailures.ts diff --git a/apps/server/src/observability/Metrics.ts b/apps/server/src/observability/Metrics.ts index 76561d735b02..bdf64da9511c 100644 --- a/apps/server/src/observability/Metrics.ts +++ b/apps/server/src/observability/Metrics.ts @@ -35,6 +35,17 @@ export const orchestrationEffectQueueWait = Metric.timer("t3_orchestration_effec "Time from an orchestration effect's temporal availability until claim, including same-thread blocking.", }); +// A failed batch (transport errors and 408/429/500/502/503/504 after 3 retries) is dropped with +// every push for the next 60 s, logged only at Debug. Incremental exports it as a monotonic counter. +export const otlpExportAttemptFailuresTotal = Metric.counter( + "t3_otlp_export_attempt_failures_total", + { + description: + "Failed OTLP export attempts by signal and reason. Retries count too, so a dropped batch counts up to four.", + incremental: true, + }, +); + export const providerSessionsTotal = Metric.counter("t3_provider_sessions_total", { description: "Total provider session lifecycle operations.", }); diff --git a/apps/server/src/observability/Observability.ts b/apps/server/src/observability/Observability.ts index 166d8ac194a8..1b0414e43b8a 100644 --- a/apps/server/src/observability/Observability.ts +++ b/apps/server/src/observability/Observability.ts @@ -17,6 +17,7 @@ import * as ResourceAttribution from "../resourceTelemetry/ResourceAttribution.t import * as ServerLogger from "../serverLogger.ts"; import * as BrowserTraceCollector from "./BrowserTraceCollector.ts"; import * as HeapAttribution from "./HeapAttribution.ts"; +import * as OtlpExportFailures from "./OtlpExportFailures.ts"; export const layer = Layer.unwrap( Effect.gen(function* () { @@ -61,7 +62,7 @@ export const layer = Layer.unwrap( exportInterval: `${traces.exportIntervalMs} millis`, headers: traces.headers, resource, - }); + }).pipe(Effect.provide(OtlpExportFailures.layer("traces"))); const tracer = yield* makeLocalFileTracer({ filePath: config.serverTracePath, @@ -90,7 +91,10 @@ export const layer = Layer.unwrap( exportInterval: `${metrics.exportIntervalMs} millis`, headers: metrics.headers, resource, - }).pipe(Layer.provide(SharedObservability.layerOtlpSerialization(metrics.protocol))); + }).pipe( + Layer.provide(OtlpExportFailures.layer("metrics")), + Layer.provide(SharedObservability.layerOtlpSerialization(metrics.protocol)), + ); const layerOtelWarnings = Layer.effectDiscard( Effect.forEach(config.otelEnvironment.warnings, (warning) => Effect.logWarning(warning)), diff --git a/apps/server/src/observability/OtlpExportFailures.test.ts b/apps/server/src/observability/OtlpExportFailures.test.ts new file mode 100644 index 000000000000..5481c0996a78 --- /dev/null +++ b/apps/server/src/observability/OtlpExportFailures.test.ts @@ -0,0 +1,78 @@ +import { assert, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Metric from "effect/Metric"; +import { + HttpBody, + HttpClient, + HttpClientError, + HttpClientRequest, + HttpClientResponse, +} from "effect/http"; +import { OtlpSerialization } from "effect/observability"; +import { describe } from "vite-plus/test"; + +import { otlpExportAttemptFailuresTotal } from "./Metrics.ts"; +import * as OtlpExportFailures from "./OtlpExportFailures.ts"; + +const failures = (reason: string) => + Metric.value( + Metric.withAttributes(otlpExportAttemptFailuresTotal, { signal: "logs", reason }), + ).pipe(Effect.map((state) => state.count)); + +describe("OtlpExportFailures", () => { + it.effect("counts each failed attempt by reason and leaves successes alone", () => { + const outcomes: Array = [503, "transport", 200]; + const client = HttpClient.make((request) => { + const outcome = outcomes.shift() ?? 200; + return outcome === "transport" + ? Effect.fail( + new HttpClientError.HttpClientError({ + reason: new HttpClientError.TransportError({ request }), + }), + ) + : Effect.succeed( + HttpClientResponse.fromWeb(request, new Response(null, { status: outcome })), + ); + }); + const serialization = OtlpSerialization.OtlpSerialization.of({ + traces: () => HttpBody.empty, + metrics: () => HttpBody.empty, + logs: () => { + throw new Error("unencodable attribute"); + }, + }); + const layer = OtlpExportFailures.layer("logs").pipe( + Layer.provide(Layer.succeed(HttpClient.HttpClient, client)), + Layer.provide(Layer.succeed(OtlpSerialization.OtlpSerialization, serialization)), + ); + + return Effect.gen(function* () { + const counted = yield* HttpClient.HttpClient; + const encode = yield* OtlpSerialization.OtlpSerialization; + const request = HttpClientRequest.post("http://localhost:4318/v1/logs"); + yield* counted.execute(request); + yield* Effect.flip(counted.execute(request)); + yield* counted.execute(request); + assert.throws(() => encode.logs({ resourceLogs: [] }), "unencodable attribute"); + + const transport = yield* Metric.value( + Metric.withAttributes(otlpExportAttemptFailuresTotal, { + signal: "logs", + reason: "transport", + }), + ); + // OTLP marks the sum monotonic only for an incremental counter. + assert.isTrue(transport.incremental); + assert.deepStrictEqual( + [ + yield* failures("status_503"), + yield* failures("transport"), + yield* failures("encode"), + yield* failures("status_200"), + ], + [1, 1, 1, 0], + ); + }).pipe(Effect.provide(layer), Effect.provideService(Metric.MetricRegistry, new Map())); + }); +}); diff --git a/apps/server/src/observability/OtlpExportFailures.ts b/apps/server/src/observability/OtlpExportFailures.ts new file mode 100644 index 000000000000..db9d089f1aec --- /dev/null +++ b/apps/server/src/observability/OtlpExportFailures.ts @@ -0,0 +1,54 @@ +import type { OtlpSignal } from "@t3tools/contracts"; +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Metric from "effect/Metric"; +import { HttpClient } from "effect/http"; +import type { HttpBody } from "effect/http"; +import { OtlpSerialization } from "effect/observability"; + +import { otlpExportAttemptFailuresTotal } from "./Metrics.ts"; + +/** + * Re-provides the HttpClient and OtlpSerialization one OTLP exporter uses, counting its failed + * attempts on the metrics channel. The exporter applies `filterStatusOk` and its retries outside + * this client, so a non-2xx arrives here as a response and each retry is counted. + */ +export const layer = (signal: OtlpSignal) => + Layer.effectContext( + Effect.gen(function* () { + const context = yield* Effect.context(); + const client = yield* HttpClient.HttpClient; + const serialization = yield* OtlpSerialization.OtlpSerialization; + const failures = (reason: string) => + Metric.withAttributes(otlpExportAttemptFailuresTotal, { signal, reason }); + // Encoding runs synchronously inside the exporter, before any request exists. + const counted = + (encode: (data: A) => HttpBody.HttpBody) => + (data: A) => { + try { + return encode(data); + } catch (error) { + failures("encode").updateUnsafe(1, context); + throw error; + } + }; + return Context.make( + HttpClient.HttpClient, + client.pipe( + HttpClient.tap((response) => + response.status >= 200 && response.status < 300 + ? Effect.void + : Metric.update(failures(`status_${response.status}`), 1), + ), + HttpClient.tapError(() => Metric.update(failures("transport"), 1)), + ), + ).pipe( + Context.add(OtlpSerialization.OtlpSerialization, { + traces: counted(serialization.traces), + metrics: counted(serialization.metrics), + logs: counted(serialization.logs), + }), + ); + }), + ); diff --git a/apps/server/src/serverLogger.ts b/apps/server/src/serverLogger.ts index 79eded855f6d..4458c717e1c5 100644 --- a/apps/server/src/serverLogger.ts +++ b/apps/server/src/serverLogger.ts @@ -10,6 +10,7 @@ import * as OtlpExporter from "effect/observability/OtlpExporter"; import * as OtlpLogger from "effect/observability/OtlpLogger"; import * as ServerConfig from "./config.ts"; +import * as OtlpExportFailures from "./observability/OtlpExportFailures.ts"; // HTTP errors logged with --log-ws-events carry the request URL and its connection ticket. const redactingCredentials = (logger: Logger.Logger) => @@ -73,6 +74,7 @@ export const layer = Effect.gen(function* () { { mergeWithExisting: false }, ).pipe( Layer.provide(OtlpExporter.layerFlusher), + Layer.provide(OtlpExportFailures.layer("logs")), Layer.provide(SharedObservability.layerOtlpSerialization(logs.protocol)), ); diff --git a/docs/operations/observability.md b/docs/operations/observability.md index 4fa782ca21be..ca09202a4ff5 100644 --- a/docs/operations/observability.md +++ b/docs/operations/observability.md @@ -475,6 +475,13 @@ Usually one of these is true: If the local NDJSON file is updating, local tracing is working. The problem is almost always OTLP export configuration or process startup. +If metrics arrive but logs or traces have gaps, read `t3_otlp_export_attempt_failures_total` by +`signal` and `reason` (`status_`, `transport`, `encode`). The exporter drops a batch once it +fails (transport errors and 408, 429, 500, 502, 503 and 504 after 3 retries; other statuses and +encoding at once) and then drops that signal for 60 s, logging it only at Debug, so at the default +log level this counter is the only record. Every retry counts, so one dropped batch reads as up to +four. + ## How To Think About Adding Tracing To Future Code ### Prefer Boundaries Over Tiny Helpers From ecde5791c12f60437a85045001c65f182bee6edd Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 17 Nov 2026 04:10:44 -0800 Subject: [PATCH 031/133] fix(server): preview_open reports a desktop tab it reveals as visible (#38066) --- .../src/preview/DesktopBrowserChannel.test.ts | 5 +- .../src/preview/DesktopBrowserChannel.ts | 27 ++++++++- apps/server/src/preview/ServerBrowser.test.ts | 57 ++++++++++++++++++- apps/server/src/preview/ServerBrowser.ts | 16 ++++-- 4 files changed, 96 insertions(+), 9 deletions(-) diff --git a/apps/server/src/preview/DesktopBrowserChannel.test.ts b/apps/server/src/preview/DesktopBrowserChannel.test.ts index 3cadfcb92e47..bf5cbc2d3c3f 100644 --- a/apps/server/src/preview/DesktopBrowserChannel.test.ts +++ b/apps/server/src/preview/DesktopBrowserChannel.test.ts @@ -2,6 +2,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import * as NodeStream from "@effect/platform-node/NodeStream"; import { expect, it } from "@effect/vitest"; import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; import * as Queue from "effect/Queue"; import * as Stream from "effect/Stream"; @@ -38,9 +39,9 @@ it.effect("protects unknown desktop visibility until an explicit hidden report a yield* channel.awaitAttached({ threadId: key.threadId, tabId: "sentinel-1" }, "5 seconds"); expect(channel.isShown(key)).toBe(false); + const shown = yield* channel.awaitShown(key, "5 seconds").pipe(Effect.forkChild); yield* send({ type: "shown", ...key, shown: true }); - yield* send({ type: "attached", threadId: key.threadId, tabId: "sentinel-2" }); - yield* channel.awaitAttached({ threadId: key.threadId, tabId: "sentinel-2" }, "5 seconds"); + expect(yield* Fiber.join(shown)).toBe(true); expect(channel.isShown(key)).toBe(true); yield* send({ type: "shown", ...key, shown: false }); diff --git a/apps/server/src/preview/DesktopBrowserChannel.ts b/apps/server/src/preview/DesktopBrowserChannel.ts index 5d6b55fa882e..4da0efe3ce8f 100644 --- a/apps/server/src/preview/DesktopBrowserChannel.ts +++ b/apps/server/src/preview/DesktopBrowserChannel.ts @@ -47,6 +47,8 @@ export class DesktopBrowserChannel extends Context.Service< readonly isAttached: (key: DesktopTabKey) => Effect.Effect; /** Whether a desktop window draws the tab on screen, which no streamed viewer counts. */ readonly isShown: (key: DesktopTabKey) => boolean; + /** Resolves true once the tab is shown, or false on timeout. */ + readonly awaitShown: (key: DesktopTabKey, timeout: Duration.Input) => Effect.Effect; /** A load failure the desktop saw, possibly before the server connected to the tab. */ readonly loadFailure: (key: DesktopTabKey) => PreviewAutomationLoadError | undefined; readonly endpoint: (key: DesktopTabKey) => Effect.Effect; @@ -67,6 +69,7 @@ const make = Effect.gen(function* () { const attachedTabs = new Set(); // Missing reports protect desktop tabs until the renderer explicitly marks them hidden. const shownTabs = new Map(); + const shownReports = yield* PubSub.unbounded(); const loadFailures = new Map(); const inbound = new Map>(); const writeLock = yield* Semaphore.make(1); @@ -92,6 +95,9 @@ const make = Effect.gen(function* () { return Effect.void; }), isShown: () => false, + awaitShown: Effect.fn("DesktopBrowserChannel.awaitShown")(function () { + return Effect.succeed(false); + }), loadFailure: () => undefined, }); } @@ -149,7 +155,7 @@ const make = Effect.gen(function* () { } case "shown": shownTabs.set(id, event.shown); - return Effect.void; + return event.shown ? PubSub.publish(shownReports, id) : Effect.void; } }), Effect.catchCause((cause) => Effect.logWarning("desktop browser channel stopped", { cause })), @@ -224,6 +230,8 @@ const make = Effect.gen(function* () { return `ws://127.0.0.1:${address.port}/${secret}`; }); + const isShown = (key: DesktopTabKey) => shownTabs.get(keyOf(key)) ?? true; + return DesktopBrowserChannel.of({ available: true, awaitAttached: Effect.fn("DesktopBrowserChannel.awaitAttached")(function (key, timeout) { @@ -252,7 +260,22 @@ const make = Effect.gen(function* () { isAttached: Effect.fn("DesktopBrowserChannel.isAttached")(function (key) { return Effect.sync(() => attachedTabs.has(keyOf(key))); }), - isShown: (key) => shownTabs.get(keyOf(key)) ?? true, + isShown, + awaitShown: Effect.fn("DesktopBrowserChannel.awaitShown")(function (key, timeout) { + return Effect.scoped( + Effect.gen(function* () { + const subscription = yield* PubSub.subscribe(shownReports); + if (isShown(key)) return true; + return yield* Stream.fromSubscription(subscription).pipe( + Stream.filter((id) => id === keyOf(key)), + Stream.runHead, + Effect.map(Option.isSome), + Effect.timeoutOption(timeout), + Effect.map((result) => Option.getOrElse(result, () => false)), + ); + }), + ); + }), loadFailure: (key) => loadFailures.get(keyOf(key)), endpoint, turn: Effect.fn("DesktopBrowserChannel.turn")(function (threadId, active) { diff --git a/apps/server/src/preview/ServerBrowser.test.ts b/apps/server/src/preview/ServerBrowser.test.ts index 8087a25e6e55..46a28b26aa8b 100644 --- a/apps/server/src/preview/ServerBrowser.test.ts +++ b/apps/server/src/preview/ServerBrowser.test.ts @@ -421,7 +421,13 @@ const desktopRenders = (tabId: string) => { /** When set, a desktop that has not attached a tab waits for it the way the real channel does. */ let desktopAttachesLate = false; let desktopAttachWaiting = Promise.withResolvers(); -const shownDesktopTabs = new Set(); +const shownDesktopTabs = new (class extends Set { + override add(tabId: string) { + super.add(tabId); + desktopDetaches.emit("shown", tabId); + return this; + } +})(); const releasedDesktopTabs: Array = []; const desktopLoadFailures = new Map(); const desktopTurns = new NodeEvents.EventEmitter(); @@ -509,6 +515,16 @@ const dependencies = Layer.mergeAll( ), isAttached: (key) => Effect.sync(() => desktopRenders(key.tabId)), isShown: (key) => shownDesktopTabs.has(key.tabId), + awaitShown: (key, timeout) => + shownDesktopTabs.has(key.tabId) + ? Effect.succeed(true) + : Effect.callback((resume) => { + const onShown = (tabId: string) => { + if (tabId === key.tabId) resume(Effect.succeed(true)); + }; + desktopDetaches.on("shown", onShown); + return Effect.sync(() => desktopDetaches.off("shown", onShown)); + }).pipe(Effect.timeoutOrElse({ duration: timeout, orElse: () => Effect.succeed(false) })), loadFailure: (key) => desktopLoadFailures.get(key.tabId), endpoint: (key) => Effect.acquireRelease(Effect.succeed(`ws://desktop/${key.tabId}`), () => @@ -3303,6 +3319,45 @@ it.effect("preview_open reports a tab it shows as visible once the client attach ).pipe(Effect.provide(layer)), ); +it.effect("preview_open reports a hidden desktop tab it reveals as visible", () => + Effect.scoped( + Effect.gen(function* () { + const broker = yield* Broker.PreviewAutomationBroker; + const manager = yield* Manager.PreviewManager; + yield* ServerBrowser.ServerBrowser; + const events = yield* manager.subscribeEvents; + yield* Effect.yieldNow; + desktopRendersNext = true; + const created = yield* broker.invoke({ + scope, + operation: "open", + input: { reuseExistingTab: false, open: false }, + }); + const tabId = PreviewTabId.make(created.tabId!); + expect(created.visible).toBe(false); + // Like the desktop renderer, the docked panel reports the tab shown after the reveal arrives. + yield* Effect.gen(function* () { + let event; + do event = yield* PubSub.take(events); + while (event.type !== "navigated" || !event.snapshot.revealRequest); + // The report crosses the client, the desktop main process and its pipe, so it lands a task later. + yield* Effect.yieldNow; + yield* Effect.sync(() => shownDesktopTabs.add(tabId)); + }).pipe(Effect.forkScoped); + + const opened = yield* broker.invoke({ + scope, + tabId, + operation: "open", + input: { open: true }, + }); + + expect(opened.visible).toBe(true); + expect(opened.tabs).toEqual([expect.objectContaining({ tabId, visible: true })]); + }), + ).pipe(Effect.provide(layer)), +); + it.effect("a session's own tab stays its default while other sessions' tabs are listed", () => Effect.scoped( Effect.gen(function* () { diff --git a/apps/server/src/preview/ServerBrowser.ts b/apps/server/src/preview/ServerBrowser.ts index 59f70c887f14..8d4e6080daa4 100644 --- a/apps/server/src/preview/ServerBrowser.ts +++ b/apps/server/src/preview/ServerBrowser.ts @@ -128,6 +128,8 @@ const DESKTOP_VIEWPORT_READ_TIMEOUT = "1 second"; const DESKTOP_RESIZE_WAIT_MS = 1000; // A revealed tab's client opens the panel and attaches its stream a few round trips later, remote ones included. const REVEAL_VIEWER_WAIT_MS = 1000; +// A desktop panel's shown report waits on the renderer's layout, which a busy machine can push past a second. +const REVEAL_DESKTOP_SHOWN_WAIT_MS = 3000; const sleepUntil = (deadline: number) => new Promise((resolve) => setTimeout(resolve, Math.max(0, deadline - Date.now()))); @@ -2649,11 +2651,17 @@ const make = Effect.gen(function* () { }), ); // Only an explicit show is sure to reach a client; desktop tabs are visible without a viewer. + const remainingMs = deadlineMs - performance.now(); if (reveal === true && tab.viewers.size === 0 && tab.desktop === null) - shown = awaitViewer( - tab, - Math.min(REVEAL_VIEWER_WAIT_MS, deadlineMs - performance.now()), - ); + shown = awaitViewer(tab, Math.min(REVEAL_VIEWER_WAIT_MS, remainingMs)); + // A desktop panel reports the revealed tab shown a few hops after the reveal. + else if (reveal === true && !isVisible(tab)) + shown = runPromise( + desktopChannel.awaitShown( + tab, + Math.max(0, Math.min(REVEAL_DESKTOP_SHOWN_WAIT_MS, remainingMs)), + ), + ).then(constVoid); } await shown; return statusWithTitle(tab, request.agentSessionId); From d3c91008059beb5fbc97b782f070f19dbb60f41b Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 17 Nov 2026 04:14:07 -0800 Subject: [PATCH 032/133] fix(gitlab): issue timelines keep system events past the first page of notes (#38101) --- .../src/server/GitLabIssueTracker.test.ts | 83 +++++++++++ .../src/server/GitLabIssueTracker.ts | 139 +++++++++++++----- 2 files changed, 189 insertions(+), 33 deletions(-) diff --git a/packages/source-control-gitlab/src/server/GitLabIssueTracker.test.ts b/packages/source-control-gitlab/src/server/GitLabIssueTracker.test.ts index 63da6c97b642..9b6e23b16d0e 100644 --- a/packages/source-control-gitlab/src/server/GitLabIssueTracker.test.ts +++ b/packages/source-control-gitlab/src/server/GitLabIssueTracker.test.ts @@ -197,6 +197,89 @@ describe("GitLabIssueTracker", () => { }), ); + it.effect("keeps system events after the first hundred notes in the issue timeline", () => + Effect.gen(function* () { + const firstPage = Array.from({ length: 100 }, (_, index) => ({ + id: index + 1000, + body: "Discussion", + author: { username: "julius" }, + created_at: "2026-07-02T00:00:00Z", + })); + const api = yield* tracker((args) => { + const path = args[1]!; + if (path.includes("/notes?")) { + const page = new URLSearchParams(path.split("?")[1]).get("page"); + if (page === "1") return encode(firstPage); + if (page === "2") { + return encode([ + { + id: 1100, + body: "closed", + system: true, + author: { username: "theo" }, + created_at: "2026-07-03T00:00:00Z", + }, + ]); + } + return encode([]); + } + return answer(path); + }); + const target = { cwd: "/w", host: "gitlab.com", scope: "acme/web", key: "42" }; + const issue = yield* api.getIssue(target); + let cursor = issue.commentsCursor; + while (cursor !== null) { + cursor = (yield* api.getComments({ ...target, cursor })).nextCursor; + } + expect(issue.events).toContainEqual( + expect.objectContaining({ id: "note-1100", kind: "closed" }), + ); + }), + ); + + it.effect("follows GitLab's next page past a short page of notes", () => + Effect.gen(function* () { + const notes = (next: string, rows: ReadonlyArray) => + `HTTP/2.0 200 OK\r\nContent-Type: application/json\r\nX-Next-Page: ${next}\r\nX-Page: 1\r\n\r\n${encode(rows)}`; + const api = yield* tracker((args) => { + const path = args[1]!; + if (path.includes("/notes?")) { + const params = new URLSearchParams(path.split("?")[1]); + if (params.get("activity_filter") === "only_activity") { + return params.get("page") === "1" + ? notes("2", []) + : notes("", [ + { + id: 300, + body: "closed", + system: true, + author: { username: "theo" }, + created_at: "2026-07-03T00:00:00Z", + }, + ]); + } + return notes("2", [ + { + id: 1, + body: "Hi", + author: { username: "julius" }, + created_at: "2026-07-02T00:00:00Z", + }, + ]); + } + return answer(path); + }); + const issue = yield* api.getIssue({ + cwd: "/w", + host: "gitlab.com", + scope: "acme/web", + key: "42", + }); + expect(issue.commentsCursor).toBe("2"); + expect(issue.events.map((event) => event.id)).toEqual(["label-3", "note-300"]); + }), + ); + it.effect("pages a listing by GitLab's page number and stops on a short page", () => Effect.gen(function* () { const paths: string[] = []; diff --git a/packages/source-control-gitlab/src/server/GitLabIssueTracker.ts b/packages/source-control-gitlab/src/server/GitLabIssueTracker.ts index d33ba0ea0444..e30dcc18b256 100644 --- a/packages/source-control-gitlab/src/server/GitLabIssueTracker.ts +++ b/packages/source-control-gitlab/src/server/GitLabIssueTracker.ts @@ -1,7 +1,7 @@ /** - * GitLab's issue tracker over `glab api`. GitLab pages by offset and reports no total, so every - * cursor is a page number and a full page is the only sign that more exists. Notes, label - * events, linked merge requests and awards are separate endpoints, joined into the detail. + * GitLab's issue tracker over `glab api`. GitLab pages by offset, so every cursor is a page + * number. Notes, label events, linked merge requests and awards are separate endpoints, joined + * into the detail. */ import * as Effect from "effect/Effect"; import * as Result from "effect/Result"; @@ -9,6 +9,7 @@ import * as Schema from "effect/Schema"; import { IssueTrackerKind, type IssueCapabilities, + type IssueEvent, type IssueInvolvement, type IssueViewerPermissions, } from "@t3tools/contracts"; @@ -43,6 +44,8 @@ import { } from "./gitLabMergeRequestJson.ts"; const KIND = IssueTrackerKind.make("gitlab"); +/** How many pages of system notes the timeline reads before giving up on the rest. */ +const MAX_ACTIVITY_PAGES = 20; const CAPABILITIES: IssueCapabilities = { create: true, @@ -108,6 +111,26 @@ function commentsCursor(notesNext: string | null, awardsNext: string | null): st return awardsNext === null ? notesNext : `${notesNext}:${awardsNext}`; } +/** + * `glab api --include` output split into the body and GitLab's next page. GitLab can return a + * short page when it hides notes the viewer may not see, so only `X-Next-Page` says whether more + * exists; without headers a full page is taken as the sign. + */ +function splitPagedResponse(raw: string): { + readonly body: string; + readonly nextPage: number | null | undefined; +} { + if (!raw.startsWith("HTTP/")) return { body: raw, nextPage: undefined }; + const end = /\r?\n\r?\n/.exec(raw); + const headers = end === null ? raw : raw.slice(0, end.index); + const body = end === null ? "" : raw.slice(end.index + end[0].length); + const next = /^x-next-page:[ \t]*([1-9]\d{0,6})?[ \t]*\r?$/im.exec(headers); + return { + body, + nextPage: next === null ? undefined : next[1] === undefined ? null : Number(next[1]), + }; +} + function query(params: ReadonlyArray): string { return params.map(([key, value]) => `${key}=${encodeURIComponent(value)}`).join("&"); } @@ -185,6 +208,7 @@ export const make: Effect.Effect = readonly path: string; readonly method?: string; readonly body?: unknown; + readonly includeHeaders?: boolean; }) => gitlab .execute({ @@ -193,6 +217,7 @@ export const make: Effect.Effect = args: [ "api", input.path, + ...(input.includeHeaders === true ? ["--include"] : []), ...(input.method === undefined ? [] : ["--method", input.method]), // A JSON body from stdin: argv is visible in process listings, and `glab api --input` // sends no Content-Type of its own, which GitLab answers with HTTP 415. @@ -214,6 +239,7 @@ export const make: Effect.Effect = readonly path: string; readonly method?: string; readonly body?: unknown; + readonly includeHeaders?: boolean; readonly decode: (raw: string) => Result.Result; }): Effect.Effect => api(input).pipe( @@ -303,6 +329,7 @@ export const make: Effect.Effect = readonly path: string; readonly page: number; readonly operation: string; + readonly onlyActivity?: boolean; }) => read({ cwd: input.cwd, @@ -313,14 +340,44 @@ export const make: Effect.Effect = ["page", String(input.page)], ["order_by", "created_at"], ["sort", "asc"], + ...(input.onlyActivity === true ? [["activity_filter", "only_activity"] as const] : []), ])}`, - decode: decodeIssueNotesJson, - }).pipe( - Effect.map((notes) => ({ - ...notes, - nextCursor: notes.rawCount < PAGE_SIZE ? null : String(input.page + 1), - })), - ); + includeHeaders: true, + decode: (raw) => { + const { body, nextPage } = splitPagedResponse(raw); + return Result.map(decodeIssueNotesJson(body), (notes) => { + const next = + nextPage === undefined + ? notes.rawCount < PAGE_SIZE + ? null + : input.page + 1 + : nextPage; + return { ...notes, nextCursor: next === null ? null : String(next) }; + }); + }, + }); + + /** Every system note, wherever it falls among the comments, for the issue's timeline. */ + const activity = Effect.fn("GitLabIssueTracker.activity")(function* (input: { + readonly cwd: string; + readonly host: string; + readonly path: string; + }) { + const events: Array = []; + let page = 1; + for (let count = 0; count < MAX_ACTIVITY_PAGES; count++) { + const notes = yield* notesPage({ + ...input, + page, + operation: "getIssue", + onlyActivity: true, + }); + events.push(...notes.events); + if (notes.nextCursor === null) break; + page = Number(notes.nextCursor); + } + return events; + }); const awards = (input: { readonly cwd: string; @@ -444,6 +501,7 @@ export const make: Effect.Effect = page: 1, operation: "getIssue", }), + activity({ cwd: input.cwd, host: input.host, path }), read({ cwd: input.cwd, host: input.host, @@ -469,29 +527,44 @@ export const make: Effect.Effect = { concurrency: 4 }, ), ), - Effect.map(([issue, viewerLogin, notes, labelEvents, closing, related, awardPage]) => { - const closingKeys = new Set(closing.map((link) => `${link.repository}!${link.number}`)); - return { - ...issue, - viewer: viewerLogin, - viewerPermissions: VIEWER_PERMISSIONS, - states: ISSUE_STATES, - reactions: awardPage.reactions, - comments: notes.comments.map((comment) => ({ - ...comment, - reactions: awardPage.reactionsByNoteId.get(comment.id) ?? [], - })), - commentsCursor: commentsCursor(notes.nextCursor, awardPage.nextCursor), - events: [...notes.events, ...labelEvents].sort((left, right) => - left.createdAt.localeCompare(right.createdAt), - ), - // A merge request that closes the issue outranks its sighting as a mere mention. - linkedPullRequests: [ - ...closing, - ...related.filter((link) => !closingKeys.has(`${link.repository}!${link.number}`)), - ], - }; - }), + Effect.map( + ([ + issue, + viewerLogin, + notes, + systemEvents, + labelEvents, + closing, + related, + awardPage, + ]) => { + const closingKeys = new Set( + closing.map((link) => `${link.repository}!${link.number}`), + ); + return { + ...issue, + viewer: viewerLogin, + viewerPermissions: VIEWER_PERMISSIONS, + states: ISSUE_STATES, + reactions: awardPage.reactions, + comments: notes.comments.map((comment) => ({ + ...comment, + reactions: awardPage.reactionsByNoteId.get(comment.id) ?? [], + })), + commentsCursor: commentsCursor(notes.nextCursor, awardPage.nextCursor), + events: [...systemEvents, ...labelEvents].sort((left, right) => + left.createdAt.localeCompare(right.createdAt), + ), + // A merge request that closes the issue outranks its sighting as a mere mention. + linkedPullRequests: [ + ...closing, + ...related.filter( + (link) => !closingKeys.has(`${link.repository}!${link.number}`), + ), + ], + }; + }, + ), ), getComments: (input) => { From ecb295516fb1a7a606e31778b14bf2c58dd4cc41 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 17 Nov 2026 04:37:38 -0800 Subject: [PATCH 033/133] fix(server): Git Bash drive paths load images and files on Windows (#38104) --- apps/server/src/assets/AssetAccess.test.ts | 27 +++++++++++++++++++ apps/server/src/assets/AssetAccess.ts | 6 ++--- .../src/workspace/WorkspaceFileSystem.test.ts | 21 +++++++++++++++ .../src/workspace/WorkspaceFileSystem.ts | 4 +-- .../{wslDrivePath.ts => hostDrivePath.ts} | 17 +++++++++--- 5 files changed, 67 insertions(+), 8 deletions(-) rename apps/server/src/workspace/{wslDrivePath.ts => hostDrivePath.ts} (67%) diff --git a/apps/server/src/assets/AssetAccess.test.ts b/apps/server/src/assets/AssetAccess.test.ts index 38203278c2ed..be4122e6f559 100644 --- a/apps/server/src/assets/AssetAccess.test.ts +++ b/apps/server/src/assets/AssetAccess.test.ts @@ -627,6 +627,33 @@ describe("AssetAccess", () => { }).pipe(Effect.provide(layerTest)), ); + // Agents on Windows copy paths from Git Bash, which prints `C:\x` as `/c/x`. + it.effect.runIf(HostProcess.Platform.defaultValue() === "win32")( + "resolves a Git Bash drive media path on Windows", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const workspaceRoot = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-gitbash-" }); + const canonicalFile = path.join(yield* fs.realPath(workspaceRoot), "shot.png"); + yield* fs.writeFile(canonicalFile, screenshotPng); + const gitBashPath = `/${canonicalFile[0]!.toLowerCase()}${canonicalFile.slice(2).replaceAll("\\", "/")}`; + + for (const resource of [ + { _tag: "media-file", threadId: ThreadId.make("thread-1"), path: gitBashPath }, + { _tag: "draft-workspace-file", cwd: workspaceRoot, path: gitBashPath }, + ] as const) { + const result = yield* issueAssetUrl({ resource, workspaceRoot }); + expect(result.imageDimensions).toEqual({ width: 390, height: 844 }); + const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length); + const separator = suffix.indexOf("/"); + expect( + yield* resolveAsset(suffix.slice(0, separator), suffix.slice(separator + 1)), + ).toMatchObject({ kind: "file", path: canonicalFile, mimeType: "image/png" }); + } + }).pipe(Effect.provide(layerTest)), + ); + // Resolving `file://attacker.test/share/cat.jpg` from an agent's markdown sent the // Windows user's NTLM credentials to attacker.test. it.effect("never resolves a network media path outside the thread's project", () => diff --git a/apps/server/src/assets/AssetAccess.ts b/apps/server/src/assets/AssetAccess.ts index 35da41fe7331..ba6254e8ca63 100644 --- a/apps/server/src/assets/AssetAccess.ts +++ b/apps/server/src/assets/AssetAccess.ts @@ -59,7 +59,7 @@ import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion"; import * as ProjectFaviconResolver from "../project/ProjectFaviconResolver.ts"; import { isWithinRoot } from "../workspace/KnownWorkspaces.ts"; import * as WorkspacePaths from "../workspace/WorkspacePaths.ts"; -import { toWslDrivePath } from "../workspace/wslDrivePath.ts"; +import { toHostDrivePath } from "../workspace/hostDrivePath.ts"; import * as NativeAppIconResolver from "./NativeAppIconResolver.ts"; import { sourceControlDefinitions } from "../sourceControl/sourceControlDefinitions.ts"; import { extractIcnsPng } from "./icns.ts"; @@ -583,7 +583,7 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i switch (input.resource._tag) { case "media-file": { let requestedPath = expandHomePath( - yield* toWslDrivePath(input.resource.path), + yield* toHostDrivePath(input.resource.path), yield* HostProcess.HomeDirectory, ); if (!path.isAbsolute(requestedPath)) { @@ -643,7 +643,7 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i const hostPath = input.resource.path.startsWith("~/") || input.resource.path.startsWith("~\\") ? expandHomePath(input.resource.path, yield* HostProcess.HomeDirectory) - : yield* toWslDrivePath(input.resource.path); + : yield* toHostDrivePath(input.resource.path); if (path.isAbsolute(hostPath)) { const finalized = yield* finalizeAbsoluteMediaFileAsset({ requestedPath: hostPath, diff --git a/apps/server/src/workspace/WorkspaceFileSystem.test.ts b/apps/server/src/workspace/WorkspaceFileSystem.test.ts index f00017e4001e..7fd184a1f1e9 100644 --- a/apps/server/src/workspace/WorkspaceFileSystem.test.ts +++ b/apps/server/src/workspace/WorkspaceFileSystem.test.ts @@ -443,6 +443,27 @@ it.layer(layerTest, { excludeTestServices: true })("WorkspaceFileSystemLive", (i }), ); + // Agents on Windows copy paths from Git Bash, which prints `C:\x` as `/c/x`. + it.effect.runIf(HostProcess.Platform.defaultValue() === "win32")( + "reads a Git Bash drive path on Windows", + () => + Effect.gen(function* () { + const service = yield* WorkspaceFileSystem.WorkspaceFileSystem; + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const cwd = yield* makeTempDir; + const filePath = path.join(yield* fs.realPath(yield* makeTempDir), "notes.md"); + yield* fs.writeFileString(filePath, "# Notes\n"); + const gitBashPath = `/${filePath[0]!.toLowerCase()}${filePath.slice(2).replaceAll("\\", "/")}`; + + expect((yield* service.getMetadata({ paths: [gitBashPath] })).entries).toEqual([ + { kind: "file", byteLength: 8 }, + ]); + const result = yield* service.readFile({ cwd, relativePath: gitBashPath }); + expect(result).toMatchObject({ contents: "# Notes\n", truncated: false }); + }), + ); + it.effect("refuses a network path outside the workspace", () => Effect.gen(function* () { const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem; diff --git a/apps/server/src/workspace/WorkspaceFileSystem.ts b/apps/server/src/workspace/WorkspaceFileSystem.ts index 98047345d4ff..8c3121aed6db 100644 --- a/apps/server/src/workspace/WorkspaceFileSystem.ts +++ b/apps/server/src/workspace/WorkspaceFileSystem.ts @@ -27,7 +27,7 @@ import * as KnownWorkspaces from "./KnownWorkspaces.ts"; import * as WorkspaceEntries from "./WorkspaceEntries.ts"; import * as WorkspacePaths from "./WorkspacePaths.ts"; import { fileHeaderMimeType } from "./fileHeaderMimeType.ts"; -import { toWslDrivePath } from "./wslDrivePath.ts"; +import { toHostDrivePath } from "./hostDrivePath.ts"; const PROJECT_READ_FILE_MAX_BYTES = 1024 * 1024; @@ -167,7 +167,7 @@ export const make = Effect.gen(function* () { const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; const toHostPath = (requestedPath: string) => - toWslDrivePath(requestedPath).pipe( + toHostDrivePath(requestedPath).pipe( Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), ); diff --git a/apps/server/src/workspace/wslDrivePath.ts b/apps/server/src/workspace/hostDrivePath.ts similarity index 67% rename from apps/server/src/workspace/wslDrivePath.ts rename to apps/server/src/workspace/hostDrivePath.ts index 188e1c85f45e..776b0fce779d 100644 --- a/apps/server/src/workspace/wslDrivePath.ts +++ b/apps/server/src/workspace/hostDrivePath.ts @@ -4,13 +4,24 @@ import * as Effect from "effect/Effect"; import * as ChildProcess from "effect/process/ChildProcess"; import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; +// Git Bash, which runs Claude Code's Bash tool on Windows, prints `C:\x` as `/c/x`. +const GIT_BASH_DRIVE_PATTERN = /^\/([a-zA-Z])(?:\/|$)/; + +// Maps a drive path written for the other side of a Windows host to this host's form. // WSL mounts Windows drives under a configurable automount root, so only wslpath knows where. // No WSL env check: servers started by systemd lack WSL_DISTRO_NAME, and off WSL the spawn just fails. -// Untraced: it runs for every chip path, and only drive paths on Linux do any work. -export const toWslDrivePath = Effect.fnUntraced(function* (requestedPath: string) { +// Untraced: it runs for every chip path, and only drive paths on Linux spawn anything. +export const toHostDrivePath = Effect.fnUntraced(function* (requestedPath: string) { + const platform = yield* HostProcess.Platform; + if (platform === "win32") { + return requestedPath.replace( + GIT_BASH_DRIVE_PATTERN, + (_, drive: string) => `${drive.toUpperCase()}:/`, + ); + } // spawn throws on a NUL byte instead of failing. if (!isWindowsDrivePath(requestedPath) || requestedPath.includes("\0")) return requestedPath; - if ((yield* HostProcess.Platform) !== "linux") return requestedPath; + if (platform !== "linux") return requestedPath; const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; const output = yield* spawner .string( From 25fada9351ce9f907ecbe8ca3a819e358646777d Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 17 Nov 2026 04:54:26 -0800 Subject: [PATCH 034/133] fix(server): a waiting child run marks its parent task waiting (#38112) --- .../DelegatedCompletionDelivery.test.ts | 21 +++++++++++++++++++ .../src/orchestration-v2/Orchestrator.ts | 3 ++- 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts b/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts index 533f035e150a..23b3deb1184c 100644 --- a/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts +++ b/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts @@ -2432,6 +2432,27 @@ it.layer(Layer.merge(layerTest, ProviderContinuationRequests.layer))( const resumed = yield* orchestrator.getThreadProjection(parentThreadId); assert.equal(resumed.subagents.find((row) => row.id === task.id)?.status, "running"); assert.isNull(resumed.subagents.find((row) => row.id === task.id)?.result); + + const started = (yield* orchestrator.getThreadProjection(child.childThreadId)).runs.find( + (run) => run.id === queued.id, + )!; + const waitingSequence = yield* eventSink.latestSequence(); + yield* eventSink.write({ + events: [ + { + id: EventId.make("event:held-followup-waiting"), + type: "run.updated", + threadId: child.childThreadId, + runId: started.id, + occurredAt: now, + payload: { ...started, status: "waiting" }, + }, + ], + }); + yield* waitForStatus(waitingSequence, "waiting"); + const waiting = yield* orchestrator.getThreadProjection(parentThreadId); + assert.equal(waiting.subagents.find((row) => row.id === task.id)?.status, "waiting"); + assert.equal(waiting.nodes.find((row) => row.id === task.id)?.status, "waiting"); }), ); diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 6e6c7fc862ff..933676e23d99 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -15824,7 +15824,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio stored.event.payload.queueHeld === true)) && ((stored.event.payload.delegatedTaskId !== undefined && (stored.event.payload.status === "queued" || - stored.event.payload.status === "starting")) || + stored.event.payload.status === "starting" || + stored.event.payload.status === "waiting")) || stored.event.payload.status === "completed" || stored.event.payload.status === "interrupted" || stored.event.payload.status === "failed" || From 758291c17669e0177d43ef12422a230ead47ac9d Mon Sep 17 00:00:00 2001 From: Simone Date: Tue, 17 Nov 2026 14:06:57 +0100 Subject: [PATCH 035/133] fix(server): preserve line breaks in repository identity paths (#38114) Co-authored-by: Simone <185146821+Lucenx9@users.noreply.github.com> Co-authored-by: Julius Marminge --- .../RepositoryIdentityResolver.test.ts | 19 +++++++++++++++---- .../src/project/RepositoryIdentityResolver.ts | 7 ++++--- 2 files changed, 19 insertions(+), 7 deletions(-) diff --git a/apps/server/src/project/RepositoryIdentityResolver.test.ts b/apps/server/src/project/RepositoryIdentityResolver.test.ts index 50d749c3fb1b..72bbb0165110 100644 --- a/apps/server/src/project/RepositoryIdentityResolver.test.ts +++ b/apps/server/src/project/RepositoryIdentityResolver.test.ts @@ -5,6 +5,7 @@ import { expect, it } from "@effect/vitest"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Path from "effect/Path"; +import * as HostProcess from "@t3tools/shared/HostProcess"; import { vi } from "vite-plus/test"; import * as ProcessRunner from "../processRunner.ts"; @@ -14,6 +15,14 @@ import * as RepositoryIdentityResolver from "./RepositoryIdentityResolver.ts"; const normalizePathSeparators = (value: string) => value.replaceAll("\\", "/"); const normalizeResolvedPath = (value: string) => normalizePathSeparators(value); +// Windows forbids CR and LF in file names. +const lineBreakSuffixes = HostProcess.Platform.defaultValue() === "win32" ? [] : ["\r", "\n"]; +const bareLayouts = [ + "bare clone", + "dot-bare", + ...lineBreakSuffixes.map((suffix) => `bare clone${suffix}`), +]; + const git = (cwd: string, args: ReadonlyArray) => Effect.gen(function* () { const processRunner = yield* ProcessRunner.ProcessRunner; @@ -137,7 +146,7 @@ it.layer(NodeServices.layer)("RepositoryIdentityResolverLive", (it) => { }).pipe(Effect.provide(RepositoryIdentityResolver.layer)), ); - it.effect.each(["repo", "repo "] as const)( + it.effect.each(["repo", "repo ", ...lineBreakSuffixes.map((suffix) => `repo${suffix}`)])( "returns the git top-level root path when resolving from a nested workspace in %j", (rootName) => Effect.gen(function* () { @@ -167,8 +176,8 @@ it.layer(NodeServices.layer)("RepositoryIdentityResolverLive", (it) => { }).pipe(Effect.provide(RepositoryIdentityResolver.layer)), ); - it.effect.each(["bare clone", "dot-bare"] as const)( - "resolves a %s to its Git directory and the same identity as a checkout", + it.effect.each(bareLayouts)( + "resolves a %j to its Git directory and the same identity as a checkout", (layout) => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; @@ -176,9 +185,11 @@ it.layer(NodeServices.layer)("RepositoryIdentityResolverLive", (it) => { const checkout = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-repository-identity-checkout-", }); - const root = yield* fileSystem.makeTempDirectoryScoped({ + const parent = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-repository-identity-bare-", }); + const root = path.join(parent, layout); + yield* fileSystem.makeDirectory(root); const bareGitDir = layout === "dot-bare" ? path.join(root, ".bare") : root; yield* git(checkout, ["init"]); diff --git a/apps/server/src/project/RepositoryIdentityResolver.ts b/apps/server/src/project/RepositoryIdentityResolver.ts index 826529e704b2..1a992388da2f 100644 --- a/apps/server/src/project/RepositoryIdentityResolver.ts +++ b/apps/server/src/project/RepositoryIdentityResolver.ts @@ -211,8 +211,8 @@ const resolveRepositoryIdentityCacheKey = Effect.fn("RepositoryIdentityResolver. return null; } if (topLevelResult.value.code === 0) { - // Paths may end in spaces, so strip only git's line terminator. - const rootPath = topLevelResult.value.stdout.replace(/\r?\n$/, ""); + // Git appends LF on every platform; a preceding CR belongs to the path. + const rootPath = topLevelResult.value.stdout.replace(/\n$/, ""); return rootPath.length > 0 ? new RepositoryIdentityCacheKey({ rootPath, isBare: false }) : null; @@ -256,7 +256,8 @@ const resolveRepositoryIdentityCacheKey = Effect.fn("RepositoryIdentityResolver. if (bareResult._tag === "None" || bareResult.value.timedOut) return null; if (bareResult.value.code !== 0) continue; - const [isBare, rootPath = ""] = bareResult.value.stdout.split(/\r?\n/); + const [isBare, ...rootLines] = bareResult.value.stdout.split("\n"); + const rootPath = rootLines.join("\n").replace(/\n$/, ""); // A checkout's .git directory contains remotes but is not a project root. return isBare === "true" && rootPath.length > 0 ? new RepositoryIdentityCacheKey({ rootPath, isBare: true }) From 1da3f3f3702841a604f76d460b2e5710838a812e Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 17 Nov 2026 05:12:03 -0800 Subject: [PATCH 036/133] fix(web): review comments added to the chat arrive whole with their line comments (#38113) --- .../pullRequestDetail.logic.test.ts | 99 ++++++++++++++++++- .../pullRequest/pullRequestDetail.logic.ts | 99 ++++++++++++++++--- .../pullRequest/usePullRequestDetail.ts | 3 + 3 files changed, 186 insertions(+), 15 deletions(-) diff --git a/apps/web/src/components/pullRequest/pullRequestDetail.logic.test.ts b/apps/web/src/components/pullRequest/pullRequestDetail.logic.test.ts index 04931ff06ea2..1f348f57afd1 100644 --- a/apps/web/src/components/pullRequest/pullRequestDetail.logic.test.ts +++ b/apps/web/src/components/pullRequest/pullRequestDetail.logic.test.ts @@ -1109,7 +1109,11 @@ describe("asking about a change rather than working on it", () => { }); describe("adding a remark to the chat", () => { - const pullRequest = { number: 42, url: "https://github.com/pingdotgg/t3code/pull/42" }; + const pullRequest = { + number: 42, + url: "https://github.com/pingdotgg/t3code/pull/42", + reviewThreads: [], + }; const remark = (id: string, body: string): PullRequestComment => ({ id, kind: "issue-comment", @@ -1131,6 +1135,97 @@ describe("adding a remark to the chat", () => { expect(context?.text).toBe("octocat: Why not reuse the existing parser?"); }); + it("keeps a review summary longer than a fix finding's bound whole", () => { + const summary = `No critical issues. ${"One misplaced doc comment inline. ".repeat(80)}End.`; + const context = buildPullRequestCommentContext(pullRequest, { + kind: "comment", + comment: remark("c1", summary), + }); + + expect(context?.text).toBe(`octocat: ${summary.trim()}`); + }); + + it("gives a GitHub review summary its link and the line comments it posted", () => { + const url = "https://github.com/pingdotgg/t3code/pull/42"; + const review: PullRequestComment = { + ...remark("r9", "One misplaced doc comment inline."), + kind: "review", + url: `${url}#pullrequestreview-9`, + reviewState: "COMMENTED", + }; + const lineComment = (id: string, reviewUrl: string, body: string) => ({ + id, + author: { login: "octocat", name: null, avatarUrl: null }, + body, + createdAt: "2026-07-03T00:00:00Z", + url: `${url}#discussion_${id}`, + reviewUrl, + }); + const reviewThreads = [ + { + id: "t1", + path: "src/main.rs", + line: 12, + side: "right" as const, + isResolved: false, + isOutdated: false, + comments: [ + lineComment("r1", `${url}#pullrequestreview-9`, "This doc comment belongs below."), + lineComment("r2", `${url}#pullrequestreview-10`, "Moved."), + ], + }, + ]; + + expect( + buildPullRequestCommentContext( + { ...pullRequest, reviewThreads, reviewThreadsTruncated: false }, + { kind: "comment", comment: review }, + )?.text, + ).toBe( + [ + "octocat: One misplaced doc comment inline.", + `Review: ${url}#pullrequestreview-9`, + "Line comments in this review:\n\noctocat on `src/main.rs` line 12: This doc comment belongs below.", + ].join("\n\n"), + ); + expect( + buildPullRequestCommentContext( + { ...pullRequest, reviewThreadsTruncated: false }, + { kind: "comment", comment: review }, + )?.text, + ).toBe( + [ + "octocat: One misplaced doc comment inline.", + `Review: ${url}#pullrequestreview-9`, + "This review posted no line comments.", + ].join("\n\n"), + ); + // A failed or partial thread read must not read as a review with no line comments. + expect( + buildPullRequestCommentContext( + { ...pullRequest, reviewThreadsTruncated: true }, + { kind: "comment", comment: review }, + )?.text, + ).toBe( + [ + "octocat: One misplaced doc comment inline.", + `Review: ${url}#pullrequestreview-9`, + "No line comments from this review were loaded.", + "More may exist; see the review link.", + ].join("\n\n"), + ); + + const sent = reviewCommentContextRecord( + buildPullRequestCommentContext( + { ...pullRequest, reviewThreads, reviewThreadsTruncated: false }, + { kind: "comment", comment: { ...review, body: `Summary ${"x".repeat(15_990)}` } }, + )!, + ).text; + expect(sent).toContain(`Review: ${url}#pullrequestreview-9`); + expect(sent).toContain("This doc comment belongs below."); + expect(sent).toContain("more characters of the review summary are omitted"); + }); + it("keeps every added remark when a later hand-off lands", () => { const added = ["c1", "c2"].flatMap( (id) => @@ -1223,7 +1318,7 @@ describe("adding a remark to the chat", () => { }); it("keeps remarks from two repositories apart when their host ids match", () => { - const other = { number: 42, url: "https://github.com/octocat/fork/pull/42" }; + const other = { ...pullRequest, url: "https://github.com/octocat/fork/pull/42" }; const ids = [pullRequest, other].map( (target) => buildPullRequestCommentContext(target, { kind: "comment", comment: remark("c1", "why?") }) diff --git a/apps/web/src/components/pullRequest/pullRequestDetail.logic.ts b/apps/web/src/components/pullRequest/pullRequestDetail.logic.ts index 4f5c3948de52..f93b23d8d984 100644 --- a/apps/web/src/components/pullRequest/pullRequestDetail.logic.ts +++ b/apps/web/src/components/pullRequest/pullRequestDetail.logic.ts @@ -14,6 +14,7 @@ import { } from "@t3tools/client-runtime/source-control-clients"; import * as Schema from "effect/Schema"; import { + COMPOSER_CONTEXT_REVIEW_TEXT_MAX_CHARS, GitCommandError, PullRequestDetail, PullRequestOperationError, @@ -916,6 +917,16 @@ function terminologyForUrl(url: string): ChangeRequestTerminology { .changeRequest; } +function reviewThreadText(thread: PullRequestReviewThread): string { + return thread.comments + .flatMap((comment) => { + const body = readableBody(comment.body); + return body === null ? [] : [`${comment.author?.login ?? "ghost"}: ${body}`]; + }) + .join("\n") + .trim(); +} + function reviewThreadContext( thread: PullRequestReviewThread, pullRequestNumber: number, @@ -931,14 +942,7 @@ function reviewThreadContext( rangeLabel: thread.line === null ? "file" : `L${thread.line}${thread.side === "left" ? " (before)" : ""}`, // Strip bot bookkeeping comments before bounding finding text. - text: bounded( - thread.comments - .flatMap((comment) => { - const body = readableBody(comment.body); - return body === null ? [] : [`${comment.author?.login ?? "ghost"}: ${body}`]; - }) - .join("\n"), - ), + text: bounded(reviewThreadText(thread)), diff: "", fenceLanguage: inferReviewCommentFenceLanguage(thread.path), }; @@ -1258,15 +1262,25 @@ export type PullRequestChatSubject = Extract; + readonly reviewThreadsTruncated?: boolean | undefined; + }, subject: PullRequestChatSubject, ): ReviewCommentContext | null { const pullRequestNumber = pullRequest.number; + // Unlike a batch fix, one remark brought in to talk about travels whole. if (subject.kind === "thread") { - const context = reviewThreadContext(subject.thread, pullRequestNumber); - return context.text === "" + const text = reviewThreadText(subject.thread); + return text === "" ? null - : { ...context, id: `pr-comment:${pullRequest.url}:thread:${subject.thread.id}` }; + : { + ...reviewThreadContext(subject.thread, pullRequestNumber), + id: `pr-comment:${pullRequest.url}:thread:${subject.thread.id}`, + text, + }; } const comment = subject.comment; const body = readableBody(comment.body); @@ -1281,7 +1295,7 @@ export function buildPullRequestCommentContext( startIndex: 0, endIndex: 0, rangeLabel: "comment", - text: bounded(`${author}: ${body}`), + text: remarkText(`${author}: ${body}`.trim(), reviewLineComments(comment, pullRequest)), diff: "", ...(comment.path === null ? {} @@ -1289,6 +1303,65 @@ export function buildPullRequestCommentContext( }; } +/** + * The record keeps only the first COMPOSER_CONTEXT_REVIEW_TEXT_MAX_CHARS, so a long summary gives + * up its tail, never more than half, before the review link and line comments that follow it. + */ +function remarkText(remark: string, review: ReadonlyArray): string { + if (review.length === 0) return remark; + const after = review.join("\n\n"); + const room = Math.max( + COMPOSER_CONTEXT_REVIEW_TEXT_MAX_CHARS / 2, + COMPOSER_CONTEXT_REVIEW_TEXT_MAX_CHARS - after.length - 200, + ); + if (remark.length <= room) return `${remark}\n\n${after}`; + let end = room; + const last = remark.charCodeAt(end - 1); + if (last >= 0xd800 && last <= 0xdbff) end -= 1; + const omitted = remark.length - end; + return `${remark.slice(0, end)}\n… ${omitted} more characters of the review summary are omitted; read it at the review link.\n\n${after}`; +} + +/** A GitHub review summary's link and the line comments it posted, which live in other threads. */ +function reviewLineComments( + comment: PullRequestComment, + pullRequest: { + readonly reviewThreads: ReadonlyArray; + readonly reviewThreadsTruncated?: boolean | undefined; + }, +): ReadonlyArray { + const reviewThreads = pullRequest.reviewThreads; + const anchor = comment.kind === "review" ? parsePullRequestAnchor(comment.url) : null; + // Only GitHub links line comments to their review, so no other host can say it posted none. + if (anchor?.kind !== "timeline" || !/^pullrequestreview-\d+$/i.test(anchor.anchor)) return []; + const posted = reviewThreads.flatMap((thread) => + thread.comments.flatMap((lineComment) => { + const body = readableBody(lineComment.body); + if (body === null || !pullRequestAnchorMatchesUrl(anchor.anchor, lineComment.reviewUrl)) { + return []; + } + const line = thread.line === null ? "" : ` line ${thread.line}`; + return [`${lineComment.author?.login ?? "ghost"} on \`${thread.path}\`${line}: ${body}`]; + }), + ); + // Threads or their replies can be partly loaded; then an empty match proves nothing. + const complete = + pullRequest.reviewThreadsTruncated === false && + reviewThreads.every((thread) => thread.nextCommentsCursor === undefined); + const more = complete ? [] : ["More may exist; see the review link."]; + return [ + `Review: ${comment.url}`, + ...(posted.length === 0 + ? [ + complete + ? "This review posted no line comments." + : "No line comments from this review were loaded.", + ...more, + ] + : [`Line comments in this review:\n\n${posted.join("\n\n")}`, ...more]), + ]; +} + const ANSWER_INSTRUCTIONS = [ "Answer the question asked in this message. Do not change any code, and do not check anything out unless asked to.", ]; diff --git a/apps/web/src/components/pullRequest/usePullRequestDetail.ts b/apps/web/src/components/pullRequest/usePullRequestDetail.ts index a7b28a21b233..3977aa0e31f9 100644 --- a/apps/web/src/components/pullRequest/usePullRequestDetail.ts +++ b/apps/web/src/components/pullRequest/usePullRequestDetail.ts @@ -189,6 +189,9 @@ export function usePullRequestDetail( ), commentsTruncated: activity?.commentsTruncated ?? false, reviewThreads: activity?.reviewThreads ?? [], + ...(activity?.reviewThreadsTruncated === undefined + ? {} + : { reviewThreadsTruncated: activity.reviewThreadsTruncated }), ...(activity?.overviewThreads === undefined ? {} : { overviewThreads: activity.overviewThreads }), From 5842231421d0058f1ca7e829a66f648cb472aff1 Mon Sep 17 00:00:00 2001 From: Fuksss Date: Tue, 17 Nov 2026 14:32:18 +0100 Subject: [PATCH 037/133] fix(server): DOCX text for agents no longer includes object position numbers (#38116) Co-authored-by: Julius Marminge --- .../server/src/provider/documentTextWorker.ts | 10 ++++-- .../src/provider/userInputAttachments.test.ts | 31 +++++++++++++++++++ 2 files changed, 39 insertions(+), 2 deletions(-) diff --git a/apps/server/src/provider/documentTextWorker.ts b/apps/server/src/provider/documentTextWorker.ts index 5957fdd3cd89..52521495f9d5 100644 --- a/apps/server/src/provider/documentTextWorker.ts +++ b/apps/server/src/provider/documentTextWorker.ts @@ -15,7 +15,8 @@ type TextPart = string | typeof CELL_START | typeof CELL_END | { fallback: strin const TRUNCATED = "\n\n[Extracted text truncated at document extraction limits.]"; // Parts the document never displays: the XHTML head, tracked deletions and moves, field codes, -// phonetic guides, paragraph properties such as tab-stop definitions. +// phonetic guides, paragraph properties such as tab-stop definitions, drawing anchor layout +// values and encoded field data. const HIDDEN = new Set([ "head", "script", @@ -28,6 +29,11 @@ const HIDDEN = new Set([ "delInstrText", "tracked-changes", "pPr", + "positionH", + "positionV", + "sizeRelH", + "sizeRelV", + "fldData", ]); // @effect-diagnostics-next-line extendsNativeError:off - this worker loads no Effect runtime; Truncation is a local throw sentinel. @@ -109,7 +115,7 @@ function xml(source: string, extension: string): XmlNode { parent.children.pop(); return; } - if (!node.hasText && node.name !== "noBreakHyphen") return; + if (HIDDEN.has(node.name) || (!node.hasText && node.name !== "noBreakHyphen")) return; parent.hasText = true; if (node.name === "Choice") parent.hasTextChoice = true; }); diff --git a/apps/server/src/provider/userInputAttachments.test.ts b/apps/server/src/provider/userInputAttachments.test.ts index 4087601b58c0..570fcc2fe4d5 100644 --- a/apps/server/src/provider/userInputAttachments.test.ts +++ b/apps/server/src/provider/userInputAttachments.test.ts @@ -483,6 +483,37 @@ describe("question answer paths", () => { Effect.gen(function* () { const config = yield* ServerConfig.ServerConfig; const cases = [ + // Word stores object layout and field data outside the visible document text. + { + ext: "docx", + bounded: true, + parts: { + "word/document.xml": + 'Total cost is 1905000-6350042 EUR.', + }, + expected: ["Total cost is 42 EUR."], + absent: ["1905000", "-635", "0042"], + }, + { + ext: "docx", + bounded: true, + parts: { + "word/document.xml": + '1905000-63500Chart caption', + }, + expected: ["Chart caption"], + absent: ["1905000", "-635"], + }, + { + ext: "docx", + bounded: true, + parts: { + "word/document.xml": + 'As shown RU5ETk9URQ==(Smith 2020) earlier.', + }, + expected: ["As shown (Smith 2020) earlier."], + absent: ["RU5ETk9URQ=="], + }, { ext: "docx", bounded: true, From 81049d2b922d7509c4c8a9b12f72632e4a2607c1 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Tue, 17 Nov 2026 14:53:02 +0100 Subject: [PATCH 038/133] fix(web): importing light and dark theme files together keeps their custom CSS (#38134) Co-authored-by: Julius Marminge --- apps/web/src/vscodeThemeImport.test.ts | 29 +++++++++++ apps/web/src/vscodeThemeImport.ts | 18 +++++-- .../theme-batch-pair-keeps-css.e2e.ts | 51 +++++++++++++++++++ 3 files changed, 94 insertions(+), 4 deletions(-) create mode 100644 scripts/scenarios/theme-batch-pair-keeps-css.e2e.ts diff --git a/apps/web/src/vscodeThemeImport.test.ts b/apps/web/src/vscodeThemeImport.test.ts index f0172c2354d0..3d6edb383d38 100644 --- a/apps/web/src/vscodeThemeImport.test.ts +++ b/apps/web/src/vscodeThemeImport.test.ts @@ -468,6 +468,35 @@ describe("VS Code theme import", () => { expect(getThemeColorsForMode(themes[2]!, "light")).toBeNull(); }); + it.each([ + { name: "shared", light: "a {}", dark: "a {}", expected: [["Aurora", "a {}"]] }, + { name: "light-only", light: "a {}", dark: undefined, expected: [["Aurora", "a {}"]] }, + { name: "dark-only", light: undefined, dark: "a {}", expected: [["Aurora", "a {}"]] }, + { + name: "conflicting", + light: "a {}", + dark: "b {}", + expected: [ + ["Aurora Light", "a {}"], + ["Aurora Dark", "b {}"], + ], + }, + ])("pairs light and dark halves with $name custom CSS", ({ light, dark, expected }) => { + const themes = pairVsCodeThemes( + (["light", "dark"] as const).map((appearance) => { + const css = appearance === "light" ? light : dark; + return parseThemeFile({ + version: THEME_FILE_VERSION, + name: `Aurora ${appearance === "light" ? "Light" : "Dark"}`, + appearance, + colors: { canvas: appearance === "light" ? "#fafafa" : "#101014" }, + ...(css ? { css } : {}), + }); + }), + ); + expect(themes.map((theme) => [theme.label, theme.css])).toEqual(expected); + }); + it("does not guess when a family is ambiguous", () => { const make = (name: string, type: "light" | "dark") => parseVsCodeThemeFile({ diff --git a/apps/web/src/vscodeThemeImport.ts b/apps/web/src/vscodeThemeImport.ts index 416351b16edf..c65857115cff 100644 --- a/apps/web/src/vscodeThemeImport.ts +++ b/apps/web/src/vscodeThemeImport.ts @@ -412,17 +412,27 @@ export function pairVsCodeThemes( const paired: Array<{ theme: ThemeDefinition; order: number }> = []; for (const [key, group] of groups) { - if (group.light.length === 1 && group.dark.length === 1) { + const [light] = group.light; + const [dark] = group.dark; + // A theme carries one stylesheet for both modes, so conflicting CSS stays as two themes. + if ( + light && + dark && + group.light.length === 1 && + group.dark.length === 1 && + (!light.css || !dark.css || light.css === dark.css) + ) { try { paired.push({ order: group.order, theme: parseThemeFile({ version: THEME_FILE_VERSION, - ...(options?.pairedId ? { id: options.pairedId(group.light[0]!, group.dark[0]!) } : {}), + ...(options?.pairedId ? { id: options.pairedId(light, dark) } : {}), name: key, appearance: "light", - colors: group.light[0]!.colors, - variants: { dark: group.dark[0]!.colors }, + colors: light.colors, + variants: { dark: dark.colors }, + css: light.css ?? dark.css, }), }); continue; diff --git a/scripts/scenarios/theme-batch-pair-keeps-css.e2e.ts b/scripts/scenarios/theme-batch-pair-keeps-css.e2e.ts new file mode 100644 index 000000000000..05ded37a3768 --- /dev/null +++ b/scripts/scenarios/theme-batch-pair-keeps-css.e2e.ts @@ -0,0 +1,51 @@ +import { expect } from "e2e"; + +import { test, WEB } from "./t3.ts"; + +test( + "Importing light and dark theme files together keeps their shared custom CSS", + WEB, + async ({ t3, app, screen, browser }) => { + await t3.project("demo"); + await t3.open("/settings/appearance"); + await screen.getByRole("button", "Add theme", { exact: true }).tap(); + const dialog = screen.getByRole("dialog", "Add a theme"); + await browser.evaluate(() => { + const input = document.querySelector('input[type="file"]'); + if (!input) throw new Error("Theme file input is missing"); + const files = new DataTransfer(); + for (const appearance of ["light", "dark"] as const) { + const theme = { + version: 1, + name: `Aurora ${appearance === "light" ? "Light" : "Dark"}`, + appearance, + colors: { + canvas: appearance === "light" ? "#fafafa" : "#101014", + accent: "#6d5ae6", + }, + css: "[data-settings-page-scroll] { outline: 8px solid #ff2d95; outline-offset: -8px; }", + }; + files.items.add( + new File([JSON.stringify(theme)], `aurora-${appearance}.json`, { + type: "application/json", + }), + ); + } + input.files = files.files; + input.dispatchEvent(new Event("change", { bubbles: true })); + return null; + }); + await expect(dialog).toBeHidden(); + await screen.getByRole("button", "Use Aurora theme", { exact: true }).tap(); + await app.screenshot("paired-theme-custom-css"); + await expect + .poll(() => + browser.evaluate(() => { + const surface = document.querySelector("[data-settings-page-scroll]"); + if (!surface) throw new Error("Settings surface is missing"); + return getComputedStyle(surface).outlineWidth; + }), + ) + .toBe("8px"); + }, +); From 077b206b33b63e664f5f68dc1ad675d76bd2c730 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Tue, 17 Nov 2026 14:59:14 +0100 Subject: [PATCH 039/133] fix(web): same-named themes renamed on batch import keep their CSS (#38139) Co-authored-by: Julius Marminge --- .../components/settings/ThemeImportDialog.tsx | 22 +++----- apps/web/src/themePalette.ts | 13 +++++ apps/web/src/vscodeThemeImport.test.ts | 11 ++-- apps/web/src/vscodeThemeImport.ts | 10 +--- .../scenarios/theme-batch-renamed-css.e2e.ts | 52 +++++++++++++++++++ 5 files changed, 82 insertions(+), 26 deletions(-) create mode 100644 scripts/scenarios/theme-batch-renamed-css.e2e.ts diff --git a/apps/web/src/components/settings/ThemeImportDialog.tsx b/apps/web/src/components/settings/ThemeImportDialog.tsx index 106b85b87ec3..3ddd65988e63 100644 --- a/apps/web/src/components/settings/ThemeImportDialog.tsx +++ b/apps/web/src/components/settings/ThemeImportDialog.tsx @@ -7,9 +7,8 @@ import { cn } from "../../lib/utils"; import { getCustomThemes, installCustomTheme, - parseThemeFile, removeCustomTheme, - THEME_FILE_VERSION, + renameTheme, updateCustomTheme, type ThemeDefinition, } from "../../themePalette"; @@ -343,23 +342,16 @@ function ThemeImportBody({ theme: ThemeDefinition, preferredName?: string | null, ): ThemeDefinition => { - // The collection stays behind: updating a collection replaces every theme in it. - const copyNamed = (name: string) => - parseThemeFile({ - version: THEME_FILE_VERSION, - name, - appearance: theme.appearance, - colors: theme.colors, - ...(theme.variants ? { variants: theme.variants } : {}), - ...(theme.managed ? { managed: true } : {}), - ...(theme.css ? { css: theme.css } : {}), - }); + // renameTheme leaves the collection behind: updating a collection replaces every theme in it. if (preferredName && preferredName.toLowerCase() !== theme.label.toLowerCase()) { - const candidate = copyNamed(preferredName.slice(0, 48)); + const candidate = renameTheme(theme, preferredName.slice(0, 48)); if (!isThemeIdTaken(candidate.id)) return candidate; } for (let copy = 1; copy < 100; copy += 1) { - const candidate = copyNamed(`${theme.label.slice(0, 48 - ` (${copy})`.length)} (${copy})`); + const candidate = renameTheme( + theme, + `${theme.label.slice(0, 48 - ` (${copy})`.length)} (${copy})`, + ); if (!isThemeIdTaken(candidate.id)) return candidate; } throw new Error(`Too many copies of "${theme.label}".`); diff --git a/apps/web/src/themePalette.ts b/apps/web/src/themePalette.ts index a167ce97e721..98faba8e8b63 100644 --- a/apps/web/src/themePalette.ts +++ b/apps/web/src/themePalette.ts @@ -1581,6 +1581,19 @@ export function parseThemeFile(value: unknown): ThemeDefinition { }; } +/** A copy of `theme` under `name` and the id it derives. The collection stays behind. */ +export function renameTheme(theme: ThemeDefinition, name: string): ThemeDefinition { + return parseThemeFile({ + version: THEME_FILE_VERSION, + name, + appearance: theme.appearance, + colors: theme.colors, + ...(theme.variants ? { variants: theme.variants } : {}), + ...(theme.managed ? { managed: true } : {}), + ...(theme.css ? { css: theme.css } : {}), + }); +} + export function serializeThemeFile(theme: ThemeDefinition): string { const canonicalTheme = canonicalizeThemeDefinition(theme); const file: ThemeFile = { diff --git a/apps/web/src/vscodeThemeImport.test.ts b/apps/web/src/vscodeThemeImport.test.ts index 3d6edb383d38..50924f70c857 100644 --- a/apps/web/src/vscodeThemeImport.test.ts +++ b/apps/web/src/vscodeThemeImport.test.ts @@ -514,22 +514,27 @@ describe("VS Code theme import", () => { it("tells same-named variants apart by their file names", () => { // Both Dracula theme files declare the same internal name. - const dracula = (bg: string) => - parseVsCodeThemeFile({ + const css = ".app { outline: 1px solid red; }"; + const dracula = (bg: string) => ({ + ...parseVsCodeThemeFile({ name: "Dracula", type: "dark", colors: { "editor.background": bg, "editor.foreground": "#f8f8f2" }, - }); + }), + css, + }); const themes = resolveThemeLabelCollisions([ { theme: dracula("#282a36"), sourceName: "dracula.json" }, { theme: dracula("#22232e"), sourceName: "dracula-soft.json" }, ]); expect(themes.map((theme) => theme.label)).toEqual(["Dracula", "Dracula Soft"]); expect(themes.map((theme) => theme.id)).toEqual(["dracula", "dracula-soft"]); + expect(themes.map((theme) => theme.css)).toEqual([css, css]); const numbered = resolveThemeLabelCollisions([ { theme: dracula("#282a36") }, { theme: dracula("#22232e") }, ]); expect(numbered.map((theme) => theme.label)).toEqual(["Dracula", "Dracula 2"]); + expect(numbered.map((theme) => theme.css)).toEqual([css, css]); }); }); diff --git a/apps/web/src/vscodeThemeImport.ts b/apps/web/src/vscodeThemeImport.ts index c65857115cff..298abea94364 100644 --- a/apps/web/src/vscodeThemeImport.ts +++ b/apps/web/src/vscodeThemeImport.ts @@ -7,6 +7,7 @@ import { isReservedThemeId, parseThemeFile, readableThemeColorOn, + renameTheme, themeColorToHex, themeIdFromName, THEME_FILE_VERSION, @@ -451,14 +452,7 @@ export function resolveThemeLabelCollisions( ): ReadonlyArray { const rename = (theme: ThemeDefinition, name: string): ThemeDefinition | null => { try { - return parseThemeFile({ - version: THEME_FILE_VERSION, - name: name.slice(0, 48), - appearance: theme.appearance, - colors: theme.colors, - ...(theme.variants ? { variants: theme.variants } : {}), - ...(theme.managed ? { managed: true } : {}), - }); + return renameTheme(theme, name.slice(0, 48)); } catch { return null; } diff --git a/scripts/scenarios/theme-batch-renamed-css.e2e.ts b/scripts/scenarios/theme-batch-renamed-css.e2e.ts new file mode 100644 index 000000000000..9c7b7e59e942 --- /dev/null +++ b/scripts/scenarios/theme-batch-renamed-css.e2e.ts @@ -0,0 +1,52 @@ +import { expect } from "e2e"; + +import { test, WEB } from "./t3.ts"; + +test( + "Renaming same-named themes during a batch import preserves their CSS", + WEB, + async ({ t3, app, screen, browser }) => { + await t3.project("demo"); + await t3.open("/settings/appearance"); + await screen.getByRole("button", "Add theme", { exact: true }).tap(); + + await browser.evaluate(() => { + const files = new DataTransfer(); + for (const name of ["nyx-one.json", "nyx-two.json"]) { + files.items.add( + new File( + [ + JSON.stringify({ + version: 1, + name: "Nyx", + appearance: "light", + colors: { canvas: "#f4f1ff", accent: "#6d5ae6" }, + css: "[data-settings-page-scroll] { outline: 8px solid #ff2d95; outline-offset: -8px; }", + }), + ], + name, + { type: "application/json" }, + ), + ); + } + const target = document.querySelector('input[type="file"]')?.parentElement; + if (!target) throw new Error("No theme file drop target"); + target.dispatchEvent( + new DragEvent("drop", { dataTransfer: files, bubbles: true, cancelable: true }), + ); + return null; + }); + + await screen.getByRole("button", "Use Nyx One theme").tap(); + await app.screenshot("renamed-batch-theme-selected"); + await expect + .poll(() => + browser.evaluate(() => { + const page = document.querySelector("[data-settings-page-scroll]"); + if (!page) throw new Error("No Appearance settings page"); + return getComputedStyle(page).outlineWidth; + }), + ) + .toBe("8px"); + }, +); From 28d22620830182d552895ffe7a57ffe994823954 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Tue, 17 Nov 2026 15:02:25 +0100 Subject: [PATCH 040/133] fix(web): theme wallpaper stays in the live preview when connectivity returns (#38132) Co-authored-by: Julius Marminge --- apps/web/src/themeBackground.test.ts | 15 +++++++++++++++ apps/web/src/themeBackground.ts | 5 ++++- 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/apps/web/src/themeBackground.test.ts b/apps/web/src/themeBackground.test.ts index 5c0e7c3c91b4..589b2d411f5d 100644 --- a/apps/web/src/themeBackground.test.ts +++ b/apps/web/src/themeBackground.test.ts @@ -42,6 +42,7 @@ import { CUSTOM_THEMES_STORAGE_KEY, getThemeDefinition, invalidateCustomThemes, + THEME_PREVIEW_ID, } from "./themePalette"; const BACKGROUND = "--theme-background-image"; @@ -129,6 +130,20 @@ describe("theme backgrounds", () => { expect(t.fetchBackground).toHaveBeenCalledTimes(6); }); + it("keeps the shown background under a draft preview when the browser comes back online", async () => { + using t = setup(); + t.fetchBackground.mockImplementation(loaded); + applyThemeBackground("nightfall"); + await vi.advanceTimersByTimeAsync(0); + const shown = t.properties.get(BACKGROUND); + expect(shown).toMatch(/^url\("blob:/); + + document.documentElement.dataset.themeId = THEME_PREVIEW_ID; + t.browser.dispatchEvent(new Event("online")); + await vi.advanceTimersByTimeAsync(0); + expect(t.properties.get(BACKGROUND)).toBe(shown); + }); + it.each(["theme change", "disposal"])("stops retrying after %s", async (reason) => { using t = setup(); applyThemeBackground("nightfall"); diff --git a/apps/web/src/themeBackground.ts b/apps/web/src/themeBackground.ts index 26267de50d2f..2eec19b5a98b 100644 --- a/apps/web/src/themeBackground.ts +++ b/apps/web/src/themeBackground.ts @@ -12,6 +12,8 @@ import { getCustomThemes } from "./themePalette"; const THEME_BACKGROUND_VARIABLE = "--theme-background-image"; const RETRY_DELAYS_MS = [1_000, 2_000, 4_000, 8_000]; +// The editor's draft preview replaces the root's theme id, so retries track this instead. +let appliedThemeId: string | undefined; let shownKey: string | null = null; let loading: AbortController | null = null; let objectUrl: string | null = null; @@ -55,6 +57,7 @@ async function loadBackground( */ export function applyThemeBackground(themeId: string | undefined): void { if (typeof document === "undefined") return; + appliedThemeId = themeId; const environmentId = appAtomRegistry.get(themeEnvironmentIdAtom); // A saved theme wins its id over a published one, so the published image is not its. const revision = @@ -110,7 +113,7 @@ export function applyThemeBackground(themeId: string | undefined): void { * Coming back online retries a download that failed; a shown image is left alone. */ export function startThemeBackground(): () => void { - const reapply = () => applyThemeBackground(document.documentElement.dataset.themeId); + const reapply = () => applyThemeBackground(appliedThemeId); const unsubscribe = subscribeAtomChanges(themeServerEnvironmentThemesAtom, reapply); window.addEventListener("online", reapply); return () => { From 05d3cc94b2bd4aad3b035dd3e61e45299fcf40f0 Mon Sep 17 00:00:00 2001 From: Jakub Eichner <56561313+RedHot099@users.noreply.github.com> Date: Tue, 17 Nov 2026 15:11:11 +0100 Subject: [PATCH 041/133] fix(web): collapsing a timeline review thread no longer hits Unresolve (#38141) Co-authored-by: Julius Marminge --- .../pullRequest/PullRequestTimelineTab.tsx | 102 +++++++++--------- 1 file changed, 50 insertions(+), 52 deletions(-) diff --git a/apps/web/src/components/pullRequest/PullRequestTimelineTab.tsx b/apps/web/src/components/pullRequest/PullRequestTimelineTab.tsx index f5534749b643..202f849ecef6 100644 --- a/apps/web/src/components/pullRequest/PullRequestTimelineTab.tsx +++ b/apps/web/src/components/pullRequest/PullRequestTimelineTab.tsx @@ -236,6 +236,7 @@ function ConversationCard({ reactions, showPath = true, reply = false, + resolveButton = null, }: { event: PullRequestTimelineEvent; editable: PullRequestComment | null; @@ -245,6 +246,7 @@ function ConversationCard({ showPath?: boolean; /** A reply goes with its conversation, from the card that heads it. */ reply?: boolean; + resolveButton?: ReactNode; }) { const canReact = reactions.canReact(event); const [editing, setEditing] = useState(false); @@ -304,6 +306,7 @@ function ConversationCard({ {editable !== null && !editing ? ( setEditing(true)} /> ) : null} + {resolveButton} {event.body && event.comment && !reply ? ( ) : null} @@ -477,60 +480,46 @@ function ReviewThreadEvent({ fallback={} muted={!expanded} /> -

+ {dismissed ? Review dismissed : null} + {thread.isOutdated ? Outdated : null} + {expanded ? null : ( + + · {event.actor?.login ?? "ghost"} + {replyCount > 0 ? ( + <> + {" "} + · {replyCount.toLocaleString()} {replyCount === 1 ? "reply" : "replies"} + + ) : null} + + )} + + {expanded ? ( <> + } /> {thread.replies.length > 0 ? (
From ea6d3fc30fb066635f31326f49b85cdee8fbf8d7 Mon Sep 17 00:00:00 2001 From: Martin Date: Tue, 17 Nov 2026 15:14:27 +0100 Subject: [PATCH 042/133] fix(server): a Codex speed change sent during a running turn reaches Codex (#38130) Co-authored-by: Julius Marminge --- .../Adapters/CodexAdapterV2.test.ts | 90 +++++++++++++++++++ .../Adapters/CodexAdapterV2.ts | 14 +++ .../scripts/generate.ts | 22 ++++- .../src/_generated/meta.gen.ts | 5 ++ .../src/_generated/schema.gen.ts | 15 ++++ 5 files changed, 145 insertions(+), 1 deletion(-) diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts index 019dcf4ec0ed..f0f09e87ed14 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -1820,6 +1820,96 @@ describe("CodexAdapterV2 post-settle continuation", () => { ), ); + it.effect("a steer that changes the service tier updates Codex's next-turn settings", () => + Effect.gen(function* () { + const nativeThreadId = "steer-tier-thread"; + const nativeTurnId = "steer-tier-turn"; + const harness = yield* makeCodexReplayHarness( + makeCodexReplayTranscript({ + scenario: "steer-service-tier", + entries: [ + ...codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt: "Work." }), + { + type: "expect_outbound", + label: "thread/settings/update", + frame: { + id: 4, + method: "thread/settings/update", + params: { threadId: nativeThreadId, serviceTier: "fast" }, + }, + }, + { type: "emit_inbound", frame: { id: 4, result: {} } }, + { + type: "expect_outbound", + label: "turn/steer", + frame: { + id: 5, + method: "turn/steer", + params: { + threadId: nativeThreadId, + expectedTurnId: nativeTurnId, + input: [{ type: "text", text: "Hurry up." }], + }, + }, + }, + { type: "emit_inbound", frame: { id: 5, result: { turnId: nativeTurnId } } }, + { + type: "emit_inbound", + frame: { + method: "turn/completed", + params: { + threadId: nativeThreadId, + turn: makeCodexReplayTurn({ id: nativeTurnId, status: "completed" }), + }, + }, + }, + ], + }), + ); + const turnInput = makeCodexTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("steer-tier-attempt"), + text: "Work.", + }); + yield* harness.runtime.startTurn(turnInput); + yield* harness.until(() => + harness.events.some( + (event) => + event.type === "provider_turn.updated" && + event.providerTurn.nativeTurnRef?.nativeId === nativeTurnId, + ), + ); + const providerTurnId = harness.events.flatMap((event) => + event.type === "provider_turn.updated" ? [event.providerTurn.id] : [], + )[0]; + assert.isDefined(providerTurnId); + if (providerTurnId === undefined) return; + yield* harness.runtime.steerTurn({ + ...turnInput, + providerTurnId, + modelSelection: { + ...CODEX_TEST_MODEL_SELECTION, + options: [{ id: "serviceTier", value: "fast" }], + }, + message: { ...turnInput.message, text: "Hurry up." }, + }); + yield* harness.firstTerminal; + assert.equal(harness.terminalEvents()[0]?.status, "completed"); + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + it.effect("keeps native image views available to the clients", () => Effect.gen(function* () { const nativeThreadId = "image-view-thread"; diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index d1ddd569e60d..abea674b5e1d 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -8104,6 +8104,20 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( ); } + const serviceTier = + adapterOptions.resolveRuntime === undefined + ? getCodexServiceTierOptionValue(turnInput.modelSelection) + : undefined; + if (serviceTier !== undefined) { + // turn/steer carries no settings, and the turns Codex starts on its own reuse the thread's. + yield* client.request("thread/settings/update", { threadId, serviceTier }).pipe( + Effect.catch((cause) => + Effect.logWarning("orchestration-v2.codex-steer-service-tier-failed", { + cause, + }), + ), + ); + } const codexInput = yield* toCodexInput(turnInput); yield* client.request("turn/steer", { expectedTurnId: activeTurn.nativeTurnId, diff --git a/packages/effect-codex-app-server/scripts/generate.ts b/packages/effect-codex-app-server/scripts/generate.ts index 187895588c07..9945a300b90e 100644 --- a/packages/effect-codex-app-server/scripts/generate.ts +++ b/packages/effect-codex-app-server/scripts/generate.ts @@ -66,7 +66,27 @@ class GeneratorError extends Schema.TaggedError()("GeneratorErro } } +// Codex leaves experimental requests out of its published schema. +const ManualClientRequests: ReadonlyArray = [ + { method: "thread/settings/update", paramsType: "ThreadSettingsUpdateParams" }, +]; + const ManualSchemas: Record = { + ThreadSettingsUpdateParams: { + type: "object", + title: "ThreadSettingsUpdateParams", + properties: { + threadId: { type: "string" }, + serviceTier: { + anyOf: [{ type: "string" }, { type: "null" }], + }, + }, + required: ["threadId"], + }, + ThreadSettingsUpdateResponse: { + type: "object", + title: "ThreadSettingsUpdateResponse", + }, GetAuthStatusParams: { type: "object", title: "GetAuthStatusParams", @@ -779,7 +799,7 @@ const generateFiles = Effect.fn("generateFiles")(function* () { `https://raw.githubusercontent.com/openai/codex/${UPSTREAM_REF}/codex-rs/app-server-protocol/schema/typescript/ServerNotification.ts`, ); - const clientRequestEntries = parseRequestEntries(clientRequestRaw); + const clientRequestEntries = [...parseRequestEntries(clientRequestRaw), ...ManualClientRequests]; const clientNotificationEntries = parseNotificationEntries(clientNotificationRaw); const serverRequestEntries = parseRequestEntries(serverRequestRaw); const serverNotificationEntries = parseNotificationEntries(serverNotificationRaw); diff --git a/packages/effect-codex-app-server/src/_generated/meta.gen.ts b/packages/effect-codex-app-server/src/_generated/meta.gen.ts index 339bc326ac85..f5d25eec9979 100644 --- a/packages/effect-codex-app-server/src/_generated/meta.gen.ts +++ b/packages/effect-codex-app-server/src/_generated/meta.gen.ts @@ -108,6 +108,7 @@ export const CLIENT_REQUEST_METHODS = { gitDiffToRemote: "gitDiffToRemote", getAuthStatus: "getAuthStatus", fuzzyFileSearch: "fuzzyFileSearch", + "thread/settings/update": "thread/settings/update", } as const; export const CLIENT_NOTIFICATION_METHODS = { @@ -328,6 +329,7 @@ export interface ClientRequestParamsByMethod { readonly gitDiffToRemote: CodexSchema.GitDiffToRemoteParams; readonly getAuthStatus: CodexSchema.GetAuthStatusParams; readonly fuzzyFileSearch: CodexSchema.FuzzyFileSearchParams; + readonly "thread/settings/update": CodexSchema.ThreadSettingsUpdateParams; } export interface ClientRequestResponsesByMethod { @@ -438,6 +440,7 @@ export interface ClientRequestResponsesByMethod { readonly gitDiffToRemote: CodexSchema.GitDiffToRemoteResponse; readonly getAuthStatus: CodexSchema.GetAuthStatusResponse; readonly fuzzyFileSearch: CodexSchema.FuzzyFileSearchResponse; + readonly "thread/settings/update": CodexSchema.ThreadSettingsUpdateResponse; } export interface ClientNotificationParamsByMethod { @@ -667,6 +670,7 @@ export const CLIENT_REQUEST_PARAMS = { gitDiffToRemote: CodexSchema.GitDiffToRemoteParams, getAuthStatus: CodexSchema.GetAuthStatusParams, fuzzyFileSearch: CodexSchema.FuzzyFileSearchParams, + "thread/settings/update": CodexSchema.ThreadSettingsUpdateParams, } as const; export const CLIENT_REQUEST_RESPONSES = { @@ -779,6 +783,7 @@ export const CLIENT_REQUEST_RESPONSES = { gitDiffToRemote: CodexSchema.GitDiffToRemoteResponse, getAuthStatus: CodexSchema.GetAuthStatusResponse, fuzzyFileSearch: CodexSchema.FuzzyFileSearchResponse, + "thread/settings/update": CodexSchema.ThreadSettingsUpdateResponse, } as const; export const CLIENT_NOTIFICATION_PARAMS = { diff --git a/packages/effect-codex-app-server/src/_generated/schema.gen.ts b/packages/effect-codex-app-server/src/_generated/schema.gen.ts index 371cca59fcc9..d3fa560b64cc 100644 --- a/packages/effect-codex-app-server/src/_generated/schema.gen.ts +++ b/packages/effect-codex-app-server/src/_generated/schema.gen.ts @@ -50866,6 +50866,21 @@ export const ServerRequest__CommandExecutionApprovalDecision = Schema.Union( { mode: "oneOf" }, ); +export type ThreadSettingsUpdateParams = { + readonly threadId: string; + readonly serviceTier?: string | null; +}; +export const ThreadSettingsUpdateParams = Schema.Struct({ + threadId: Schema.String, + serviceTier: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), +}).annotate({ title: "ThreadSettingsUpdateParams" }); + +export type ThreadSettingsUpdateResponse = { readonly [x: string]: Schema.Json }; +export const ThreadSettingsUpdateResponse = Schema.Record( + Schema.String, + Schema.Json.annotate({ expected: "JSON value" }), +).annotate({ title: "ThreadSettingsUpdateResponse" }); + export type ToolRequestUserInputParams = { readonly autoResolutionMs?: number | null; readonly isBlocking: boolean; From 31706f3d41edd605aaba676bd75d9f77b260f4c2 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Tue, 17 Nov 2026 15:21:57 +0100 Subject: [PATCH 043/133] fix(shared): theme CSS check no longer rejects @import text inside a string (#38150) Co-authored-by: Grok 4.7 Co-authored-by: Julius Marminge --- packages/shared/src/themeCss.test.ts | 7 +++++++ packages/shared/src/themeCss.ts | 16 ++++++++++------ 2 files changed, 17 insertions(+), 6 deletions(-) diff --git a/packages/shared/src/themeCss.test.ts b/packages/shared/src/themeCss.test.ts index 80656a8207bb..9b63049b0e36 100644 --- a/packages/shared/src/themeCss.test.ts +++ b/packages/shared/src/themeCss.test.ts @@ -30,6 +30,13 @@ describe("themeCssValueFetches", () => { }); describe("themeCssLoadsRemoteFiles", () => { + it.each([ + ['[data-chat-header]::after { content: "@import"; }', false], + ['@import "x.css";', true], + ])("%s", (css, loads) => { + expect(themeCssLoadsRemoteFiles(css)).toBe(loads); + }); + it("allows a url() inside a data: address", () => { expect( themeCssLoadsRemoteFiles(`.repro { background-image: url('${SVG_WITH_OWN_GRADIENT}'); }`), diff --git a/packages/shared/src/themeCss.ts b/packages/shared/src/themeCss.ts index 0665f8cb5623..db0e86a61bc4 100644 --- a/packages/shared/src/themeCss.ts +++ b/packages/shared/src/themeCss.ts @@ -8,12 +8,16 @@ const URL_NOT_LOCAL = /url\((?![ \t\n\f\r]*["']?(?:data:|#))/i; const URL_OR_STRING = /url\((?![ \t\n\f\r]*["'])[^)]*|url\([ \t\n\f\r]*("[^"\n\r\f]*"|'[^'\n\r\f]*')|"[^"\n\r\f]*"|'[^'\n\r\f]*'/gi; -function fetchesByText(code: string): boolean { - const outsideStrings = code.replace(URL_OR_STRING, (token, urlString: string | undefined) => { +/** The code with its strings removed, keeping `url(` where a quoted url() can load a file. */ +function withoutStrings(code: string): string { + return code.replace(URL_OR_STRING, (token, urlString: string | undefined) => { if (urlString !== undefined) return /^["'](?:data:|#)/i.test(urlString) ? "" : "url("; return token.startsWith('"') || token.startsWith("'") ? "" : token; }); - return FETCHES_BY_STRING.test(outsideStrings) || URL_NOT_LOCAL.test(outsideStrings); +} + +function fetchesOutsideStrings(code: string): boolean { + return FETCHES_BY_STRING.test(code) || URL_NOT_LOCAL.test(code); } /** @@ -22,13 +26,13 @@ function fetchesByText(code: string): boolean { * so every value that still has a backslash is refused. */ export function themeCssValueFetches(value: string): boolean { - return value.includes("\\") || fetchesByText(value); + return value.includes("\\") || fetchesOutsideStrings(withoutStrings(value)); } /** A text check for early feedback. CSS escapes can dodge it; the client check is the guard. */ export function themeCssLoadsRemoteFiles(css: string): boolean { - const code = css.replace(/\/\*[\s\S]*?\*\//g, ""); - return /@import/i.test(code) || fetchesByText(code); + const code = withoutStrings(css.replace(/\/\*[\s\S]*?\*\//g, "")); + return /@import/i.test(code) || fetchesOutsideStrings(code); } /** From e9b48b7809974913515b10e4f2f7a0fd256a985c Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 17 Nov 2026 06:31:38 -0800 Subject: [PATCH 044/133] fix(muse): usage scanning no longer makes mise download Muse (#38158) --- packages/provider-muse/src/server/usage.test.ts | 1 + packages/provider-muse/src/server/usage.ts | 3 ++- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/packages/provider-muse/src/server/usage.test.ts b/packages/provider-muse/src/server/usage.test.ts index c90906aa80b6..3815cfce4432 100644 --- a/packages/provider-muse/src/server/usage.test.ts +++ b/packages/provider-muse/src/server/usage.test.ts @@ -226,6 +226,7 @@ describe("Muse history discovery", () => { PATH: "/host/bin", XDG_DATA_HOME: xdg ?? "/host/data", MUSE_NO_AUTO_UPDATE: "1", + MISE_OFFLINE: "1", }, readOnly: true, startupTimeoutMs: 5_000, diff --git a/packages/provider-muse/src/server/usage.ts b/packages/provider-muse/src/server/usage.ts index 64187d61556d..665093f154e3 100644 --- a/packages/provider-muse/src/server/usage.ts +++ b/packages/provider-muse/src/server/usage.ts @@ -5,6 +5,7 @@ import * as Schema from "effect/Schema"; import { mergeProviderInstanceEnvironment } from "@t3tools/provider-core/server/instanceEnvironment"; import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion"; +import { providerProbeEnvironment } from "@t3tools/provider-core/server/snapshotProbe"; import { tokenCount, totalTokens, @@ -137,7 +138,7 @@ export const museUsageReader: ProviderUsageReader< const binaryPath = expandHomePath(config?.binaryPath ?? "muse", home); const museHome = yield* usageHome.resolve({ binaryPath, - environment: makeMuseEnvironment(processEnvironment), + environment: providerProbeEnvironment(makeMuseEnvironment(processEnvironment)), awaitRefresh, }); if (Option.isNone(museHome)) return [{ dir: binaryPath, refreshing: true }]; From 0c676d95b1eb60525ca3e36e085d06a1302bf0df Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 17 Nov 2026 06:58:28 -0800 Subject: [PATCH 045/133] fix(web): screen readers name thread details issue and PR rows by number and title (#38160) --- .../chat/ThreadDetailsIssueRows.tsx | 2 +- .../chat/ThreadDetailsPrRow.browser.test.tsx | 68 ++++++++++++++++++- .../components/chat/ThreadDetailsPrRow.tsx | 11 ++- .../components/chat/ThreadDetailsPrRows.tsx | 2 - 4 files changed, 75 insertions(+), 8 deletions(-) diff --git a/apps/web/src/components/chat/ThreadDetailsIssueRows.tsx b/apps/web/src/components/chat/ThreadDetailsIssueRows.tsx index 327b8a0afa3f..b529cd6afe6a 100644 --- a/apps/web/src/components/chat/ThreadDetailsIssueRows.tsx +++ b/apps/web/src/components/chat/ThreadDetailsIssueRows.tsx @@ -29,7 +29,7 @@ export function ThreadDetailsIssueRows({ onOpenLink(event, link)} > diff --git a/apps/web/src/components/chat/ThreadDetailsPrRow.browser.test.tsx b/apps/web/src/components/chat/ThreadDetailsPrRow.browser.test.tsx index f2f41be10f95..1c3fa1a3899f 100644 --- a/apps/web/src/components/chat/ThreadDetailsPrRow.browser.test.tsx +++ b/apps/web/src/components/chat/ThreadDetailsPrRow.browser.test.tsx @@ -1,5 +1,6 @@ import { EnvironmentId, + IssueTrackerKind, ProjectId, SourceControlProviderKind, ThreadId, @@ -119,6 +120,7 @@ import { act, render as renderUi } from "../../../test/render"; import { useComposerDraftStore } from "~/composerDraftStore"; import { useUiStateStore } from "~/uiStateStore"; import { ThreadDetailsPrRow } from "./ThreadDetailsPrRow"; +import { ThreadDetailsIssueRows } from "./ThreadDetailsIssueRows"; import { ThreadDetailsThreadPrRows } from "./ThreadDetailsPrRows"; const threadRef: ScopedThreadRef = { @@ -173,7 +175,6 @@ it("merges with the last selected merge method", async () => { status={null} project={null} label="Test PR" - openAriaLabel="Open PR" onOpen={vi.fn()} />, ); @@ -202,7 +203,6 @@ it("requires a new merge click after passing checks become pending and pass agai status={null} project={null} label="Test PR" - openAriaLabel="Open PR" onOpen={vi.fn()} /> ); @@ -266,7 +266,6 @@ it("adds the failing checks to a given composer instead of opening a new thread" status={null} project={null} label="Test PR" - openAriaLabel="Open PR" onOpen={vi.fn()} composerTarget={threadRef} />, @@ -333,3 +332,66 @@ it.each([ `using ${expected}`, ); }); + +it("names a linked pull request row by its kind, number and title, not its URL", async () => { + await using screen = await setup(); + state.projects = [repositoryProject]; + state.pullRequests = [ + { + host: "github.com", + repository: "owner/repo", + number: 1, + url: "https://github.com/owner/repo/pull/1", + source: "manual", + linkedAt: "2026-10-30T00:00:00.000Z", + snapshot: null, + stack: null, + }, + ]; + await act(async () => { + await screen.rerender( + , + ); + }); + const row = [...screen.container.querySelectorAll("button")].find((button) => + button.textContent?.includes("Test PR"), + )!; + const name = row.getAttribute("aria-label") ?? row.textContent ?? ""; + expect(name).not.toContain("https://"); + expect(name).toMatch(/pull request/i); + expect(name).toContain("#1"); + expect(name).toContain("Test PR"); +}); + +it("names a linked issue row by its kind, number and title, not its URL", async () => { + await using screen = await setup(); + await act(async () => { + await screen.rerender( + , + ); + }); + const row = [...screen.container.querySelectorAll("button")].find((button) => + button.textContent?.includes("Sidebar flickers on resize"), + )!; + const name = row.getAttribute("aria-label") ?? row.textContent ?? ""; + expect(name).not.toContain("https://"); + expect(name).toMatch(/issue/i); + expect(name).toContain("#123"); + expect(name).toContain("Sidebar flickers on resize"); +}); diff --git a/apps/web/src/components/chat/ThreadDetailsPrRow.tsx b/apps/web/src/components/chat/ThreadDetailsPrRow.tsx index acf9629a1034..c06763298015 100644 --- a/apps/web/src/components/chat/ThreadDetailsPrRow.tsx +++ b/apps/web/src/components/chat/ThreadDetailsPrRow.tsx @@ -94,7 +94,6 @@ export function ThreadDetailsPrRow({ status, project, label, - openAriaLabel, onOpen, onActed, onStopWatching, @@ -107,7 +106,6 @@ export function ThreadDetailsPrRow({ status: PrStatusIndicator | null; project: EnvironmentProject | null; label: string; - openAriaLabel: string; onOpen: (event: ReactMouseEvent) => void; onActed?: () => void; onStopWatching?: (() => void) | undefined; @@ -265,6 +263,15 @@ export function ThreadDetailsPrRow({ ); + const stateLabel = ( + statePresentation ?? + (pr ? resolvePullRequestState({ state: pr.state, isDraft: pr.isDraft === true }) : null) + )?.label.toLowerCase(); + const title = (detail?.title ?? pr?.title)?.trim(); + const openAriaLabel = `${capitalizeTerm(terminology.singular)} #${number}${ + stateLabel ? `, ${stateLabel}` : "" + }${title ? `: ${title}` : ""}`; + const rowTooltip = detail === null || statePresentation === null ? ( diff --git a/apps/web/src/components/chat/ThreadDetailsPrRows.tsx b/apps/web/src/components/chat/ThreadDetailsPrRows.tsx index 65f796341d3f..31ea6c6865a4 100644 --- a/apps/web/src/components/chat/ThreadDetailsPrRows.tsx +++ b/apps/web/src/components/chat/ThreadDetailsPrRows.tsx @@ -71,7 +71,6 @@ function ThreadDetailsPrLinkRow({ status={prStatusIndicator(pr, linked?.sourceControlProvider)} project={project} label={`#${link.number}${link.snapshot === null ? "" : `: ${link.snapshot.title}`}`} - openAriaLabel={link.url} onOpen={onOpen} onStopWatching={onStopWatching} composerTarget={composerTarget} @@ -207,7 +206,6 @@ export function ThreadDetailsThreadPrRows({ status={displayed.status} project={rowProject} label={`#${number}${pr?.title.trim() ? `: ${pr.title}` : ""}`} - openAriaLabel={url} onOpen={(event) => openPrLink(event, url)} composerTarget={composerTarget} {...(onActed ? { onActed } : {})} From dd40cb51ea81fef5247beb55a796fba46d6187d7 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 17 Nov 2026 07:05:30 -0800 Subject: [PATCH 046/133] fix(web): dictating a citation comment keeps Save beside Cancel (#38172) --- .../chat/AssistantCitationCommentEditor.tsx | 39 ++++++++++--------- 1 file changed, 21 insertions(+), 18 deletions(-) diff --git a/apps/web/src/components/chat/AssistantCitationCommentEditor.tsx b/apps/web/src/components/chat/AssistantCitationCommentEditor.tsx index 570c44fb1fb3..76247ad2ccde 100644 --- a/apps/web/src/components/chat/AssistantCitationCommentEditor.tsx +++ b/apps/web/src/components/chat/AssistantCitationCommentEditor.tsx @@ -114,24 +114,27 @@ export function AssistantCitationCommentEditor({ ) : null}
- - + {/* Wrap as a pair so the recording pill never pushes Save alone onto a new row under Cancel. */} +
+ + +
); From bee9c3b796f9bb542a78df3c15a3d7e12988cd87 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 17 Nov 2026 07:14:21 -0800 Subject: [PATCH 047/133] fix(server): Devin questions accept a typed answer when allowOther is set (#38173) --- .../Adapters/AcpAdapterV2.test.ts | 35 +++++++++++++++++++ packages/provider-acp/src/server/adapter.ts | 4 ++- .../src/server/elicitationForm.ts | 16 +++++++-- 3 files changed, 52 insertions(+), 3 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts index 62f9d5f8bfbb..52123f19ef05 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts @@ -104,6 +104,7 @@ import { const DEFAULT_GROK_SETTINGS = Schema.decodeSync(GrokSettings)({}); const DROID_SETTINGS = Schema.decodeSync(AcpRegistrySettings)({ agentId: "factory-droid" }); +const DEVIN_SETTINGS = Schema.decodeSync(AcpRegistrySettings)({ agentId: "devin" }); const OMP_SETTINGS = Schema.decodeSync(AcpRegistrySettings)({ source: "local", commandPath: "/usr/local/bin/omp", @@ -2038,6 +2039,39 @@ describe("AcpAdapterV2", () => { answers: { q0: "blue" }, result: { action: "accept", content: { q0: "blue" } }, }, + { + scenario: "Devin allowOther choice accepts a typed answer", + settings: DEVIN_SETTINGS, + meta: { "cognition.ai/allowOther": true }, + schema: { + type: "object", + properties: { + q0: { + type: "string", + title: "Fruit", + description: "Which fruit?", + oneOf: [ + { const: "Apple", title: "Apple" }, + { const: "Banana", title: "Banana" }, + ], + }, + }, + required: ["q0"], + }, + questions: [ + { + id: "q0", + header: "Fruit", + question: "Which fruit?", + options: [ + { label: "Apple", description: "Apple", value: "Apple" }, + { label: "Banana", description: "Banana", value: "Banana" }, + ], + }, + ], + answers: { q0: "Mango" }, + result: { action: "accept", content: { q0: "Mango" } }, + }, ])("Registry elicitation $scenario", (fixture) => { const { schema, questions, answers, result } = fixture; const withAttachments = "withAttachments" in fixture && fixture.withAttachments; @@ -2121,6 +2155,7 @@ describe("AcpAdapterV2", () => { sessionId: "droid-session", message: "Your answer?", requestedSchema: schema, + ...("meta" in fixture ? { _meta: fixture.meta } : {}), }, }, }, diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index 7929572d71a5..7abc540793af 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -7118,7 +7118,9 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const nativeForm = flavor.extractElicitationForm?.(params); const parsedForm = nativeForm === undefined - ? parseElicitationForm(params.requestedSchema, params.message) + ? parseElicitationForm(params.requestedSchema, params.message, { + allowOther: unknownRecord(params._meta)?.["cognition.ai/allowOther"] === true, + }) : undefined; const form = nativeForm ?? diff --git a/packages/provider-acp/src/server/elicitationForm.ts b/packages/provider-acp/src/server/elicitationForm.ts index c2c9bc019a41..948306c13772 100644 --- a/packages/provider-acp/src/server/elicitationForm.ts +++ b/packages/provider-acp/src/server/elicitationForm.ts @@ -177,9 +177,11 @@ function typedAnswer( } // Decline unaskable forms; validate types and selection counts, leaving other constraints to the agent. +// `allowOther` lets single choices take typed text, sent as the field's value. export function parseElicitationForm( requestedSchema: unknown, message: string, + { allowOther = false }: { readonly allowOther?: boolean } = {}, ): ElicitationForm | undefined { const schema = unknownRecord(requestedSchema); const required = new Set( @@ -226,7 +228,10 @@ export function parseElicitationForm( header: text(property.title) ?? `Question ${questions.length + 1}`, question: text(property.description) ?? message, options, - ...(kind === "text" || kind === "number" || companions.has(id) + ...(kind === "text" || + kind === "number" || + companions.has(id) || + (allowOther && kind === "choice") ? {} : { allowCustomAnswer: false }), ...(kind === "multiChoice" ? { multiSelect: true } : {}), @@ -243,7 +248,14 @@ export function parseElicitationForm( const typed = answer === undefined ? undefined : typedAnswer(field, answer); const companionId = companions.get(id); if (typed !== undefined) entries.push([id, typed]); - else if (companionId !== undefined && typeof answer === "string") { + else if ( + allowOther && + field.kind === "choice" && + typeof answer === "string" && + answer.trim() !== "" + ) { + entries.push([id, answer]); + } else if (companionId !== undefined && typeof answer === "string") { entries.push([companionId, answer]); } else if (required.has(id)) return undefined; } From 47888ec2269408b6e749d7d0bfa30e95a572ae52 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 17 Nov 2026 07:29:45 -0800 Subject: [PATCH 048/133] fix(server): storage cleanup's merge-check fetch no longer times out at 30 s or starts git gc (#38174) --- apps/server/src/vcs/GitVcsDriverCore.test.ts | 17 ++++++++++++-- apps/server/src/vcs/GitVcsDriverCore.ts | 24 +++++++++++++------- 2 files changed, 31 insertions(+), 10 deletions(-) diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.ts index 7f6a6442ce50..302200c08993 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.test.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts @@ -5444,7 +5444,11 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); - it.effect("does not start Git auto-maintenance from background upstream fetches", () => + it.effect.each([ + { fetch: "statusDetailsRemote" }, + // Storage cleanup's merge check fetches the default branch on every sweep. + { fetch: "fetchRemoteTrackingBranch" }, + ] as const)("does not start Git auto-maintenance from background $fetch fetches", ({ fetch }) => Effect.gen(function* () { const cwd = yield* makeTmpDir(); const remote = yield* makeTmpDir("git-vcs-driver-remote-"); @@ -5461,12 +5465,21 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { yield* git(cwd, ["config", "gc.autoPackLimit", "1"]); yield* git(cwd, ["config", "gc.autoDetach", "false"]); yield* git(cwd, ["config", "maintenance.autoDetach", "false"]); + // The test template's global config turns auto-maintenance off. + yield* git(cwd, ["config", "maintenance.auto", "true"]); const packCount = git(cwd, ["count-objects", "-v"]).pipe( Effect.map((stdout) => stdout.match(/^packs: (\d+)$/m)?.[1]), ); assert.equal(yield* packCount, "2"); - yield* (yield* GitVcsDriver.GitVcsDriver).statusDetailsRemote(cwd); + const driver = yield* GitVcsDriver.GitVcsDriver; + if (fetch === "statusDetailsRemote") yield* driver.statusDetailsRemote(cwd); + else + yield* driver.fetchRemoteTrackingBranch({ + cwd, + remoteName: "origin", + remoteBranch: initialBranch, + }); assert.equal(yield* packCount, "2"); }), diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index ef45e272555e..466724edba7e 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -5839,14 +5839,22 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const fetchRemoteTrackingBranch: GitVcsDriver.GitVcsDriver["Service"]["fetchRemoteTrackingBranch"] = Effect.fn("fetchRemoteTrackingBranch")(function* (input) { - yield* runGit("GitVcsDriver.fetchRemoteTrackingBranch", input.cwd, [ - "fetch", - "--quiet", - "--no-tags", - "--", - input.remoteName, - `+refs/heads/${input.remoteBranch}:refs/remotes/${input.remoteName}/${input.remoteBranch}`, - ]); + // Storage cleanup runs this every sweep: like the status fetch, a killed fetch strands a + // `tmp_pack_*` and a failing `gc --auto` repeats each time, so allow time and skip gc. + yield* runGit( + "GitVcsDriver.fetchRemoteTrackingBranch", + input.cwd, + [ + "fetch", + "--quiet", + "--no-tags", + "--no-auto-gc", + "--", + input.remoteName, + `+refs/heads/${input.remoteBranch}:refs/remotes/${input.remoteName}/${input.remoteBranch}`, + ], + { timeoutMs: FETCH_REMOTE_TIMEOUT_MS }, + ); }); const setBranchUpstream: GitVcsDriver.GitVcsDriver["Service"]["setBranchUpstream"] = Effect.fn( From cc8593e06d8d3a9209949b07e75ef71d9b73eb0e Mon Sep 17 00:00:00 2001 From: Simone Date: Tue, 17 Nov 2026 16:30:18 +0100 Subject: [PATCH 049/133] fix(server): keep truncated document text valid Unicode (#38171) Co-authored-by: Simone <185146821+Lucenx9@users.noreply.github.com> Co-authored-by: Julius Marminge --- apps/server/src/provider/documentTextWorker.ts | 2 +- apps/server/src/provider/userInputAttachments.test.ts | 10 +++++++--- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/apps/server/src/provider/documentTextWorker.ts b/apps/server/src/provider/documentTextWorker.ts index 52521495f9d5..27556d3af9ac 100644 --- a/apps/server/src/provider/documentTextWorker.ts +++ b/apps/server/src/provider/documentTextWorker.ts @@ -738,5 +738,5 @@ export async function extractDocumentText(path: string, extension: string): Prom } result = result.replaceAll(/\n(?:[ \t]*\n){2,}/g, "\n\n").trim(); if (!result && !truncated) throw new Error("No text extracted"); - return result + (truncated ? TRUNCATED : ""); + return truncated ? result.replace(/[\uD800-\uDBFF]$/, "").trimEnd() + TRUNCATED : result; } diff --git a/apps/server/src/provider/userInputAttachments.test.ts b/apps/server/src/provider/userInputAttachments.test.ts index 570fcc2fe4d5..88fbf9790a1a 100644 --- a/apps/server/src/provider/userInputAttachments.test.ts +++ b/apps/server/src/provider/userInputAttachments.test.ts @@ -1297,10 +1297,14 @@ describe("question answer paths", () => { }); expect(yield* (yield* DocumentText.DocumentText).ensure(unsupportedPath)).toBeUndefined(); expect(NodeFS.existsSync(unsupportedPath + ".txt")).toBe(false); - NodeFS.writeFileSync(path, String.raw`{\rtf1 ` + "x".repeat(1_000_100) + "}"); - expect(yield* Effect.promise(() => extractDocumentText(path, ".rtf"))).toContain( - "[Extracted text truncated", + NodeFS.writeFileSync( + path, + String.raw`{\rtf1 ` + "x".repeat(999_999) + String.raw`\u-10179?\u-8576? After}`, ); + const unicodeTruncated = yield* Effect.promise(() => extractDocumentText(path, ".rtf")); + expect(unicodeTruncated).toContain("[Extracted text truncated"); + expect(unicodeTruncated.isWellFormed()).toBe(true); + expect(unicodeTruncated.startsWith("x".repeat(999_999))).toBe(true); NodeFS.writeFileSync(path, String.raw`{\rtf1 First` + " ".repeat(1_000_100) + "Last}"); const whitespaceTruncated = yield* Effect.promise(() => extractDocumentText(path, ".rtf")); expect(whitespaceTruncated).toBe( From 8009cd8c3bc173a6baee11f2014357d7d120ad66 Mon Sep 17 00:00:00 2001 From: Martin Date: Tue, 17 Nov 2026 16:32:38 +0100 Subject: [PATCH 050/133] fix(server): a Codex speed pick made during a running turn reaches Codex (#38169) Co-authored-by: Julius Marminge --- .../Adapters/CodexAdapterV2.test.ts | 203 ++++++++++++++---- .../Adapters/CodexAdapterV2.ts | 66 ++++-- 2 files changed, 212 insertions(+), 57 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts index f0f09e87ed14..a7448dbb0974 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -1820,13 +1820,108 @@ describe("CodexAdapterV2 post-settle continuation", () => { ), ); - it.effect("a steer that changes the service tier updates Codex's next-turn settings", () => + it.effect.each([ + { codex: "accepts", reply: { result: {} } }, + { codex: "rejects", reply: { error: { code: -32601, message: "Method not found" } } }, + ] as const)( + "a steer that changes the service tier still steers when Codex $codex the settings update", + ({ codex, reply }) => + Effect.gen(function* () { + const nativeThreadId = `steer-tier-thread-${codex}`; + const nativeTurnId = `steer-tier-turn-${codex}`; + const harness = yield* makeCodexReplayHarness( + makeCodexReplayTranscript({ + scenario: `steer-service-tier-${codex}`, + entries: [ + ...codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt: "Work." }), + { + type: "expect_outbound", + label: "thread/settings/update", + frame: { + id: 4, + method: "thread/settings/update", + params: { threadId: nativeThreadId, serviceTier: "fast" }, + }, + }, + { type: "emit_inbound", frame: { id: 4, ...reply } }, + { + type: "expect_outbound", + label: "turn/steer", + frame: { + id: 5, + method: "turn/steer", + params: { + threadId: nativeThreadId, + expectedTurnId: nativeTurnId, + input: [{ type: "text", text: "Hurry up." }], + }, + }, + }, + { type: "emit_inbound", frame: { id: 5, result: { turnId: nativeTurnId } } }, + { + type: "emit_inbound", + frame: { + method: "turn/completed", + params: { + threadId: nativeThreadId, + turn: makeCodexReplayTurn({ id: nativeTurnId, status: "completed" }), + }, + }, + }, + ], + }), + ); + const turnInput = makeCodexTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("steer-tier-attempt"), + text: "Work.", + }); + yield* harness.runtime.startTurn(turnInput); + yield* harness.until(() => + harness.events.some( + (event) => + event.type === "provider_turn.updated" && + event.providerTurn.nativeTurnRef?.nativeId === nativeTurnId, + ), + ); + const providerTurnId = harness.events.flatMap((event) => + event.type === "provider_turn.updated" ? [event.providerTurn.id] : [], + )[0]; + assert.isDefined(providerTurnId); + if (providerTurnId === undefined) return; + yield* harness.runtime.steerTurn({ + ...turnInput, + providerTurnId, + modelSelection: { + ...CODEX_TEST_MODEL_SELECTION, + options: [{ id: "serviceTier", value: "fast" }], + }, + message: { ...turnInput.message, text: "Hurry up." }, + }); + yield* harness.firstTerminal; + assert.equal(harness.terminalEvents()[0]?.status, "completed"); + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + + it.effect("a speed change with no message updates Codex's next-turn settings", () => Effect.gen(function* () { - const nativeThreadId = "steer-tier-thread"; - const nativeTurnId = "steer-tier-turn"; + const nativeThreadId = "picker-tier-thread"; + const nativeTurnId = "picker-tier-turn"; const harness = yield* makeCodexReplayHarness( makeCodexReplayTranscript({ - scenario: "steer-service-tier", + scenario: "picker-service-tier", entries: [ ...codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt: "Work." }), { @@ -1835,24 +1930,10 @@ describe("CodexAdapterV2 post-settle continuation", () => { frame: { id: 4, method: "thread/settings/update", - params: { threadId: nativeThreadId, serviceTier: "fast" }, + params: { threadId: nativeThreadId, serviceTier: "default" }, }, }, { type: "emit_inbound", frame: { id: 4, result: {} } }, - { - type: "expect_outbound", - label: "turn/steer", - frame: { - id: 5, - method: "turn/steer", - params: { - threadId: nativeThreadId, - expectedTurnId: nativeTurnId, - input: [{ type: "text", text: "Hurry up." }], - }, - }, - }, - { type: "emit_inbound", frame: { id: 5, result: { turnId: nativeTurnId } } }, { type: "emit_inbound", frame: { @@ -1866,14 +1947,15 @@ describe("CodexAdapterV2 post-settle continuation", () => { ], }), ); - const turnInput = makeCodexTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now: yield* DateTime.now, - attemptId: RunAttemptId.make("steer-tier-attempt"), - text: "Work.", - }); - yield* harness.runtime.startTurn(turnInput); + yield* harness.runtime.startTurn( + makeCodexTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("picker-tier-attempt"), + text: "Work.", + }), + ); yield* harness.until(() => harness.events.some( (event) => @@ -1881,20 +1963,16 @@ describe("CodexAdapterV2 post-settle continuation", () => { event.providerTurn.nativeTurnRef?.nativeId === nativeTurnId, ), ); - const providerTurnId = harness.events.flatMap((event) => - event.type === "provider_turn.updated" ? [event.providerTurn.id] : [], - )[0]; - assert.isDefined(providerTurnId); - if (providerTurnId === undefined) return; - yield* harness.runtime.steerTurn({ - ...turnInput, - providerTurnId, - modelSelection: { - ...CODEX_TEST_MODEL_SELECTION, - options: [{ id: "serviceTier", value: "fast" }], - }, - message: { ...turnInput.message, text: "Hurry up." }, - }); + assert.isDefined(harness.runtime.applyModelSelection); + yield* ( + harness.runtime.applyModelSelection?.({ + providerThread: harness.providerThread, + modelSelection: { + ...CODEX_TEST_MODEL_SELECTION, + options: [{ id: "serviceTier", value: "default" }], + }, + }) ?? Effect.void + ); yield* harness.firstTerminal; assert.equal(harness.terminalEvents()[0]?.status, "completed"); }).pipe( @@ -4296,6 +4374,7 @@ describe("CodexAdapterV2 post-settle continuation", () => { "new-run", "steer", "start-fails", + "keep-changed-tier", ] as const)("handles terminal Codex capacity failures when retries %s", (outcome) => Effect.gen(function* () { const scenario = `capacity-${outcome}`; @@ -4338,6 +4417,23 @@ describe("CodexAdapterV2 post-settle continuation", () => { nativeTurnId: nativeTurnId(0), prompt, }); + // A speed picked while the first attempt runs; the retry must not send the old one. + const changedTier = outcome === "keep-changed-tier" ? "fast" : undefined; + const retryRequestId = (attempt: number) => (changedTier === undefined ? 3 : 4) + attempt; + if (changedTier !== undefined) { + entries.push( + { + type: "expect_outbound", + label: "thread/settings/update", + frame: { + id: 4, + method: "thread/settings/update", + params: { threadId: nativeThreadId, serviceTier: changedTier }, + }, + }, + { type: "emit_inbound", frame: { id: 4, result: {} } }, + ); + } entries.push( ...(outcome === "completion-only" ? failureEntries(0).slice(1) : failureEntries(0)), ); @@ -4363,7 +4459,7 @@ describe("CodexAdapterV2 post-settle continuation", () => { entries.push({ ...entry, frame: { - id: 3 + attempt, + id: retryRequestId(attempt), method: "turn/start", params: { threadId: nativeThreadId, @@ -4375,6 +4471,7 @@ describe("CodexAdapterV2 post-settle continuation", () => { sandboxPolicy: { type: "dangerFullAccess" }, summary: "auto", collaborationMode: { mode: "default", settings: { model: "gpt-5.4" } }, + ...(changedTier === undefined ? {} : { serviceTier: changedTier }), }, }, }); @@ -4411,7 +4508,7 @@ describe("CodexAdapterV2 post-settle continuation", () => { error: { code: -32603, message: "Start failed" }, }, } - : withReplayRequestId(entry, 3 + attempt), + : withReplayRequestId(entry, retryRequestId(attempt)), ); } else if (outcome !== "start-fails") { entries.push( @@ -4437,6 +4534,7 @@ describe("CodexAdapterV2 post-settle continuation", () => { if (outcome === "exhaust") entries.push(...failureEntries(attempt)); if ( outcome === "recover" || + outcome === "keep-changed-tier" || outcome === "completion-only" || outcome === "started-first" || outcome === "stop-starting" @@ -4520,6 +4618,24 @@ describe("CodexAdapterV2 post-settle continuation", () => { text: prompt, }); yield* harness.runtime.startTurn(turnInput); + if (changedTier !== undefined) { + yield* harness.until(() => + harness.events.some( + (event) => + event.type === "provider_turn.updated" && + event.providerTurn.nativeTurnRef?.nativeId === nativeTurnId(0), + ), + ); + yield* ( + harness.runtime.applyModelSelection?.({ + providerThread: harness.providerThread, + modelSelection: { + ...CODEX_TEST_MODEL_SELECTION, + options: [{ id: "serviceTier", value: changedTier }], + }, + }) ?? Effect.void + ); + } for (let attempt = 1; attempt <= Math.max(retries, 1); attempt++) { const milestone = yield* Queue.take(milestones); assert.equal(milestone.type, "turn_item.updated"); @@ -4591,6 +4707,7 @@ describe("CodexAdapterV2 post-settle continuation", () => { assert.equal( terminal?.status, outcome === "recover" || + outcome === "keep-changed-tier" || outcome === "completion-only" || outcome === "steer" || outcome === "started-first" || diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index abea674b5e1d..8c138e4a0ffd 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -1278,6 +1278,7 @@ function failureResetAt( interface ActiveCodexTurnContext { hookStopReason?: string; + appliedServiceTier?: string; capacityRetryAttempt?: number; capacityRetryPending?: Deferred.Deferred; closedCommandItemIds?: ReadonlySet; @@ -7239,6 +7240,21 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( yield* startNativeTurn( { ...context.input, + // A speed changed during the failed attempt outlives the retry. + ...(context.appliedServiceTier === undefined + ? {} + : { + modelSelection: { + ...context.input.modelSelection, + options: [ + ...(context.input.modelSelection.options ?? []).filter( + (option) => + option.id !== "serviceTier" && option.id !== "fastMode", + ), + { id: "serviceTier", value: context.appliedServiceTier }, + ], + }, + }), providerTurnOrdinal: context.providerTurnOrdinal + 1, }, [], @@ -7845,6 +7861,34 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( ), }; + // turn/steer carries no settings, and the turns Codex starts on its own reuse the thread's. + const applyServiceTier = Effect.fn("CodexAdapterV2.applyServiceTier")(function* ( + threadId: string, + modelSelection: ModelSelection | undefined, + ) { + const serviceTier = + adapterOptions.resolveRuntime === undefined + ? getCodexServiceTierOptionValue(modelSelection) + : undefined; + if (serviceTier === undefined) return; + const applied = yield* client + .request("thread/settings/update", { threadId, serviceTier }) + .pipe( + Effect.as(true), + Effect.catch((cause) => + Effect.logWarning("orchestration-v2.codex-service-tier-update-failed", { + cause, + }).pipe(Effect.as(false)), + ), + ); + if (!applied) return; + for (const turn of (yield* Ref.get(activeTurns)).values()) { + if (turn.providerThread.nativeThreadRef?.nativeId === threadId) { + turn.appliedServiceTier = serviceTier; + } + } + }); + const runtime: ProviderAdapter.ProviderAdapterV2SessionRuntime = { instanceId: adapterOptions.instanceId, driver: CODEX_PROVIDER, @@ -8104,20 +8148,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( ); } - const serviceTier = - adapterOptions.resolveRuntime === undefined - ? getCodexServiceTierOptionValue(turnInput.modelSelection) - : undefined; - if (serviceTier !== undefined) { - // turn/steer carries no settings, and the turns Codex starts on its own reuse the thread's. - yield* client.request("thread/settings/update", { threadId, serviceTier }).pipe( - Effect.catch((cause) => - Effect.logWarning("orchestration-v2.codex-steer-service-tier-failed", { - cause, - }), - ), - ); - } + yield* applyServiceTier(threadId, turnInput.modelSelection); const codexInput = yield* toCodexInput(turnInput); yield* client.request("turn/steer", { expectedTurnId: activeTurn.nativeTurnId, @@ -8138,6 +8169,13 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( ), ), ), + applyModelSelection: Effect.fn("CodexAdapterV2.applyModelSelection")(function* ({ + providerThread, + modelSelection, + }) { + const threadId = providerThread.nativeThreadRef?.nativeId; + if (threadId != null) yield* applyServiceTier(threadId, modelSelection); + }), // Dropping this connection's subscription lets the shared app-server // shut the native thread (and its MCP servers) down once it is idle. unloadThread: Effect.fn("CodexAdapterV2.unloadThread")( From d085ee5d155064d98a27e4e936f0316b1d92e70e Mon Sep 17 00:00:00 2001 From: Yash Singh Date: Tue, 17 Nov 2026 09:36:02 -0600 Subject: [PATCH 051/133] fix(web): decode HEIC previews under desktop CSP (#38188) --- .../files/imageDecode.browser.test.ts | 52 ++++++++++++++++++ .../components/files/imageDecode.worker.ts | 14 ++++- apps/web/test/fixtures/images/photo.heic | Bin 0 -> 642 bytes apps/web/vite.config.ts | 2 +- 4 files changed, 65 insertions(+), 3 deletions(-) create mode 100644 apps/web/src/components/files/imageDecode.browser.test.ts create mode 100644 apps/web/test/fixtures/images/photo.heic diff --git a/apps/web/src/components/files/imageDecode.browser.test.ts b/apps/web/src/components/files/imageDecode.browser.test.ts new file mode 100644 index 000000000000..604cdb8db287 --- /dev/null +++ b/apps/web/src/components/files/imageDecode.browser.test.ts @@ -0,0 +1,52 @@ +import { expect, it } from "vite-plus/test"; +import workerUrl from "./imageDecode.worker.ts?worker&url"; +import photoUrl from "../../../test/fixtures/images/photo.heic?url"; + +it("decodes HEIC under the desktop content security policy", async () => { + const bytes = await (await fetch(photoUrl)).arrayBuffer(); + const frame = document.createElement("iframe"); + frame.srcdoc = ``; + const controller = new AbortController(); + try { + const loaded = new Promise((resolve) => + frame.addEventListener("load", () => resolve(), { once: true }), + ); + document.body.append(frame); + await loaded; + const decoded = new Promise<{ blob?: Blob; error?: string }>((resolve) => { + window.addEventListener( + "message", + (event) => { + if (event.source === frame.contentWindow) resolve(event.data); + }, + { signal: controller.signal }, + ); + }); + frame.contentWindow!.postMessage( + { bytes, workerUrl: new URL(workerUrl, location.href).href }, + "*", + [bytes], + ); + const result = await decoded; + expect(result.error).toBeUndefined(); + expect(result.blob?.type).toBe("image/png"); + const bitmap = await createImageBitmap(result.blob!); + expect([bitmap.width, bitmap.height]).toEqual([128, 128]); + bitmap.close(); + } finally { + controller.abort(); + frame.remove(); + } +}); diff --git a/apps/web/src/components/files/imageDecode.worker.ts b/apps/web/src/components/files/imageDecode.worker.ts index cf3c9c121f9b..1821b038e55e 100644 --- a/apps/web/src/components/files/imageDecode.worker.ts +++ b/apps/web/src/components/files/imageDecode.worker.ts @@ -152,8 +152,18 @@ async function decode(bytes: ArrayBuffer, heif: boolean) { if (bytes.byteLength > 50 * 1024 * 1024) throw new Error("Preview limited to files under 50 MB."); if (heif) { validateHeif(bytes); - const { heicTo } = await import("heic-to/next"); - return await heicTo({ blob: new Blob([bytes]), type: "image/png" }); + // Desktop CSP forbids the JavaScript evaluation used by heic-to/next. + const { heicTo } = await import("heic-to/csp"); + const bitmap = await heicTo({ blob: new Blob([bytes]), type: "bitmap" }); + try { + const canvas = new OffscreenCanvas(bitmap.width, bitmap.height); + const context = canvas.getContext("2d"); + if (!context) throw new Error("Image decoding is unavailable."); + context.drawImage(bitmap, 0, 0); + return await canvas.convertToBlob({ type: "image/png" }); + } finally { + bitmap.close(); + } } const { decode: decodeTiff } = await import("tiff"); validateTiffMetadata(bytes); diff --git a/apps/web/test/fixtures/images/photo.heic b/apps/web/test/fixtures/images/photo.heic new file mode 100644 index 0000000000000000000000000000000000000000..6c14ec8276c2e0f27e88550dc3179bed111e8f91 GIT binary patch literal 642 zcmYjOziSjx5T3WI$3~AJcp?S~Yq&zhCKjR=;Ycna%^4x3Af9jcxPjf=V{_^qT3kTX zCM0P?icM-EN{Up1h=O1v{sXB(8bQGj4vDPa>}E}dH_SKlee-_IBcgJn-8D_0HNiq| zjMn&G6mq>$ Date: Tue, 17 Nov 2026 16:39:02 +0100 Subject: [PATCH 052/133] fix(ssh): Host patterns match Unicode aliases byte by byte like OpenSSH (#38184) Co-authored-by: Grok 4.7 --- packages/ssh/src/config.test.ts | 5 +++-- packages/ssh/src/config.ts | 15 ++++++++------- 2 files changed, 11 insertions(+), 9 deletions(-) diff --git a/packages/ssh/src/config.test.ts b/packages/ssh/src/config.test.ts index a38e08edbf7c..c3cafc968b75 100644 --- a/packages/ssh/src/config.test.ts +++ b/packages/ssh/src/config.test.ts @@ -90,7 +90,7 @@ describe("ssh config", () => { yield* fs.makeDirectory(path.join(sshDir, "single.d")); yield* fs.writeFileString( path.join(sshDir, "config"), - "Include config.d/*\nInclude config.d/.literal.conf\nInclude config.d/.enabled-*.conf\nInclude explicit-directory\nInclude single.d/team?one.conf\nInclude single.d/exact??.conf\nHost real\n HostName real.example.com\nHost svc?x\n HostName wrong.example.com\nHost svc\u2028x\n HostName correct.example.com\n", + "Include config.d/*\nInclude config.d/.literal.conf\nInclude config.d/.enabled-*.conf\nInclude explicit-directory\nInclude single.d/team?one.conf\nInclude single.d/exact??.conf\nHost real\n HostName real.example.com\nHost svc?x\n HostName wrong.example.com\nHost svc\u2028x\n HostName correct.example.com\nHost svc\u00f8x\n HostName byte-correct.example.com\n", ); for (const [index, separator] of ["\u2028", "\u2029"].entries()) { yield* fs.writeFileString( @@ -131,7 +131,7 @@ describe("ssh config", () => { ); yield* fs.writeFileString( path.join(sshDir, "known_hosts"), - "known.example.com ssh-ed25519 AAAA\n", + "known.example.com ssh-ed25519 AAAA\nbyte-correct.example.com ssh-ed25519 AAAA\n", ); const hosts = yield* discoverSshHosts({ homeDir }); @@ -145,6 +145,7 @@ describe("ssh config", () => { ["real", "real.example.com", "ssh-config"], ["single-ascii", "single-ascii.example.com", "ssh-config"], ["svc\u2028x", "correct.example.com", "ssh-config"], + ["svc\u00f8x", "byte-correct.example.com", "ssh-config"], ["team", "team.example.com", "ssh-config"], ["unicode-0", "unicode-0.example.com", "ssh-config"], ["unicode-1", "unicode-1.example.com", "ssh-config"], diff --git a/packages/ssh/src/config.ts b/packages/ssh/src/config.ts index 4ddc0923f551..795aa529d1f7 100644 --- a/packages/ssh/src/config.ts +++ b/packages/ssh/src/config.ts @@ -92,16 +92,17 @@ function escapeRegex(value: string): string { const utf8 = new TextEncoder(); -// OpenSSH's glob matches UTF-8 bytes, so `?` consumes one byte of a filename. function globBytes(value: string): string { return Array.from(utf8.encode(value), (byte) => String.fromCharCode(byte)).join(""); } -function globToRegExp(pattern: string): RegExp { - return new RegExp( - `^${escapeRegex(pattern).replace(/\\\*/gu, "[^]*").replace(/\\\?/gu, ".")}$`, +// OpenSSH matches Include globs and Host patterns on UTF-8 bytes, so `?` consumes one byte. +function globMatcher(pattern: string): (value: string) => boolean { + const regex = new RegExp( + `^${escapeRegex(globBytes(pattern)).replace(/\\\*/gu, "[^]*").replace(/\\\?/gu, ".")}$`, "u", ); + return (value) => regex.test(globBytes(value)); } function hasGlobWildcard(value: string): boolean { @@ -126,7 +127,7 @@ const expandGlob = Effect.fnUntraced(function* ( const directoryIsGlob = hasGlobWildcard(directoryPattern); const directories = directoryIsGlob ? yield* expandGlob(directoryPattern) : [directoryPattern]; - const matcher = globToRegExp(globBytes(basePattern)); + const matches = globMatcher(basePattern); const matchedPaths: string[] = []; for (const directory of directories) { if (!(yield* fs.exists(directory))) continue; @@ -137,7 +138,7 @@ const expandGlob = Effect.fnUntraced(function* ( : yield* fs.readDirectory(directory); for (const entry of entries) { if (entry.startsWith(".") && !basePattern.startsWith(".")) continue; - if (!matcher.test(globBytes(entry))) { + if (!matches(entry)) { continue; } const entryPath = path.join(directory, entry); @@ -165,7 +166,7 @@ function matchesHostPatterns(alias: string, patterns: ReadonlyArray): bo const hostPattern = negated ? pattern.slice(1) : pattern; const matches = hostPattern === "*" || - (hasSshPattern(hostPattern) ? globToRegExp(hostPattern).test(alias) : hostPattern === alias); + (hasSshPattern(hostPattern) ? globMatcher(hostPattern)(alias) : hostPattern === alias); if (!matches) continue; if (negated) return false; matched = true; From 56e449ff58ab039f0873cd30b55453abb482614f Mon Sep 17 00:00:00 2001 From: Guilherme Bernardes Rodrigues Date: Tue, 17 Nov 2026 08:48:28 -0700 Subject: [PATCH 053/133] fix(server): worktree recovery no longer fails on Windows when the emptied folder is in use (#38163) Co-authored-by: Julius Marminge --- .../ProviderTurnStartService.test.ts | 59 ++++++++++++++++++- .../src/workspace/restoreMissingWorktree.ts | 14 ++++- 2 files changed, 70 insertions(+), 3 deletions(-) diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts index edec4cad5879..d12e6fd1e8bd 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts @@ -337,6 +337,61 @@ effectIt.effect("restores a missing worktree before a send only under the worksp }).pipe(Effect.provide(layerRestoreLeaseTest)), ); +effectIt.effect("restores into a leftover worktree folder that cannot itself be removed", () => { + const worktreePath = `${managedWorktreesDir}/project/feature-restore`; + // Windows refuses to remove a folder that is still some process's cwd. + const remove = vi.fn((target: string) => + target === worktreePath + ? Effect.fail( + PlatformError.systemError({ + _tag: "Busy", + module: "FileSystem", + method: "remove", + pathOrDescriptor: target, + }), + ) + : Effect.void, + ); + const createWorktree = vi.fn(() => Effect.succeed({} as never)); + return Effect.gen(function* () { + const { restore } = yield* ThreadWorktreeRestore; + yield* restore({ + id: ThreadId.make("thread_leftover_restore"), + projectId: ProjectId.make("project_leftover_restore"), + worktreePath, + branch: "feature/restore", + }); + expect(remove).toHaveBeenCalledWith(`${worktreePath}/node_modules`, { recursive: true }); + expect(createWorktree).toHaveBeenCalledTimes(1); + }).pipe( + Effect.provide( + layerThreadWorktreeRestore.pipe( + Layer.provide( + Layer.mergeAll( + Layer.succeed(FileSystem.FileSystem, { + exists: (target: string) => Effect.succeed(!target.endsWith("/.git")), + readDirectory: () => Effect.succeed(["node_modules"]), + stat: () => Effect.succeed({ type: "Directory" }), + realPath: (target: string) => Effect.succeed(normalize(target)), + remove, + } as never), + layerWorktreeLocation(), + Layer.mock(GitWorkflow.GitWorkflowService)({ + pruneWorktrees: () => Effect.void, + createWorktree, + listLocalBranchNames: () => Effect.succeed(["feature/restore"]), + }), + Layer.mock(ProjectService.ProjectService)({ + getById: () => + Effect.succeedSome({ workspaceRoot: "/tmp/provider-turn-start-project" } as never), + }), + ), + ), + ), + ), + ); +}); + it.each([ { label: "directly in the scratch root", folder: "/tmp/t3-home/scratch/notes", recreated: true }, { label: "below another folder", folder: "/tmp/t3-home/scratch/notes/deep", recreated: false }, @@ -2445,7 +2500,9 @@ effectIt.effect.each(["cleanup-first", "startup-first"])( failReadsAfterRunning: true, }); harness.createWorktree.mockImplementation(() => - fileSystem.makeDirectory(worktreePath).pipe(Effect.as({} as never), Effect.orDie), + fileSystem + .makeDirectory(worktreePath, { recursive: true }) + .pipe(Effect.as({} as never), Effect.orDie), ); const open = harness.open.getMockImplementation()!; harness.open.mockImplementation(() => diff --git a/apps/server/src/workspace/restoreMissingWorktree.ts b/apps/server/src/workspace/restoreMissingWorktree.ts index dee23025dbf4..c2c3c00eb774 100644 --- a/apps/server/src/workspace/restoreMissingWorktree.ts +++ b/apps/server/src/workspace/restoreMissingWorktree.ts @@ -182,8 +182,18 @@ export const makeRestoreMissingWorktree = Effect.gen(function* () { worktreePath, branch, }); - // `git worktree add` refuses a non-empty target. - yield* (leftover ? fileSystem.remove(worktreePath, { recursive: true }) : Effect.void).pipe( + // `git worktree add` refuses a non-empty target but accepts an empty one. Keep the folder + // itself: Windows cannot remove a folder that is still a terminal's or provider's cwd. + const clearLeftovers = Effect.suspend(() => fileSystem.readDirectory(worktreePath)).pipe( + Effect.flatMap((entries) => + Effect.forEach( + entries, + (entry) => fileSystem.remove(path.join(worktreePath, entry), { recursive: true }), + { discard: true }, + ), + ), + ); + yield* (leftover ? clearLeftovers : Effect.void).pipe( Effect.andThen(recreateMissingWorktree({ cwd: project.workspaceRoot, worktreePath, branch })), Effect.mapError((cause) => cause._tag === "WorktreeRecreateNoBaseError" From 983654b3b2f7267a69e3d5d049d781aadbbc3166 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Tue, 17 Nov 2026 16:54:51 +0100 Subject: [PATCH 054/133] fix(web): an invalid host filter in an Issues link no longer crashes the page (#38190) Co-authored-by: Julius Marminge --- apps/web/src/components/issue/IssuesPage.tsx | 12 ++++---- .../components/issue/issueListPreferences.ts | 2 +- .../issue/issuesSearch.logic.test.ts | 5 ++-- .../components/issue/issuesSearch.logic.ts | 28 ++++++------------- .../pullRequest/pullRequestListPreferences.ts | 2 +- .../pullRequest/usePullRequestListView.ts | 8 +++--- apps/web/src/reopenClosedView.ts | 6 ++-- .../issues-invalid-host-keeps-page.e2e.ts | 11 ++++++++ 8 files changed, 38 insertions(+), 36 deletions(-) create mode 100644 scripts/scenarios/issues-invalid-host-keeps-page.e2e.ts diff --git a/apps/web/src/components/issue/IssuesPage.tsx b/apps/web/src/components/issue/IssuesPage.tsx index 94a1d4e905f9..b676dc74eb57 100644 --- a/apps/web/src/components/issue/IssuesPage.tsx +++ b/apps/web/src/components/issue/IssuesPage.tsx @@ -93,13 +93,13 @@ import { useDebouncedValue } from "~/state/queries"; import { primaryServerKeybindingsAtom } from "~/state/server"; export interface IssuesSearch extends IssueListPreferences { - readonly selectedEnvironmentId?: EnvironmentId; - readonly selectedProjectId?: ProjectId; + readonly selectedEnvironmentId?: EnvironmentId | undefined; + readonly selectedProjectId?: ProjectId | undefined; /** Part of the panel tab's identity, so a link reopens the tab a row press opened. */ - readonly selectedHost?: string; - readonly tracker?: string; - readonly scope?: string; - readonly key?: string; + readonly selectedHost?: string | undefined; + readonly tracker?: string | undefined; + readonly scope?: string | undefined; + readonly key?: string | undefined; } const STATE_TABS = [ diff --git a/apps/web/src/components/issue/issueListPreferences.ts b/apps/web/src/components/issue/issueListPreferences.ts index 5400c887a4e7..a93a267758f5 100644 --- a/apps/web/src/components/issue/issueListPreferences.ts +++ b/apps/web/src/components/issue/issueListPreferences.ts @@ -11,7 +11,7 @@ import { IssueInvolvement, IssueListState } from "@t3tools/contracts"; export interface IssueListPreferences { readonly who: IssueInvolvement; readonly status: IssueListState; - readonly host?: string; + readonly host?: string | undefined; readonly q?: string | undefined; /** `label`, `assignee` and `order` for the same reason: the pull-request page has `labels` and `sort`. */ readonly label?: ReadonlyArray | undefined; diff --git a/apps/web/src/components/issue/issuesSearch.logic.test.ts b/apps/web/src/components/issue/issuesSearch.logic.test.ts index ca2ef7fb021c..0ea88f19959b 100644 --- a/apps/web/src/components/issue/issuesSearch.logic.test.ts +++ b/apps/web/src/components/issue/issuesSearch.logic.test.ts @@ -3,10 +3,11 @@ import { describe, expect, it } from "vite-plus/test"; import { issuesSearchFromUrl } from "./issuesSearch.logic"; describe("issuesSearchFromUrl", () => { - it("replaces a malformed label or order instead of letting the raw value through", () => { + it("replaces a malformed filter instead of letting the raw value through", () => { // The router lays the validated keys over the raw search, so a key left out keeps its raw value. - const raw = { label: true, order: "oldest", assignee: " " }; + const raw = { label: true, order: "oldest", assignee: " ", host: true }; const search = { ...raw, ...issuesSearchFromUrl(raw) }; + expect(search.host).toBeUndefined(); expect(search.label).toBeUndefined(); expect(search.assignee).toBeUndefined(); expect(search.order).toBeUndefined(); diff --git a/apps/web/src/components/issue/issuesSearch.logic.ts b/apps/web/src/components/issue/issuesSearch.logic.ts index c15b2f24ffc3..ba0db88e6dda 100644 --- a/apps/web/src/components/issue/issuesSearch.logic.ts +++ b/apps/web/src/components/issue/issuesSearch.logic.ts @@ -7,37 +7,27 @@ const bounded = (value: unknown): string | undefined => { const text = typeof value === "number" ? String(value) : value; return typeof text === "string" && text.trim() ? text.trim().slice(0, 200) : undefined; }; -/** A search key that is either present as a string or absent, never present as undefined. */ -function present( - key: K, - value: string | undefined, -): { [P in K]?: V } { - return value === undefined ? {} : ({ [key]: value } as { [P in K]: V }); -} const labels = (raw: unknown): ReadonlyArray | undefined => { const names = (Array.isArray(raw) ? raw : [raw]).flatMap((name) => bounded(name) ?? []); return names.length === 0 ? undefined : names.slice(0, 20); }; +// Every optional key is an own key, even when undefined: the router lays these over the parent +// route's unvalidated search, where a key left out would keep its raw value. export const issuesSearchFromUrl = (raw: Record): IssuesSearch => ({ who: raw.who === "assigned" || raw.who === "authored" || raw.who === "mentioned" ? raw.who : "all", status: raw.status === "closed" || raw.status === "all" ? raw.status : "open", - ...present("host", bounded(raw.host)), - // `q`, `label`, `assignee` and `order` are always own keys: the router lays these over the parent route's - // unvalidated search, where a key left out would keep its raw value. + host: bounded(raw.host), q: bounded(raw.q), label: labels(raw.label), assignee: bounded(raw.assignee), order: raw.order === "created" ? "created" : undefined, - ...present<"selectedEnvironmentId", EnvironmentId>( - "selectedEnvironmentId", - bounded(raw.selectedEnvironmentId), - ), - ...present<"selectedProjectId", ProjectId>("selectedProjectId", bounded(raw.selectedProjectId)), - ...present("selectedHost", bounded(raw.selectedHost)), - ...present("tracker", bounded(raw.tracker)), - ...present("scope", bounded(raw.scope)), - ...present("key", bounded(raw.key)), + selectedEnvironmentId: bounded(raw.selectedEnvironmentId) as EnvironmentId | undefined, + selectedProjectId: bounded(raw.selectedProjectId) as ProjectId | undefined, + selectedHost: bounded(raw.selectedHost), + tracker: bounded(raw.tracker), + scope: bounded(raw.scope), + key: bounded(raw.key), }); diff --git a/apps/web/src/components/pullRequest/pullRequestListPreferences.ts b/apps/web/src/components/pullRequest/pullRequestListPreferences.ts index 816b51b92ce6..25cf7ef0cd80 100644 --- a/apps/web/src/components/pullRequest/pullRequestListPreferences.ts +++ b/apps/web/src/components/pullRequest/pullRequestListPreferences.ts @@ -24,7 +24,7 @@ export interface PullRequestListPreferences { readonly state: PullRequestListState; readonly environmentId?: EnvironmentId; readonly projectId?: ProjectId; - readonly host?: string; + readonly host?: string | undefined; readonly q?: string | undefined; readonly draft?: "only" | "hide"; readonly review?: NonNullable; diff --git a/apps/web/src/components/pullRequest/usePullRequestListView.ts b/apps/web/src/components/pullRequest/usePullRequestListView.ts index 7b9e128f12b6..2f6baa593b63 100644 --- a/apps/web/src/components/pullRequest/usePullRequestListView.ts +++ b/apps/web/src/components/pullRequest/usePullRequestListView.ts @@ -47,12 +47,12 @@ export interface PullRequestsSearch extends PullRequestListPreferences { readonly selectedUrl?: string; readonly environmentId?: EnvironmentId; readonly projectId?: ProjectId; - readonly host?: string; + readonly host?: string | undefined; readonly repository?: string; readonly number?: number; - readonly selectedProjectId?: ProjectId; - readonly selectedHost?: string; - readonly selectedEnvironmentId?: EnvironmentId; + readonly selectedProjectId?: ProjectId | undefined; + readonly selectedHost?: string | undefined; + readonly selectedEnvironmentId?: EnvironmentId | undefined; } const SEARCH_DEBOUNCE_MS = 250; diff --git a/apps/web/src/reopenClosedView.ts b/apps/web/src/reopenClosedView.ts index 6ff5b9b8fc9d..2a4d8a3199f2 100644 --- a/apps/web/src/reopenClosedView.ts +++ b/apps/web/src/reopenClosedView.ts @@ -56,9 +56,9 @@ export function planNextReopen( type PullRequestsSearchLike = Partial & { repository?: string; number?: number; - selectedProjectId?: ProjectId; - selectedHost?: string; - selectedEnvironmentId?: EnvironmentId; + selectedProjectId?: ProjectId | undefined; + selectedHost?: string | undefined; + selectedEnvironmentId?: EnvironmentId | undefined; }; export function pullRequestsSearchForRestore( diff --git a/scripts/scenarios/issues-invalid-host-keeps-page.e2e.ts b/scripts/scenarios/issues-invalid-host-keeps-page.e2e.ts new file mode 100644 index 000000000000..fd4a7009efdd --- /dev/null +++ b/scripts/scenarios/issues-invalid-host-keeps-page.e2e.ts @@ -0,0 +1,11 @@ +import { expect } from "e2e"; + +import { test, WEB } from "./t3.ts"; + +test("An invalid host filter keeps the Issues page open", WEB, async ({ t3, app, browser }) => { + await t3.project("demo"); + await t3.open("/issues?host=true"); + + await app.screenshot("issues-invalid-host"); + await expect(browser.locator("h1")).toHaveText("Issues"); +}); From b91ea5443c2a597899432c99be3d9b4a48058e09 Mon Sep 17 00:00:00 2001 From: Simone Date: Tue, 17 Nov 2026 17:16:34 +0100 Subject: [PATCH 055/133] fix(shared): keep Unicode whitespace in launch argument values (#38193) Co-authored-by: Simone <185146821+Lucenx9@users.noreply.github.com> Co-authored-by: Julius Marminge --- packages/shared/src/cliArgs.test.ts | 9 +++++++++ packages/shared/src/cliArgs.ts | 2 +- 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/packages/shared/src/cliArgs.test.ts b/packages/shared/src/cliArgs.test.ts index 62a4b3190edd..107b2cdf7277 100644 --- a/packages/shared/src/cliArgs.test.ts +++ b/packages/shared/src/cliArgs.test.ts @@ -35,6 +35,15 @@ describe("tokenizeCliArgs", () => { "--verbose", ]); } + + for (const whitespace of ["\u00a0", "\u2003", "\u2028", "\u2029"]) { + const path = `/tmp/project${whitespace}name`; + expect(tokenizeCliArgs(`--add-dir ${path} --verbose`)).toEqual([ + "--add-dir", + path, + "--verbose", + ]); + } }); it("ignores unescaped surrounding whitespace", () => { diff --git a/packages/shared/src/cliArgs.ts b/packages/shared/src/cliArgs.ts index 5b064aae8e3b..1e1d072b3bc5 100644 --- a/packages/shared/src/cliArgs.ts +++ b/packages/shared/src/cliArgs.ts @@ -43,7 +43,7 @@ export function tokenizeCliArgs(args?: string): ReadonlyArray { if (char === "'" || char === '"') { quote = char; quoted = true; - } else if (/\s/.test(char)) { + } else if (/[ \t\n\r\f\v]/.test(char)) { if (current || quoted) { tokens.push(current); current = ""; From b4dfd75624fade1a8c9596810016d0c33b8a5a4b Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 17 Nov 2026 08:23:29 -0800 Subject: [PATCH 056/133] fix(client-runtime): issues held by two environments list once (#38205) --- packages/client-runtime/src/issueList.test.ts | 69 +++++++++++++++++++ packages/client-runtime/src/issueList.ts | 4 ++ 2 files changed, 73 insertions(+) diff --git a/packages/client-runtime/src/issueList.test.ts b/packages/client-runtime/src/issueList.test.ts index 591c41087656..5085c10e5188 100644 --- a/packages/client-runtime/src/issueList.test.ts +++ b/packages/client-runtime/src/issueList.test.ts @@ -10,6 +10,7 @@ import { describe, expect, it } from "vite-plus/test"; import { continueIssuePage, + groupIssues, holdIssuePages, issueCursorsForHost, issueFilterScopes, @@ -153,3 +154,71 @@ describe("issueFilterScopes", () => { expect(issueFilterScopes(held, [])).toEqual([]); }); }); + +describe("groupIssues", () => { + it("lists an issue once when two environments hold the same repository", () => { + const github = { + tracker: "github", + host: "github.com", + projectCount: 1, + capabilities: { labels: true, assignees: true }, + configured: true, + detail: null, + } as IssueTrackerSummary; + const page = answer({ + trackers: [github], + entries: [entry({ key: "1" }), entry({ key: "2" })], + }); + const held = holdIssuePages( + [ + [environmentId, page], + [ + "env-2" as EnvironmentId, + answer({ + ...page, + entries: page.entries.map((row) => ({ ...row, projectId: "other" as ProjectId })), + }), + ], + ], + new Map(), + ); + const [group] = groupIssues(held, "", []); + expect(group!.rows.map((row) => row.displayKey)).toEqual(["#1", "#2"]); + }); + + it("keeps same-keyed issues from two Linear workspaces apart", () => { + const linear = { + tracker: "linear", + host: "linear.app", + projectCount: 1, + capabilities: { labels: true, assignees: true }, + configured: true, + detail: null, + } as IssueTrackerSummary; + const inWorkspace = (workspace: string) => + answer({ + trackers: [linear], + entries: [ + entry({ + tracker: "linear" as IssueTrackerKind, + host: "linear.app", + scope: "ENG", + key: "ENG-1", + url: `https://linear.app/${workspace}/issue/ENG-1`, + }), + ], + }); + const held = holdIssuePages( + [ + [environmentId, inWorkspace("acme")], + ["env-2" as EnvironmentId, inWorkspace("globex")], + ], + new Map(), + ); + const [group] = groupIssues(held, "", []); + expect(group!.rows.map((row) => row.url)).toEqual([ + "https://linear.app/acme/issue/ENG-1", + "https://linear.app/globex/issue/ENG-1", + ]); + }); +}); diff --git a/packages/client-runtime/src/issueList.ts b/packages/client-runtime/src/issueList.ts index 34d421231382..df0f80aae5c5 100644 --- a/packages/client-runtime/src/issueList.ts +++ b/packages/client-runtime/src/issueList.ts @@ -115,6 +115,7 @@ export function groupIssues( more: EnvironmentId[]; } >(); + const listed = new Set(); const needle = query.toLowerCase(); for (const [environmentId, page] of held) { for (const tracker of page.answer.trackers) { @@ -137,6 +138,9 @@ export function groupIssues( !entry.displayKey.toLowerCase().includes(needle) ) continue; + // Environments holding the same repository answer the same issue; the first one keeps it. + if (listed.has(entry.url)) continue; + listed.add(entry.url); group.rows.push({ ...entry, environmentId }); } for (const error of page.errors) { From 9b3b1c79a71ee564ed59b9937fbaefffb458473d Mon Sep 17 00:00:00 2001 From: Rajvardhan Patil Date: Tue, 17 Nov 2026 21:57:17 +0530 Subject: [PATCH 057/133] fix(client): a thread search that fails says so instead of "No results" (#38155) Co-authored-by: Rajvardhan Patil <243567420+RajvardhanPatil07@users.noreply.github.com> Co-authored-by: Julius Marminge --- apps/mobile/src/features/home/HomeScreen.tsx | 6 ++++++ .../src/features/keyboard/CommandPalette.tsx | 6 +++++- .../threads/ThreadNavigationSidebar.tsx | 4 +++- apps/mobile/src/state/queries.ts | 5 +++++ apps/web/src/components/CommandPalette.tsx | 5 ++++- .../components/CommandPaletteThreadItems.tsx | 1 + apps/web/src/components/Sidebar.tsx | 6 +++++- apps/web/src/state/queries.ts | 5 +++++ .../src/state/threadSearch.test.ts | 14 +++++++++++--- .../client-runtime/src/state/threadSearch.ts | 18 ++++++++++++++++-- 10 files changed, 61 insertions(+), 9 deletions(-) diff --git a/apps/mobile/src/features/home/HomeScreen.tsx b/apps/mobile/src/features/home/HomeScreen.tsx index c2946c59ed06..220082934614 100644 --- a/apps/mobile/src/features/home/HomeScreen.tsx +++ b/apps/mobile/src/features/home/HomeScreen.tsx @@ -707,6 +707,12 @@ export function HomeScreen(props: HomeScreenProps) { detail={`Looking for "${props.searchQuery}" in messages.`} variant={Platform.OS === "android" ? "plain" : undefined} /> + ) : hasSearchQuery && threadSearch.failed ? ( + ) : hasSearchQuery ? ( - {search.isPending ? "Searching…" : "No results"} + {search.isPending + ? "Searching…" + : search.failed + ? "Couldn't search messages" + : "No results"} } // Message results from slower environments may still arrive below. diff --git a/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx b/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx index 6de4c54d6d43..940cf885ece3 100644 --- a/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx +++ b/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx @@ -577,7 +577,9 @@ function ThreadNavigationSidebarPane(props: ThreadNavigationSidebarProps) { : props.searchQuery.trim().length > 0 ? threadSearch.isPending ? "Searching thread messages…" - : "No matching threads" + : threadSearch.failed + ? "Couldn't search thread messages" + : "No matching threads" : selectedProjectScope !== null ? `No threads in ${selectedProjectScope.title}` : "No threads yet"} diff --git a/apps/mobile/src/state/queries.ts b/apps/mobile/src/state/queries.ts index a84059d2e360..51a0dbbf04a6 100644 --- a/apps/mobile/src/state/queries.ts +++ b/apps/mobile/src/state/queries.ts @@ -60,6 +60,7 @@ const EMPTY_THREAD_SEARCH_MATCHES: ReadonlyArray = const EMPTY_THREAD_SEARCH_ATOM = Atom.make({ matches: EMPTY_THREAD_SEARCH_MATCHES, isLoading: false, + failed: false, rows: [], }).pipe(Atom.withLabel("mobile:thread-search:empty")); @@ -223,6 +224,8 @@ export function useThreadSearch( /** The query `matches` are for, which lags the typed one while a search runs. */ readonly query: string; readonly isPending: boolean; + /** No environment could run the search for the current query, so an empty result is not "no matches". */ + readonly failed: boolean; } { // A pasted wall of text searches by its start rather than failing the request. const normalizedQuery = query.trim().slice(0, THREAD_SEARCH_QUERY_MAX_LENGTH).trim(); @@ -241,6 +244,7 @@ export function useThreadSearch( searchKey === null ? EMPTY_THREAD_SEARCH_ATOM : threadSearch.results(searchKey), ); const isPending = canSearch && (normalizedQuery !== debouncedQuery || result.isLoading); + const failed = settledQuery !== null && !result.isLoading && result.failed; // What fast environments returned shows without waiting for a slow one; // callers keep shown rows in place with `nextShownOrder`. const ready = @@ -276,6 +280,7 @@ export function useThreadSearch( matches: visible.matches, query: visible.query, isPending, + failed, }; } diff --git a/apps/web/src/components/CommandPalette.tsx b/apps/web/src/components/CommandPalette.tsx index 0057fef1c596..ff0770444ff6 100644 --- a/apps/web/src/components/CommandPalette.tsx +++ b/apps/web/src/components/CommandPalette.tsx @@ -933,6 +933,7 @@ function OpenCommandPaletteDialog(props: { threadMessageItems, now: searchNow, isSearchPending: isThreadSearchPending, + isSearchFailed: isThreadSearchFailed, } = useCommandPaletteThreadItems({ activeThread: activeThread ?? null, threadSearchQuery }); // Recent means used recently: written in or opened, whichever is later. The // open thread would always lead that list, so it is left out. @@ -3103,7 +3104,9 @@ function OpenCommandPaletteDialog(props: { } : isThreadSearchPending ? { emptyStateMessage: "Searching thread messages…" } - : {})} + : isThreadSearchFailed + ? { emptyStateMessage: "Couldn't search thread messages." } + : {})} /> ); diff --git a/apps/web/src/components/CommandPaletteThreadItems.tsx b/apps/web/src/components/CommandPaletteThreadItems.tsx index 12a42e250f45..eab86ecbd002 100644 --- a/apps/web/src/components/CommandPaletteThreadItems.tsx +++ b/apps/web/src/components/CommandPaletteThreadItems.tsx @@ -249,5 +249,6 @@ export function useCommandPaletteThreadItems(input: { threadMessageItems, now, isSearchPending: messageSearch.isPending, + isSearchFailed: messageSearch.failed, }; } diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index e6cdb90d5c86..4a76a689fa21 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -3274,7 +3274,11 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve role="status" className="px-2 py-6 text-center text-xs text-sidebar-muted-foreground" > - {threadSearch.isPending ? "Searching thread messages…" : "No threads found"} + {threadSearch.isPending + ? "Searching thread messages…" + : threadSearch.failed + ? "Couldn't search thread messages" + : "No threads found"}

) ) : null} diff --git a/apps/web/src/state/queries.ts b/apps/web/src/state/queries.ts index 8afc9d7ba921..18276f93727f 100644 --- a/apps/web/src/state/queries.ts +++ b/apps/web/src/state/queries.ts @@ -60,6 +60,7 @@ const EMPTY_THREAD_SEARCH_MATCHES: ReadonlyArray = const EMPTY_THREAD_SEARCH_ATOM = Atom.make({ matches: EMPTY_THREAD_SEARCH_MATCHES, isLoading: false, + failed: false, rows: [], }).pipe(Atom.withLabel("web:thread-search:empty")); @@ -114,6 +115,8 @@ export function useThreadSearch( readonly matches: ReadonlyArray; readonly query: string; readonly isPending: boolean; + /** No environment could run the search for the current query, so an empty result is not "no matches". */ + readonly failed: boolean; } { // A pasted wall of text searches by its start rather than failing the request. const normalizedQuery = query.trim().slice(0, THREAD_SEARCH_QUERY_MAX_LENGTH).trim(); @@ -132,6 +135,7 @@ export function useThreadSearch( searchKey === null ? EMPTY_THREAD_SEARCH_ATOM : threadSearch.results(searchKey), ); const isPending = canSearch && (normalizedQuery !== debouncedQuery || result.isLoading); + const failed = settledQuery !== null && !result.isLoading && result.failed; // What fast environments returned shows without waiting for a slow one; // callers keep shown rows in place with `nextShownOrder`. const ready = @@ -167,6 +171,7 @@ export function useThreadSearch( matches: visible.matches, query: visible.query, isPending, + failed, }; } diff --git a/packages/client-runtime/src/state/threadSearch.test.ts b/packages/client-runtime/src/state/threadSearch.test.ts index d9f2cca584fb..ea0a4b748ec5 100644 --- a/packages/client-runtime/src/state/threadSearch.test.ts +++ b/packages/client-runtime/src/state/threadSearch.test.ts @@ -64,15 +64,15 @@ it("ignores invalid search keys", () => { const state = registry.get(searchAtom(makeThreadSearchKey([envA], "a".repeat(201)))); const malformedState = registry.get(searchAtom("not json{{")); - expect(state).toEqual({ matches: [], isLoading: false, rows: [] }); - expect(malformedState).toEqual({ matches: [], isLoading: false, rows: [] }); + expect(state).toEqual({ matches: [], isLoading: false, failed: false, rows: [] }); + expect(malformedState).toEqual({ matches: [], isLoading: false, failed: false, rows: [] }); expect(searchCount).toBe(0); } finally { registry.dispose(); } }); -it("merges successful environments and silently ignores failures", () => { +it("merges successful environments, and reports a failure only when none answered", () => { const result: OrchestrationSearchThreadsResult = { matches: [ { @@ -101,9 +101,17 @@ it("merges successful environments and silently ignores failures", () => { expect(state).toEqual({ matches: [{ ...result.matches[0], environmentId: envA }], isLoading: false, + failed: false, rows: [], }); expect(threadSearchMatchKey(state.matches[0]!)).toBe('["env-a","thread-a"]'); + // With no environment answering, an empty result must not read as "no matches". + expect(registry.get(searchAtom(makeThreadSearchKey([envB], "needle")))).toEqual({ + matches: [], + isLoading: false, + failed: true, + rows: [], + }); registry.dispose(); }); diff --git a/packages/client-runtime/src/state/threadSearch.ts b/packages/client-runtime/src/state/threadSearch.ts index 81ff06b0861e..82edcf32dfd6 100644 --- a/packages/client-runtime/src/state/threadSearch.ts +++ b/packages/client-runtime/src/state/threadSearch.ts @@ -52,6 +52,11 @@ export interface EnvironmentThreadSearchMatch extends OrchestrationThreadSearchM export interface ThreadSearchResultsState { readonly matches: ReadonlyArray; readonly isLoading: boolean; + /** + * Every environment asked failed to answer, so an empty result says nothing about matches. One + * environment failing beside another that answered still counts as an answer. + */ + readonly failed: boolean; /** Rows of matching older settled threads, which shells that omit them do not hold. */ readonly rows: ReadonlyArray<{ readonly environmentId: EnvironmentId; @@ -121,7 +126,7 @@ export function createThreadSearchResultsAtomFamily(options: { Atom.make((get): ThreadSearchResultsState => { const parsedKey = parseThreadSearchKey(key); if (Option.isNone(parsedKey)) { - return { matches: [], isLoading: false, rows: EMPTY_SEARCH_ROWS }; + return { matches: [], isLoading: false, failed: false, rows: EMPTY_SEARCH_ROWS }; } const [environmentIds, query, scope = {}] = parsedKey.value; @@ -131,6 +136,8 @@ export function createThreadSearchResultsAtomFamily(options: { const matches: EnvironmentThreadSearchMatch[] = []; const rows: Array = []; let isLoading = false; + let asked = 0; + let failures = 0; for (const environmentId of environmentIds) { const before = options.olderSettledBefore @@ -152,6 +159,8 @@ export function createThreadSearchResultsAtomFamily(options: { }), ); isLoading ||= result.waiting; + asked += 1; + if (AsyncResult.isFailure(result)) failures += 1; const value = AsyncResult.getOrElse(result, () => null); if (value !== null) { matches.push(...value.matches.map((match) => ({ ...match, environmentId }))); @@ -164,7 +173,12 @@ export function createThreadSearchResultsAtomFamily(options: { } } - return { matches, isLoading, rows: rows.length === 0 ? EMPTY_SEARCH_ROWS : rows }; + return { + matches, + isLoading, + failed: asked > 0 && failures === asked, + rows: rows.length === 0 ? EMPTY_SEARCH_ROWS : rows, + }; }).pipe(Atom.withLabel(`${options.labelPrefix}:${key}`)), ); const rowsAtom = Atom.family((rowsKey: string) => { From ddb14277ec9cb3e4fba4bcc5dd9ab941aee9d136 Mon Sep 17 00:00:00 2001 From: azhar Date: Tue, 17 Nov 2026 23:28:59 +0700 Subject: [PATCH 058/133] fix(server): a Claude goal no longer shows as set after the CLI drops it on an error (#38199) Co-authored-by: azhar Co-authored-by: Julius Marminge --- .../Adapters/ClaudeAdapterV2.test.ts | 57 +++++++++++++++++++ .../Adapters/ClaudeAdapterV2.ts | 8 +++ 2 files changed, 65 insertions(+) diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index 57ed889a6231..d0dda62b1ff2 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -24603,6 +24603,63 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ), ); + + it.effect("drops a goal the CLI clears after an unrecoverable error", () => + Effect.gen(function* () { + const harness = yield* makeWakeHarness; + const condition = "all tests pass"; + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: { + ...harness.providerThread, + goal: { objective: condition, status: "active", checks: 1 }, + }, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("goal-error-clear-attempt"), + text: "Continue.", + attachments: [], + }), + ); + yield* Queue.offerAll(harness.sdkMessages, [ + makeAssistantErrorFrame({ + uuid: "goal-error-clear-api-error", + error: "invalid_request", + text: "Prompt is too long", + }), + claudeSdkFrame({ + type: "system", + subtype: "informational", + content: `Goal cleared after an unrecoverable error (context limit reached): "${condition}". Run /goal again to continue.`, + level: "warning", + session_id: WAKE_NATIVE_SESSION, + uuid: "goal-error-clear-notice", + }), + makeResultFrame({ + uuid: "goal-error-clear-result", + result: "Prompt is too long", + isError: true, + terminalReason: "prompt_too_long", + }), + ]); + const terminal = yield* Queue.take(harness.terminalReceipts); + assert.equal(terminal.status, "failed"); + assert.isNull( + harness.events.findLast((event) => event.type === "provider_thread.updated") + ?.providerThread.goal, + ); + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); }); }); diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index 35db7f169159..edb8ef01301a 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -2546,6 +2546,14 @@ function nextClaudeGoal( current: OrchestrationV2ProviderGoal | null, message: SDKMessage, ): OrchestrationV2ProviderGoal | null | undefined { + // The CLI drops a goal on a context-limit, auth, or billing failure and reports it only here. + if ( + message.type === "system" && + message.subtype === "informational" && + message.content.startsWith("Goal cleared after an unrecoverable error (") + ) { + return null; + } if (message.type === "assistant") { if (message.parent_tool_use_id !== null || message.message.model !== "") { return undefined; From ffc5bbffb03d81330acfefed9bfdbc60c87b85b6 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Tue, 17 Nov 2026 17:30:33 +0100 Subject: [PATCH 059/133] fix(mobile): fully pushed feature branch offers Create PR (#38182) Co-authored-by: Grok 4.7 Co-authored-by: Julius Marminge --- packages/client-runtime/src/state/gitActions.test.ts | 10 ++++++++++ packages/client-runtime/src/state/gitActions.ts | 10 ++++++++++ 2 files changed, 20 insertions(+) diff --git a/packages/client-runtime/src/state/gitActions.test.ts b/packages/client-runtime/src/state/gitActions.test.ts index 3fa84580614e..7418ed0df172 100644 --- a/packages/client-runtime/src/state/gitActions.test.ts +++ b/packages/client-runtime/src/state/gitActions.test.ts @@ -78,6 +78,16 @@ describe("git action copy", () => { ).toBe("No local commits to include in an MR."); }); + it("offers creating a PR after the feature branch has been fully pushed", () => { + const pushed = status({ aheadCount: 0, behindCount: 0, aheadOfDefaultCount: 1 }); + expect(resolveQuickAction(pushed, false)).toMatchObject({ + disabled: false, + kind: "run_action", + action: "create_pr", + }); + expect(resolveQuickAction({ ...pushed, isDefaultRef: true }, false, true).disabled).toBe(true); + }); + it("names the host's change request in the default-branch dialog", () => { const input = { action: "commit_push_pr", branchName: "main", includesCommit: true } as const; expect( diff --git a/packages/client-runtime/src/state/gitActions.ts b/packages/client-runtime/src/state/gitActions.ts index fe5a2b77c4e6..a81f69d01c2f 100644 --- a/packages/client-runtime/src/state/gitActions.ts +++ b/packages/client-runtime/src/state/gitActions.ts @@ -138,6 +138,7 @@ export function resolveQuickAction( const hasChanges = gitStatus.hasWorkingTreeChanges; const hasOpenPr = gitStatus.pr?.state === "open"; const isAhead = gitStatus.aheadCount > 0; + const hasDefaultBranchDelta = (gitStatus.aheadOfDefaultCount ?? gitStatus.aheadCount) > 0; const isBehind = gitStatus.behindCount > 0; const isDiverged = isAhead && isBehind; const terminology = changeRequestTerminologyFor(gitStatus); @@ -243,6 +244,15 @@ export function resolveQuickAction( return { label: `View ${terminology.shortLabel}`, disabled: false, kind: "open_pr" }; } + if (hasDefaultBranchDelta && !isDefaultBranch) { + return { + label: `Create ${terminology.shortLabel}`, + disabled: false, + kind: "run_action", + action: "create_pr", + }; + } + return { label: "Commit", disabled: true, From 733821285cf706cae221e745fbaaafd93a1b9207 Mon Sep 17 00:00:00 2001 From: Simone Date: Tue, 17 Nov 2026 17:35:55 +0100 Subject: [PATCH 060/133] fix(ssh): read wildcard Includes in UTF-8 byte order (#38208) Co-authored-by: Simone <185146821+Lucenx9@users.noreply.github.com> Co-authored-by: Julius Marminge --- packages/ssh/src/config.test.ts | 10 ++++++++++ packages/ssh/src/config.ts | 7 ++++++- 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/packages/ssh/src/config.test.ts b/packages/ssh/src/config.test.ts index c3cafc968b75..459746c1e5be 100644 --- a/packages/ssh/src/config.test.ts +++ b/packages/ssh/src/config.test.ts @@ -98,6 +98,15 @@ describe("ssh config", () => { `Host unicode-${index}\n HostName unicode-${index}.example.com\n`, ); } + for (const [file, hostname] of [ + ["Z.conf", "first.example.com"], + ["🚀.conf", "second.example.com"], + ] as const) { + yield* fs.writeFileString( + path.join(sshDir, "config.d", file), + `Host ordered\n HostName ${hostname}\n`, + ); + } // OpenSSH's `?` matches one byte, so it never matches a multi-byte line separator. yield* fs.writeFileString( path.join(sshDir, "single.d", "team\u2028one.conf"), @@ -142,6 +151,7 @@ describe("ssh config", () => { ["enabled", "enabled.example.com", "ssh-config"], ["known.example.com", "known.example.com", "known-hosts"], ["literal", "literal.example.com", "ssh-config"], + ["ordered", "first.example.com", "ssh-config"], ["real", "real.example.com", "ssh-config"], ["single-ascii", "single-ascii.example.com", "ssh-config"], ["svc\u2028x", "correct.example.com", "ssh-config"], diff --git a/packages/ssh/src/config.ts b/packages/ssh/src/config.ts index 795aa529d1f7..9700d88ea5b4 100644 --- a/packages/ssh/src/config.ts +++ b/packages/ssh/src/config.ts @@ -147,7 +147,12 @@ const expandGlob = Effect.fnUntraced(function* ( } } } - return matchedPaths.toSorted(); + // OpenSSH's glob sorts matches by UTF-8 bytes, not UTF-16 code units. + return matchedPaths.toSorted((left, right) => { + const leftBytes = globBytes(left); + const rightBytes = globBytes(right); + return leftBytes < rightBytes ? -1 : leftBytes > rightBytes ? 1 : 0; + }); }); type HostCondition = ReadonlyArray | null; From c516061259d3591941d8437745a3116588b45e78 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 17 Nov 2026 08:40:19 -0800 Subject: [PATCH 061/133] fix(server): Forgejo PR lookup reads tea API pages over 1 MB (#38211) --- .../src/server/ForgejoCli.ts | 11 +++ .../ForgejoSourceControlProvider.test.ts | 95 +++++++++++++++++++ 2 files changed, 106 insertions(+) diff --git a/packages/source-control-forgejo/src/server/ForgejoCli.ts b/packages/source-control-forgejo/src/server/ForgejoCli.ts index 6a408b47550b..c94d96dd39eb 100644 --- a/packages/source-control-forgejo/src/server/ForgejoCli.ts +++ b/packages/source-control-forgejo/src/server/ForgejoCli.ts @@ -18,6 +18,9 @@ import * as SourceControlHost from "@t3tools/source-control-core/server/SourceCo import { collectUint8StreamText } from "@t3tools/provider-core/server/collectStreamText"; import type { SourceControlProviderContext } from "@t3tools/source-control-core/server/SourceControlProvider"; +// A Gitea list page can hold 50 pull request bodies; tea's output is otherwise capped at 1 MB. +const API_MAX_OUTPUT_BYTES = 16 * 1024 * 1024; + const encodeApiBody = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown)); export class ForgejoCliError extends Schema.TaggedError()("ForgejoCliError", { @@ -731,6 +734,7 @@ export const make = Effect.gen(function* () { `${repository.baseUrl}/api/v1/${path}`, ], ...(stdin === undefined ? {} : { stdin }), + maxOutputBytes: API_MAX_OUTPUT_BYTES, }); // tea reports HTTP failures with exit code zero; use its response status. const status = Number(/^HTTP\/\S+ (\d{3})/m.exec(result.stderr)?.[1]); @@ -763,6 +767,13 @@ export const make = Effect.gen(function* () { : `Forgejo API request failed (HTTP ${status}).`, }); } + if (result.stdoutTruncated) + return yield* new ForgejoCliError({ + command: "tea", + cwd: input.cwd, + reason: "invalid-response", + detail: "Forgejo API response exceeded the output size limit.", + }); return result; }); return ForgejoCli.of({ execute, listLogins, getAccount, resolveRepository, api }); diff --git a/packages/source-control-forgejo/src/server/ForgejoSourceControlProvider.test.ts b/packages/source-control-forgejo/src/server/ForgejoSourceControlProvider.test.ts index 76137928af06..1768dbdc2a76 100644 --- a/packages/source-control-forgejo/src/server/ForgejoSourceControlProvider.test.ts +++ b/packages/source-control-forgejo/src/server/ForgejoSourceControlProvider.test.ts @@ -1124,6 +1124,101 @@ it.effect("reads only the changed front of a Gitea pull request list it has read ); }); +it.effect( + "finds a branch's pull request on Gitea when a page of the full list exceeds 1 MB", + () => { + const repo = { full_name: "maria/project", owner: { login: "maria" } }; + const pull = (number: number, head: string, body: string) => ({ + number, + title: `PR ${number}`, + body, + html_url: `http://forgejo.local:3000/maria/project/pulls/${number}`, + state: "closed", + merged: true, + updated_at: `2026-10-12T00:00:0${number}Z`, + base: { ref: "main", label: "main", sha: "base", repo }, + head: { ref: head, label: head, sha: "h", repo }, + }); + const pulls = [pull(2, "renovate", "x".repeat(999_993)), pull(1, "feature", "small")]; + return Effect.gen(function* () { + const provider = yield* ForgejoSourceControlProvider.make; + const found = yield* provider.listChangeRequests({ + cwd: "/repo", + context: { + provider: { + kind: SourceControlProviderKind.make("forgejo"), + name: "Forgejo", + baseUrl: "http://forgejo.local:3000", + }, + remoteName: "origin", + remoteUrl: "http://forgejo.local:3000/maria/project.git", + }, + headSelector: "feature", + state: "all", + }); + assert.deepStrictEqual( + found.map((item) => item.number), + [1], + ); + }).pipe( + Effect.provide( + ForgejoCli.layer.pipe( + Layer.provideMerge( + Layer.mergeAll( + Layer.succeed( + FileSystem.FileSystem, + FileSystem.makeNoop({ exists: () => Effect.succeed(false) }), + ), + Layer.succeed( + HttpClient.HttpClient, + HttpClient.make(() => { + throw new Error("tea must handle its own HTTP request"); + }), + ), + TestSourceControlHost.layer({ + process: { + run: (input) => { + if (input.args[0] === "login") + return Effect.succeed( + processOutput( + encodeJson([ + { + name: "work", + url: "http://forgejo.local:3000", + ssh_host: "forgejo.local", + user: "maria", + default: "true", + }, + ]), + ), + ); + const url = new URL(input.args.at(-1) ?? ""); + const number = /\/pulls\/(\d+)$/.exec(url.pathname)?.[1]; + // Gitea ignores `head=`, so every list page holds every pull request. + const stdout = encodeJson( + number + ? pulls.find((item) => item.number === Number(number)) + : url.searchParams.get("page") === "1" + ? pulls + : [], + ); + // VcsProcess truncates at 1,000,000 bytes unless a caller raises the cap. + const maxBytes = input.maxOutputBytes ?? 1_000_000; + return Effect.succeed({ + ...processOutput(stdout.slice(0, maxBytes), { stderr: "HTTP/1.1 200 OK\n" }), + stdoutTruncated: stdout.length > maxBytes, + }); + }, + }, + }), + ), + ), + ), + ), + ); + }, +); + it.effect("finds a merged Forgejo pull request whose head branch was deleted", () => Effect.gen(function* () { const provider = yield* ForgejoSourceControlProvider.make; From 705c7f2479d7087393f3030578162470a9583729 Mon Sep 17 00:00:00 2001 From: Vincent Guillebaud Date: Tue, 17 Nov 2026 17:44:22 +0100 Subject: [PATCH 062/133] fix(mobile): bottom of Git panel lists clears the Android nav bar (#38176) Co-authored-by: Julius Marminge --- .../src/features/cloud/ConnectOnboardingRouteScreen.tsx | 2 +- .../src/features/connection/ConnectionsNewRouteScreen.tsx | 2 +- apps/mobile/src/features/threads/git/GitOverviewSheet.tsx | 7 +++++-- 3 files changed, 7 insertions(+), 4 deletions(-) diff --git a/apps/mobile/src/features/cloud/ConnectOnboardingRouteScreen.tsx b/apps/mobile/src/features/cloud/ConnectOnboardingRouteScreen.tsx index 3913eaa47557..db5cf357a900 100644 --- a/apps/mobile/src/features/cloud/ConnectOnboardingRouteScreen.tsx +++ b/apps/mobile/src/features/cloud/ConnectOnboardingRouteScreen.tsx @@ -74,11 +74,11 @@ function ConfiguredConnectOnboardingRouteScreen() { contentInsetAdjustmentBehavior="automatic" showsVerticalScrollIndicator={false} className="flex-1" - contentInset={{ bottom: Math.max(insets.bottom, 18) + 18 }} contentContainerStyle={{ gap: 16, paddingHorizontal: 20, paddingTop: 16, + paddingBottom: Math.max(insets.bottom, 18) + 18, }} refreshControl={} > diff --git a/apps/mobile/src/features/connection/ConnectionsNewRouteScreen.tsx b/apps/mobile/src/features/connection/ConnectionsNewRouteScreen.tsx index c76c79896d10..44d2da810ca1 100644 --- a/apps/mobile/src/features/connection/ConnectionsNewRouteScreen.tsx +++ b/apps/mobile/src/features/connection/ConnectionsNewRouteScreen.tsx @@ -202,10 +202,10 @@ function PairingForm({ keyboardShouldPersistTaps="handled" showsVerticalScrollIndicator={false} className="flex-1" - contentInset={{ bottom: Math.max(insets.bottom, 18) + 18 }} contentContainerStyle={{ paddingHorizontal: 16, paddingTop: 4, + paddingBottom: Math.max(insets.bottom, 18) + 18, }} > diff --git a/apps/mobile/src/features/threads/git/GitOverviewSheet.tsx b/apps/mobile/src/features/threads/git/GitOverviewSheet.tsx index c3a591f50ef4..425b4353dec1 100644 --- a/apps/mobile/src/features/threads/git/GitOverviewSheet.tsx +++ b/apps/mobile/src/features/threads/git/GitOverviewSheet.tsx @@ -235,8 +235,11 @@ function GitOverviewSheetContent(props: GitOverviewSheetProps) { className="flex-1 bg-screen" contentInsetAdjustmentBehavior="automatic" showsVerticalScrollIndicator={false} - contentInset={{ bottom: Math.max(insets.bottom, 18) + 18 }} - contentContainerStyle={{ ...groupedListInsets(isInspector), paddingTop: 8 }} + contentContainerStyle={{ + ...groupedListInsets(isInspector), + paddingTop: 8, + paddingBottom: Math.max(insets.bottom, 18) + 18, + }} refreshControl={ void handleRefresh()} /> } From a99faf5a629023a5aca16fc8422553a5a4a9067f Mon Sep 17 00:00:00 2001 From: Yash Singh Date: Tue, 17 Nov 2026 10:48:29 -0600 Subject: [PATCH 063/133] feat(antigravity): edit earlier messages with Edit from here (#38227) Co-authored-by: Cursor --- .../NativeChildWorkQuery.test.ts | 33 +++++++++++++++---- .../orchestration-v2/NativeChildWorkQuery.ts | 15 +++++++-- .../src/provider/AntigravityProvider.test.ts | 2 +- .../src/provider/AntigravityProvider.ts | 2 +- docs/user/providers-antigravity.md | 7 ++-- 5 files changed, 45 insertions(+), 14 deletions(-) diff --git a/apps/server/src/orchestration-v2/NativeChildWorkQuery.test.ts b/apps/server/src/orchestration-v2/NativeChildWorkQuery.test.ts index b2beb334667a..1b7c95336629 100644 --- a/apps/server/src/orchestration-v2/NativeChildWorkQuery.test.ts +++ b/apps/server/src/orchestration-v2/NativeChildWorkQuery.test.ts @@ -26,7 +26,8 @@ const childThreadId = ThreadId.make("thread-child"); const launch = describeAntigravitySubagentLaunches([LAUNCH]); // A permission-prompt batch in session ROOT, plus an older batch with no launch text in `olderRun`. -const records = (olderRun: string) => ({ +// `rootThreadSession` is where the root provider thread points now; a rollback moves it. +const records = (olderRun: string, rootThreadSession: string) => ({ thread: { id: childThreadId, creationSource: "provider", @@ -57,12 +58,24 @@ const records = (olderRun: string) => ({ }, ], runs: [ - { id: "run-root", providerThreadId: "provider-root" }, - { id: "run-root-earlier", providerThreadId: "provider-root" }, - { id: "run-other", providerThreadId: "provider-other" }, + { id: "run-root", providerThreadId: "provider-root", activeAttemptId: "attempt-root" }, + { + id: "run-root-earlier", + providerThreadId: "provider-root", + activeAttemptId: "attempt-root-earlier", + }, + { id: "run-other", providerThreadId: "provider-other", activeAttemptId: null }, + ], + attempts: [ + { id: "attempt-root", nativeThreadId: ROOT }, + { id: "attempt-root-earlier", nativeThreadId: ROOT }, ], providerThreads: [ - { id: "provider-root", providerInstanceId: instanceId, nativeThreadRef: { nativeId: ROOT } }, + { + id: "provider-root", + providerInstanceId: instanceId, + nativeThreadRef: { nativeId: rootThreadSession }, + }, { id: "provider-other", providerInstanceId: instanceId, @@ -71,7 +84,7 @@ const records = (olderRun: string) => ({ ], }); -const readChildren = (olderRun: string) => +const readChildren = (olderRun: string, rootThreadSession = ROOT) => Effect.gen(function* () { const query = yield* NativeChildWorkQuery.NativeChildWorkQuery; return (yield* query.getNativeChildWork({ threadId: childThreadId })).children; @@ -80,7 +93,7 @@ const readChildren = (olderRun: string) => NativeChildWorkQuery.layer.pipe( Layer.provide( Layer.mock(ThreadManagement.ThreadManagementService)({ - getThreadRecords: () => Effect.succeed(records(olderRun) as never), + getThreadRecords: () => Effect.succeed(records(olderRun, rootThreadSession) as never), }), ), ), @@ -114,6 +127,12 @@ it.layer( expect(fromOtherSession.map((child) => child.conversationId)).toEqual([CHILD]); // An earlier run in the same session may own the only record. expect(yield* readChildren("run-root-earlier")).toEqual([]); + // After a rollback, kept batches still read the session they ran in. + const rolledBack = "1a7f8b0c-3c55-4c1e-9a43-5d0e2b6f9c11"; + expect( + (yield* readChildren("run-other", rolledBack)).map((child) => child.conversationId), + ).toEqual([CHILD]); + expect(yield* readChildren("run-root-earlier", rolledBack)).toEqual([]); }), ); }); diff --git a/apps/server/src/orchestration-v2/NativeChildWorkQuery.ts b/apps/server/src/orchestration-v2/NativeChildWorkQuery.ts index 4bc7849dc698..389ae6c40827 100644 --- a/apps/server/src/orchestration-v2/NativeChildWorkQuery.ts +++ b/apps/server/src/orchestration-v2/NativeChildWorkQuery.ts @@ -73,12 +73,23 @@ const make = Effect.gen(function* () { ["runs", "providerThreads"], { runIds: [subagent.runId, ...others.flatMap((other) => other.runId ?? [])] }, ); + const { attempts } = yield* threads.getThreadRecords(parentThreadId, ["attempts"], { + attemptIds: runs.flatMap((run) => run.activeAttemptId ?? []), + }); const providerThreadOf = (runId: string | null) => { const providerThreadId = runs.find((run) => run.id === runId)?.providerThreadId; return providerThreads.find((candidate) => candidate.id === providerThreadId); }; + // Rollback moves the provider thread to a fresh session; a batch's records stay where it ran. + const sessionOf = (runId: string | null) => { + const attemptId = runs.find((run) => run.id === runId)?.activeAttemptId; + return ( + attempts.find((attempt) => attempt.id === attemptId)?.nativeThreadId ?? + providerThreadOf(runId)?.nativeThreadRef?.nativeId + ); + }; const providerThread = providerThreadOf(subagent.runId); - const rootSessionId = providerThread?.nativeThreadRef?.nativeId; + const rootSessionId = sessionOf(subagent.runId); if (!rootSessionId || providerThread?.providerInstanceId !== subagent.providerInstanceId) { return NO_CHILDREN; } @@ -94,7 +105,7 @@ const make = Effect.gen(function* () { // Only batches from the same agent session can share its records. siblings: others.flatMap((other) => { const id = other.nativeTaskRef?.nativeId; - return id && providerThreadOf(other.runId)?.nativeThreadRef?.nativeId === rootSessionId + return id && sessionOf(other.runId) === rootSessionId ? [{ nativeTaskId: id, title: other.title, prompt: other.prompt }] : []; }), diff --git a/apps/server/src/provider/AntigravityProvider.test.ts b/apps/server/src/provider/AntigravityProvider.test.ts index a67627382785..9612fb535ddd 100644 --- a/apps/server/src/provider/AntigravityProvider.test.ts +++ b/apps/server/src/provider/AntigravityProvider.test.ts @@ -302,7 +302,7 @@ it.layer(layerTest)("Antigravity provider snapshots", (it) => { models: [], setup: { canAuthenticate: true, canInstall: true }, showInteractionModeToggle: false, - supportsConversationRollback: false, + supportsConversationRollback: true, supportsTextGeneration: false, }); expect(yield* Ref.get(harness.probeCalls)).toBe(0); diff --git a/apps/server/src/provider/AntigravityProvider.ts b/apps/server/src/provider/AntigravityProvider.ts index b140c7511ca1..7510106f2c5d 100644 --- a/apps/server/src/provider/AntigravityProvider.ts +++ b/apps/server/src/provider/AntigravityProvider.ts @@ -204,7 +204,7 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func }, }), setup: { canAuthenticate: true, canInstall: true }, - supportsConversationRollback: false, + supportsConversationRollback: true, supportsTextGeneration: false, workspaceSnapshots: [], } satisfies ServerProviderDraft; diff --git a/docs/user/providers-antigravity.md b/docs/user/providers-antigravity.md index 8a284a11e782..c62cc56b310d 100644 --- a/docs/user/providers-antigravity.md +++ b/docs/user/providers-antigravity.md @@ -90,9 +90,10 @@ Use Antigravity's native `/plan` command for planning. Tool approvals follow [Pe Questions with fixed choices still need one of the offered answers, even in **Full access**. -T3 Code keeps conversation history and file diffs, but Antigravity cannot rewind -its conversation. Reverting a thread or editing and resubmitting an earlier turn -is unavailable. Continue with a follow-up message or start a new thread. +On web and desktop, [Edit from here](./composer.md#edit-an-earlier-prompt) works with +Antigravity. Antigravity cannot rewind its own conversation, so the next turn +starts a fresh Antigravity session and T3 Code sends it the kept conversation, +without the turns you removed. Manual context compaction is unavailable through Antigravity's ACP runtime, even though its CLI has `/compact`. Send `/clear` when you need a fresh context. From 3fdd9fc80ccbffabb36c53e893679dbce1a2b162 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Tue, 17 Nov 2026 18:19:39 +0100 Subject: [PATCH 064/133] fix(mobile): settings filter keeps a selected environment while it is disconnected (#38196) Co-authored-by: Grok 4.7 Co-authored-by: Julius Marminge --- .../settings-environment-filter.logic.test.ts | 46 +++++++++++++++++++ .../settings-environment-filter.logic.ts | 16 ++++--- .../settings/settings-environment-filter.tsx | 3 +- 3 files changed, 58 insertions(+), 7 deletions(-) create mode 100644 apps/mobile/src/features/settings/settings-environment-filter.logic.test.ts diff --git a/apps/mobile/src/features/settings/settings-environment-filter.logic.test.ts b/apps/mobile/src/features/settings/settings-environment-filter.logic.test.ts new file mode 100644 index 000000000000..8b22892dd6c3 --- /dev/null +++ b/apps/mobile/src/features/settings/settings-environment-filter.logic.test.ts @@ -0,0 +1,46 @@ +import { EnvironmentId } from "@t3tools/contracts"; +import { describe, expect, it } from "vite-plus/test"; + +import { toggleSettingsEnvironment } from "./settings-environment-filter.logic"; + +describe("settings selection across disconnected environments", () => { + const a = EnvironmentId.make("a"); + const b = EnvironmentId.make("b"); + const c = EnvironmentId.make("c"); + const d = EnvironmentId.make("d"); + const all = [a, b, c, d].map((environmentId) => ({ environmentId })); + const connected = all.filter((entry) => entry.environmentId !== b); + + it.each([ + { + name: "keeps offline environments selected from All", + selected: null, + toggles: [c], + expected: [a, b, d], + }, + { + name: "keeps offline environments deselected after toggling off and on", + selected: new Set([a, c, d]), + toggles: [c, c], + expected: [a, c, d], + }, + { + name: "ignores toggles of offline environments", + selected: new Set([a]), + toggles: [b], + expected: [a], + }, + { + name: "returns to All when every known environment is selected", + selected: new Set([a, b, d]), + toggles: [c], + expected: null, + }, + ])("$name", ({ selected, toggles, expected }) => { + let next: ReadonlySet | null = selected; + for (const id of toggles) { + next = toggleSettingsEnvironment(next, connected, id, all); + } + expect(next).toEqual(expected === null ? null : new Set(expected)); + }); +}); diff --git a/apps/mobile/src/features/settings/settings-environment-filter.logic.ts b/apps/mobile/src/features/settings/settings-environment-filter.logic.ts index 4186d249783f..b6db9e55df02 100644 --- a/apps/mobile/src/features/settings/settings-environment-filter.logic.ts +++ b/apps/mobile/src/features/settings/settings-environment-filter.logic.ts @@ -1,16 +1,20 @@ import type { EnvironmentId } from "@t3tools/contracts"; +/** + * Toggles one connected environment in the Settings scope. `null` means every environment. + * Known offline environments keep their selection when they reconnect. + */ export function toggleSettingsEnvironment( selected: ReadonlySet | null, available: readonly { readonly environmentId: EnvironmentId }[], toggledId: EnvironmentId, + known: readonly { readonly environmentId: EnvironmentId }[] = available, ): ReadonlySet | null { - const ids = available.map((entry) => entry.environmentId); - const next = new Set(ids.filter((id) => selected === null || selected.has(id))); - if (ids.includes(toggledId)) { - if (next.has(toggledId)) next.delete(toggledId); - else next.add(toggledId); - } + if (!available.some((entry) => entry.environmentId === toggledId)) return selected; + const ids = known.map((entry) => entry.environmentId); + const next = new Set(selected ?? ids); + if (next.has(toggledId)) next.delete(toggledId); + else next.add(toggledId); return ids.every((id) => next.has(id)) ? null : next; } diff --git a/apps/mobile/src/features/settings/settings-environment-filter.tsx b/apps/mobile/src/features/settings/settings-environment-filter.tsx index 2d75625dedee..c9a4b96f58a7 100644 --- a/apps/mobile/src/features/settings/settings-environment-filter.tsx +++ b/apps/mobile/src/features/settings/settings-environment-filter.tsx @@ -146,10 +146,11 @@ export function useSettingsEnvironmentFilter() { selectAll: () => setSelectedIds(null), toggleEnvironment: (environmentId: EnvironmentId) => setSelectedIds((current) => - toggleSettingsEnvironment(current, availableTargets, environmentId), + toggleSettingsEnvironment(current, availableTargets, environmentId, environments), ), }), [ + environments, availableTargets, selectedTargets, selectedIds, From 0597532f16d54189c4a696a249cc66c6d44c7ab5 Mon Sep 17 00:00:00 2001 From: VendettaGhub <73823502+VendettaGhub@users.noreply.github.com> Date: Tue, 17 Nov 2026 18:21:33 +0100 Subject: [PATCH 065/133] fix(server): queue a provider switch sent while a Claude turn runs (#38216) Co-authored-by: Hannes Lenz Co-authored-by: Julius Marminge --- .../src/orchestration-v2/CommandPolicy.ts | 17 +- .../src/orchestration-v2/Orchestrator.ts | 26 ++ .../ProviderSwitch.integration.test.ts | 278 ++++++++++++++++++ 3 files changed, 316 insertions(+), 5 deletions(-) diff --git a/apps/server/src/orchestration-v2/CommandPolicy.ts b/apps/server/src/orchestration-v2/CommandPolicy.ts index 69c5497d3b87..c49d229949a7 100644 --- a/apps/server/src/orchestration-v2/CommandPolicy.ts +++ b/apps/server/src/orchestration-v2/CommandPolicy.ts @@ -108,10 +108,7 @@ export function resolveMessageDispatchIntent( target === undefined || !isActiveRun(target) ? undefined : providerTurnCapabilities(projection, target); - return turns !== undefined && - !turns.supportsActiveSteering && - !(turns.supportsInterrupt && turns.supportsSteeringByInterruptRestart) && - turns.supportsQueuedMessages + return turns !== undefined && !turns.supportsActiveSteering && providerSwitchWaitsForTurn(turns) ? { type: "queue_after_active" } : mode; } @@ -135,7 +132,17 @@ export function followUpOwnerRun( ); } -function providerTurnCapabilities( +/** A provider that cannot restart its turn for new input runs a provider switch after the turn. */ +export function providerSwitchWaitsForTurn( + turns: OrchestrationV2ProviderCapabilities["turns"], +): boolean { + return ( + turns.supportsQueuedMessages && + !(turns.supportsInterrupt && turns.supportsSteeringByInterruptRestart) + ); +} + +export function providerTurnCapabilities( projection: OrchestrationV2ThreadProjection, run: OrchestrationV2Run, ) { diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 933676e23d99..7d1248cebd41 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -117,6 +117,8 @@ import { goalCommandStopsActiveRun, isActiveRun, isNativeMaintenanceCommand, + providerSwitchWaitsForTurn, + providerTurnCapabilities, resolveMessageDispatchIntent, } from "./CommandPolicy.ts"; import { CommandReceiptStoreV2, type CommandReceiptV2 } from "./CommandReceiptStore.ts"; @@ -7239,6 +7241,30 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio taskIds: delivery.taskIds, }; } + // A steer that switches provider needs a new turn. A provider that cannot restart its + // turn for new input takes it after the turn, like a provider that cannot steer at all. + // An explicit steer that Stop reached still fails below. + if (dispatchMode.type === "steer_active" && command.modelSelection !== undefined) { + const targetRunId = dispatchMode.targetRunId; + const target = projection.runs.find((run) => run.id === targetRunId); + if ( + target !== undefined && + isActiveRun(target) && + target.providerInstanceId !== command.modelSelection.instanceId && + !(yield* stopReachedRun(command, command.threadId, target.id)) + ) { + // Before the provider session starts, the adapter's capabilities stand in for its own. + const turns = + providerTurnCapabilities(projection, target) ?? + (yield* providerAdapters.get(target.providerInstanceId).pipe( + Effect.flatMap((adapter) => adapter.getCapabilities()), + mapDispatchError(command), + )).turns; + if (providerSwitchWaitsForTurn(turns)) { + dispatchMode = { type: "queue_after_active" }; + } + } + } // A provider that can stop a turn but not restart it with new input runs a // restart as the next turn: first in the queue, with the running turn stopped. if (dispatchMode.type === "restart_active" && !isNativeMaintenanceCommand(command)) { diff --git a/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts b/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts index 7aa0a1a2631f..e1b2572d8d1a 100644 --- a/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts +++ b/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts @@ -123,6 +123,7 @@ function makeTestAdapter(input: { readonly subagentOnlyBackgroundWork?: boolean; readonly holdFirstTurn?: Deferred.Deferred; readonly releaseFirstTurn?: Deferred.Deferred; + readonly holdOpenSession?: Deferred.Deferred; /** A tool call the held turn reports running before it holds. */ readonly heldRunningToolCall?: { readonly id: TurnItemId; @@ -141,6 +142,7 @@ function makeTestAdapter(input: { planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" }), openSession: (sessionInput) => Effect.gen(function* () { + if (input.holdOpenSession !== undefined) yield* Deferred.await(input.holdOpenSession); const events = yield* PubSub.unbounded(); if (input.closedSessions !== undefined) { const closedSessions = input.closedSessions; @@ -2497,6 +2499,282 @@ describe("orchestration v2 provider switching", () => { }), ); + const steerProviderSwitchHarness = Effect.fn("steerProviderSwitchHarness")(function* ( + key: string, + holdOpenSession?: Deferred.Deferred, + ) { + const cwd = yield* checkpointWorkspace(`steer-provider-switch-${key}`); + const capturedTurns = yield* Ref.make>([]); + const started = yield* Deferred.make(); + const release = yield* Deferred.make(); + const threadId = ThreadId.make(`thread:steer-provider-switch:${key}`); + const layerRegistry = ProviderAdapterRegistry.layerFromAdapters([ + makeTestAdapter({ + instanceId: CLAUDE_MODEL_SELECTION.instanceId, + driver: CLAUDE_DRIVER, + capabilities: ClaudeProviderCapabilitiesV2, + modelSelection: CLAUDE_MODEL_SELECTION, + responseByRunOrdinal: { 1: "Claude finished the current turn" }, + capturedTurns, + holdFirstTurn: started, + releaseFirstTurn: release, + ...(holdOpenSession === undefined ? {} : { holdOpenSession }), + }), + makeTestAdapter({ + instanceId: CODEX_MODEL_SELECTION.instanceId, + driver: CODEX_DRIVER, + capabilities: CodexProviderCapabilitiesV2, + modelSelection: CODEX_MODEL_SELECTION, + responseByRunOrdinal: { 2: "Codex continued" }, + capturedTurns, + }), + ]); + const layer = ProviderReplayHarness.layerWithRegistry( + { + name: `steer-provider-switch-${key}`, + runtimePolicyOverride: { + cwd, + approvalPolicy: "never", + sandboxPolicy: { + type: "readOnly", + access: { type: "fullAccess" }, + networkAccess: false, + }, + }, + }, + layerRegistry, + ); + const startClaudeTurn = Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + yield* orchestrator.dispatch({ + type: "thread.create", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make(`command:steer-provider-switch:${key}:create`), + threadId, + projectId: ProjectId.make(`project:steer-provider-switch:${key}`), + title: "Steer provider switch", + modelSelection: CLAUDE_MODEL_SELECTION, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: cwd, + }); + yield* orchestrator.dispatch({ + type: "message.dispatch", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make(`command:steer-provider-switch:${key}:first`), + threadId, + messageId: MessageId.make(`message:steer-provider-switch:${key}:first`), + text: "Current Claude turn", + attachments: [], + modelSelection: CLAUDE_MODEL_SELECTION, + dispatchMode: { type: "start_immediately" }, + }); + }); + const markClaudeTurnRunning = Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const eventSink = yield* EventSink.EventSinkV2; + const [claudeRun] = (yield* orchestrator.getThreadProjection(threadId)).runs; + const now = yield* DateTime.now; + yield* eventSink.write({ + events: [ + { + id: EventId.make(`event:steer-provider-switch:${key}:first-turn-running`), + type: "provider-turn.updated", + threadId, + runId: claudeRun!.id, + nodeId: claudeRun!.rootNodeId!, + driver: CLAUDE_DRIVER, + providerInstanceId: CLAUDE_MODEL_SELECTION.instanceId, + occurredAt: now, + payload: { + // The adapter's own turn id, so its completion ends this turn. + id: ProviderTurnId.make(`provider-turn:${CLAUDE_DRIVER}:${threadId}:1`), + providerThreadId: claudeRun!.providerThreadId!, + nodeId: claudeRun!.rootNodeId!, + runAttemptId: claudeRun!.activeAttemptId!, + nativeTurnRef: null, + ordinal: 1, + status: "running", + startedAt: now, + completedAt: null, + }, + }, + ], + }); + }); + const steerToCodex = Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + return yield* orchestrator.dispatch({ + type: "message.dispatch", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make(`command:steer-provider-switch:${key}:codex`), + threadId, + messageId: MessageId.make(`message:steer-provider-switch:${key}:codex`), + text: "Continue with Codex", + attachments: [], + modelSelection: CODEX_MODEL_SELECTION, + deliveryIntent: "steer", + dispatchMode: { type: "start_immediately" }, + }); + }); + return { + threadId, + started, + release, + capturedTurns, + layer, + startClaudeTurn, + markClaudeTurnRunning, + steerToCodex, + }; + }); + + it.live.each(["is running", "has no provider session yet"] as const)( + "runs a provider switch steered into a Claude turn that %s after that turn", + (phase) => + Effect.gen(function* () { + const sessionGate = yield* Deferred.make(); + if (phase === "is running") yield* Deferred.succeed(sessionGate, undefined); + const harness = yield* steerProviderSwitchHarness( + phase === "is running" ? "running" : "before-session", + sessionGate, + ); + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const waitForRun = (ordinal: number) => + orchestrator.streamStoredEvents.pipe( + Stream.filter( + ({ event }) => + event.type === "run.updated" && + event.threadId === harness.threadId && + event.payload.ordinal === ordinal && + event.payload.status === "completed", + ), + Stream.runHead, + Effect.andThen(worker.drain()), + ); + yield* harness.startClaudeTurn; + if (phase === "is running") { + yield* Deferred.await(harness.started); + yield* worker.drain(); + yield* harness.markClaudeTurnRunning; + } else { + const beforeSession = yield* orchestrator.getThreadProjection(harness.threadId); + assert.include(["preparing", "starting"], beforeSession.runs[0]?.status); + assert.lengthOf(beforeSession.providerSessions, 0); + } + // Claude cannot restart its turn for new input, so the switch waits for the turn. + yield* harness.steerToCodex; + const queued = (yield* orchestrator.getThreadProjection(harness.threadId)).runs.at(-1); + assert.equal(queued?.status, "queued"); + assert.equal(queued?.providerInstanceId, CODEX_MODEL_SELECTION.instanceId); + assert.isUndefined(queued?.steerWhenReadyRunId); + + yield* Deferred.succeed(sessionGate, undefined); + yield* Deferred.await(harness.started); + yield* Deferred.succeed(harness.release, undefined); + yield* waitForRun(1); + yield* waitForRun(2); + const projection = yield* orchestrator.getThreadProjection(harness.threadId); + assert.deepEqual( + projection.runs.map((run) => [run.status, run.providerInstanceId]), + [ + ["completed", CLAUDE_MODEL_SELECTION.instanceId], + ["completed", CODEX_MODEL_SELECTION.instanceId], + ], + ); + assert.deepEqual(projection.thread.modelSelection, CODEX_MODEL_SELECTION); + const handoff = projection.contextHandoffs.find( + (candidate) => candidate.id === projection.runs[1]?.contextHandoffId, + ); + assert.isDefined(handoff); + const codexTurn = (yield* Ref.get(harness.capturedTurns)).at(-1)!; + assert.include(codexTurn.text, "Continue with Codex"); + assert.include(codexTurn.text, "Current Claude turn"); + assert.include(codexTurn.text, "Claude finished the current turn"); + }).pipe(Effect.provide(harness.layer)); + }), + ); + + it.live("stops a Claude turn for a /goal steered into it with another provider", () => + Effect.gen(function* () { + const harness = yield* steerProviderSwitchHarness("goal"); + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + yield* harness.startClaudeTurn; + yield* Deferred.await(harness.started); + yield* worker.drain(); + yield* harness.markClaudeTurnRunning; + const [claudeRun] = (yield* orchestrator.getThreadProjection(harness.threadId)).runs; + // An explicit steer without a delivery intent, as thread tools send it. + yield* orchestrator.dispatch({ + type: "message.dispatch", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make("command:steer-provider-switch:goal:codex"), + threadId: harness.threadId, + messageId: MessageId.make("message:steer-provider-switch:goal:codex"), + text: "/goal all tests pass", + attachments: [], + modelSelection: CODEX_MODEL_SELECTION, + dispatchMode: { type: "steer_active", targetRunId: claudeRun!.id }, + }); + const projection = yield* orchestrator.getThreadProjection(harness.threadId); + assert.isTrue( + projection.turnItems.some( + (item) => item.type === "run_interrupt_request" && item.runId === claudeRun!.id, + ), + ); + assert.deepEqual( + projection.runs.map((run) => [run.status, run.providerInstanceId]), + [ + ["running", CLAUDE_MODEL_SELECTION.instanceId], + ["queued", CODEX_MODEL_SELECTION.instanceId], + ], + ); + yield* Deferred.succeed(harness.release, undefined); + }).pipe(Effect.provide(harness.layer)); + }), + ); + + // regression: #32891 a steer that Stop already reached is refused, not queued + it.live("refuses a provider switch steered into a Claude turn that Stop reached", () => + Effect.gen(function* () { + const harness = yield* steerProviderSwitchHarness("after-stop"); + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + yield* harness.startClaudeTurn; + yield* Deferred.await(harness.started); + yield* worker.drain(); + yield* harness.markClaudeTurnRunning; + const [claudeRun] = (yield* orchestrator.getThreadProjection(harness.threadId)).runs; + // The worker has not delivered the interrupt yet, so the run still reads as running. + yield* orchestrator.dispatch({ + type: "run.interrupt", + commandId: CommandId.make("command:steer-provider-switch:after-stop:stop"), + threadId: harness.threadId, + runId: claudeRun!.id, + }); + const error = yield* harness.steerToCodex.pipe(Effect.flip); + assert.instanceOf(error, Orchestrator.OrchestratorDispatchError); + assert.deepEqual( + (yield* orchestrator.getThreadProjection(harness.threadId)).runs.map( + (run) => run.providerInstanceId, + ), + [CLAUDE_MODEL_SELECTION.instanceId], + ); + yield* Deferred.succeed(harness.release, undefined); + }).pipe(Effect.provide(harness.layer)); + }), + ); + it.live("hands completed Grok steering context to earlier queued Codex and later Claude", () => Effect.gen(function* () { const cwd = yield* checkpointWorkspace("queued-steer-provider-switch"); From 4d0e2f52d25a7cf663068b2d6f12c290d1a4f40f Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Tue, 17 Nov 2026 18:26:37 +0100 Subject: [PATCH 066/133] fix(cli): concurrent installs no longer nest a duplicate runtime (#38235) Co-authored-by: Grok 4.7 Co-authored-by: Julius Marminge --- scripts/install.sh | 2 + scripts/install.test.ts | 96 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 98 insertions(+) diff --git a/scripts/install.sh b/scripts/install.sh index bc53dcc578d9..4f30deda6858 100755 --- a/scripts/install.sh +++ b/scripts/install.sh @@ -262,6 +262,8 @@ else rm -rf "$target_dir" mv "$staging" "$target_dir" + # When a concurrent install published first, mv moved this copy inside it; keep only theirs. + rm -rf "${target_dir}/${staging##*/}" trap - EXIT fi diff --git a/scripts/install.test.ts b/scripts/install.test.ts index 4580820c7314..f123a9cc0433 100644 --- a/scripts/install.test.ts +++ b/scripts/install.test.ts @@ -536,3 +536,99 @@ describe.skipIf(HostProcess.Platform.defaultValue() !== "linux")("installer chec }, ); }); + +// regression: #38234 +describe.skipIf(HostProcess.Platform.defaultValue() !== "linux")("concurrent installers", () => { + it("publishes one runtime without nesting the other install's staging directory", async () => { + const root = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-install-concurrent-")); + const version = "1.2.3"; + const stem = `t3-${version}-linux-${HostProcess.Architecture.defaultValue()}`; + const archiveName = `${stem}.tar.gz`; + const target = NodePath.join(root, "home/runtime/versions", version); + const waiting = new Map(); + const server = NodeHttp.createServer(); + try { + const tools = NodePath.join(root, "tools"); + await NodeFSP.mkdir(tools); + await NodeFSP.mkdir(NodePath.join(root, stem)); + await NodeFSP.writeFile(NodePath.join(root, stem, "t3"), "#!/bin/sh\necho 't3 v1.2.3'\n", { + mode: 0o755, + }); + const archivePath = NodePath.join(root, archiveName); + NodeChildProcess.execFileSync("tar", ["-czf", archivePath, "-C", root, stem]); + const archive = await NodeFSP.readFile(archivePath); + const digest = NodeCrypto.createHash("sha256").update(archive).digest("hex"); + server.on("request", (request, response) => { + if (request.url?.startsWith("/ready/")) { + waiting.set(request.url.slice(7), response); + if (waiting.size === 2) waiting.get("first")!.end("go"); + } else if (request.url === "/published") { + waiting.get("second")!.end("go"); + response.end("ok"); + } else { + response.end( + request.url?.endsWith("/SHA256SUMS") ? `${digest} ${archiveName}\n` : archive, + ); + } + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const address = server.address(); + if (!address || typeof address === "string") throw new Error("Expected a TCP listener"); + const origin = `http://127.0.0.1:${address.port}`; + const realMv = NodeChildProcess.execFileSync("sh", ["-c", "command -v mv"], { + encoding: "utf8", + }).trim(); + // Hold publication until both installers have removed the destination, then let them rename in order. + const wrapper = NodePath.join(tools, "mv.mjs"); + await NodeFSP.writeFile( + wrapper, + ` +import { execFileSync } from 'node:child_process'; +await fetch(process.env.T3_TEST_ORIGIN + '/ready/' + process.env.T3_TEST_INSTALLER); +execFileSync(${JSON.stringify(realMv)}, process.argv.slice(2)); +if (process.env.T3_TEST_INSTALLER === 'first') await fetch(process.env.T3_TEST_ORIGIN + '/published'); +`, + ); + await NodeFSP.writeFile( + NodePath.join(tools, "mv"), + `#!/bin/sh\nexec '${process.execPath}' '${wrapper}' "$@"\n`, + { mode: 0o755 }, + ); + const install = (id: string) => + new Promise<{ code: number | null; output: string }>((resolve, reject) => { + const child = NodeChildProcess.spawn( + "sh", + [NodePath.join(import.meta.dirname, "install.sh")], + { + env: { + ...process.env, + PATH: `${tools}:${process.env.PATH}`, + T3CODE_VERSION: version, + T3CODE_HOME: NodePath.join(root, "home"), + T3CODE_INSTALL_BIN_DIR: NodePath.join(root, "bin", id), + T3CODE_RELEASE_BASE_URL: origin, + T3_TEST_ORIGIN: origin, + T3_TEST_INSTALLER: id, + }, + stdio: ["ignore", "pipe", "pipe"], + }, + ); + let output = ""; + child.stdout.on("data", (chunk: Buffer) => (output += chunk.toString())); + child.stderr.on("data", (chunk: Buffer) => (output += chunk.toString())); + child.on("error", reject); + child.on("close", (code) => resolve({ code, output })); + }); + const results = await Promise.all([install("first"), install("second")]); + for (const result of results) expect(result.code, result.output).toBe(0); + expect( + (await NodeFSP.readdir(target)).filter((name) => name.startsWith(".staging-")), + "concurrent installs must not leave a nested runtime", + ).toEqual([]); + } finally { + server.closeAllConnections(); + await new Promise((resolve) => server.close(() => resolve())); + await NodeFSP.rm(root, { recursive: true, force: true }); + } + }); +}); From b46edac5c1993b0c2cf721a5ffd3909709bcf7c0 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Tue, 17 Nov 2026 18:35:56 +0100 Subject: [PATCH 067/133] fix(acp): MCP bridge disconnect gives up on an endpoint that never answers (#38237) Co-authored-by: Grok 4.7 Co-authored-by: Julius Marminge --- .../src/server/mcpOverAcpBridge.test.ts | 62 +++++++++++++++++++ .../src/server/mcpOverAcpBridge.ts | 13 +++- 2 files changed, 74 insertions(+), 1 deletion(-) diff --git a/packages/provider-acp/src/server/mcpOverAcpBridge.test.ts b/packages/provider-acp/src/server/mcpOverAcpBridge.test.ts index d60da55bb91d..04d9fe4b5563 100644 --- a/packages/provider-acp/src/server/mcpOverAcpBridge.test.ts +++ b/packages/provider-acp/src/server/mcpOverAcpBridge.test.ts @@ -1,6 +1,9 @@ import { describe, expect, it } from "@effect/vitest"; import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; +import * as Exit from "effect/Exit"; +import * as Scope from "effect/Scope"; +import * as TestClock from "effect/testing/TestClock"; import { makeAcpMcpOverAcpBridge } from "./mcpOverAcpBridge.ts"; @@ -165,6 +168,65 @@ describe("AcpMcpOverAcpBridge", () => { }), ); + it.effect("closes all MCP sessions within one disconnect timeout during runtime cleanup", () => + Effect.gen(function* () { + const deleteStarted = Promise.withResolvers(); + const deleteResponse = Promise.withResolvers(); + const deleteSignals: AbortSignal[] = []; + let nextConnectionId = 0; + const bridge = yield* makeAcpMcpOverAcpBridge({ + endpoint: "http://127.0.0.1:1/mcp", + authorization: "Bearer bridge-test", + allocateConnectionId: Effect.sync(() => `connection-${++nextConnectionId}`), + fetchImplementation: (_url, init) => { + if (init?.method === "DELETE") { + if (!init.signal) throw new Error("Missing cancellation signal"); + deleteSignals.push(init.signal); + deleteStarted.resolve(); + return deleteResponse.promise; + } + const request = JSON.parse(String(init?.body)) as { readonly id: number }; + return Promise.resolve( + new Response( + JSON.stringify({ + jsonrpc: "2.0", + id: request.id, + result: { protocolVersion: "2025-06-18" }, + }), + { + headers: { + "content-type": "application/json", + "mcp-session-id": `session-${nextConnectionId}`, + }, + }, + ), + ); + }, + }); + for (let index = 0; index < 16; index++) { + const { connectionId } = yield* bridge.connect({ serverId: "t3-code" }); + yield* bridge.message({ connectionId, method: "initialize" }); + } + const scope = yield* Scope.make(); + yield* Scope.addFinalizer(scope, bridge.dispose); + const closing = yield* Scope.close(scope, Exit.void).pipe(Effect.forkChild); + yield* Effect.gen(function* () { + yield* Effect.promise(() => deleteStarted.promise); + yield* TestClock.adjust("5 seconds"); + expect(closing.pollUnsafe(), "All sessions must close within one timeout").toBeDefined(); + expect(deleteSignals).toHaveLength(16); + expect(deleteSignals.every((signal) => signal.aborted)).toBe(true); + }).pipe( + Effect.ensuring( + Effect.gen(function* () { + deleteResponse.resolve(new Response(null, { status: 204 })); + yield* Fiber.join(closing); + }), + ), + ); + }), + ); + it.effect("rejects unknown servers, connections, and oversized messages", () => Effect.gen(function* () { const bridge = yield* makeAcpMcpOverAcpBridge({ diff --git a/packages/provider-acp/src/server/mcpOverAcpBridge.ts b/packages/provider-acp/src/server/mcpOverAcpBridge.ts index 3ec47074f144..779076a622b5 100644 --- a/packages/provider-acp/src/server/mcpOverAcpBridge.ts +++ b/packages/provider-acp/src/server/mcpOverAcpBridge.ts @@ -10,6 +10,8 @@ import { responsePayloads } from "@t3tools/shared/mcpResponsePayloads"; const MAX_CONNECTIONS = 16; const MAX_MESSAGE_BYTES = 8 * 1024 * 1024; +// Runtime teardown waits on disconnect, so an endpoint that never answers must not hold it. +const DISCONNECT_TIMEOUT = "5 seconds"; interface JsonRpcEnvelope { readonly id?: unknown; @@ -207,6 +209,15 @@ export const makeAcpMcpOverAcpBridge = Effect.fn("AcpMcpOverAcpBridge.make")(fun () => response.body?.cancel().catch(() => undefined) ?? Promise.resolve(), ); }).pipe( + Effect.timeoutOrElse({ + duration: DISCONNECT_TIMEOUT, + orElse: () => + Effect.fail( + new AcpMcpOverAcpError({ + message: "T3 Code MCP endpoint did not answer disconnect.", + }), + ), + }), // Restore a session that failed to close, so a retry or dispose can close it. Effect.onError(() => Effect.sync(() => connections.set(request.connectionId, connection))), ); @@ -272,7 +283,7 @@ export const makeAcpMcpOverAcpBridge = Effect.fn("AcpMcpOverAcpBridge.make")(fun Effect.forEach( [...connections.keys()], (connectionId) => disconnect({ connectionId }).pipe(Effect.ignore), - { discard: true }, + { concurrency: "unbounded", discard: true }, ), ), }; From f596689035f8f75c6f2c93fb6aca18541d0de7f9 Mon Sep 17 00:00:00 2001 From: Jay Meistrich Date: Tue, 17 Nov 2026 09:52:27 -0800 Subject: [PATCH 068/133] chore(deps): bump @legendapp/list to 3.7.3 and drop its patch (#38220) --- patches/@legendapp__list@3.7.2.patch | 210 --------------------------- pnpm-lock.yaml | 17 +-- pnpm-workspace.yaml | 8 +- 3 files changed, 11 insertions(+), 224 deletions(-) delete mode 100644 patches/@legendapp__list@3.7.2.patch diff --git a/patches/@legendapp__list@3.7.2.patch b/patches/@legendapp__list@3.7.2.patch deleted file mode 100644 index a9a1d31a3982..000000000000 --- a/patches/@legendapp__list@3.7.2.patch +++ /dev/null @@ -1,210 +0,0 @@ -diff --git a/react-native.js b/react-native.js -index 4af685dfb961eb0c8a4bf1ae9132c9304cf4fa4d..a50466b8fc8509db2d097b85a09d2109a20530cb 100644 ---- a/react-native.js -+++ b/react-native.js -@@ -1795,7 +1795,35 @@ function resolvePendingNativeMVCPAdjust(ctx, newScroll) { - } - return false; - } -+// T3 patch: while following the end, a size-only change keeps the end in the same pass that -+// repositions the items. Native end following otherwise runs a frame later, after MVCP has -+// anchored the top row, so the feed visibly jumps twice. -+function shouldHoldEndOnSizeChange(ctx, dataChanged) { -+ const state = ctx.state; -+ return !dataChanged && !!state.props.maintainScrollAtEnd && !!state.didFinishInitialScroll && !state.endFollowInterrupted && !state.visibleContentAnchor && state.scrollingTo === void 0 && !state.isDragging && state.userScrollContentSize === void 0 && !!peek$(ctx, "isFollowingEnd"); -+} - function prepareMVCP(ctx, dataChanged, adjustmentSource) { -+ const restore = prepareDefaultMVCP(ctx, dataChanged, adjustmentSource); -+ if (!shouldHoldEndOnSizeChange(ctx, dataChanged)) { -+ return restore; -+ } -+ return () => { -+ if (!shouldHoldEndOnSizeChange(ctx, dataChanged)) { -+ restore == null ? void 0 : restore(); -+ return; -+ } -+ // Content that shrinks under an offset past its new end pulls the native offset back by itself. -+ const endOffset = getScrollRangeEnd(ctx); -+ if (ctx.state.scroll > endOffset) { -+ ctx.state.scroll = endOffset; -+ } -+ const positionDiff = endOffset - ctx.state.scroll; -+ if (Math.abs(positionDiff) > MVCP_POSITION_EPSILON) { -+ requestAdjust(ctx, positionDiff, adjustmentSource); -+ } -+ }; -+} -+function prepareDefaultMVCP(ctx, dataChanged, adjustmentSource) { - var _a3, _b, _c; - const state = ctx.state; - const { idsInView, positions, props } = state; -@@ -5422,6 +5450,11 @@ function updateItemSizesBatch(ctx, measurements) { - const result = {}; - const previousTotalSize = state.totalSize; - for (const measurement of measurements) { -+ // T3 patch: Fabric's measure() reports NaN for a container with no layout yet. A NaN size makes -+ // totalSize NaN, and since NaN !== NaN, useArr$ returns a new snapshot on every read until React -+ // throws "Maximum update depth exceeded". The container's onLayout reports its real size later. -+ const measuredSize = state.props.horizontal ? measurement.size.width : measurement.size.height; -+ if (!Number.isFinite(measuredSize)) continue; - const ownsMeasuredItem = measurement.containerId === void 0 || isContainerItemCurrent(ctx, measurement.containerId, measurement.itemKey); - if (ownsMeasuredItem) { - const index = state.indexByKey.get(measurement.itemKey); -diff --git a/react-native.mjs b/react-native.mjs -index 9ebfddc183a9b202d35c990a387c9b628feeb185..489050190144997ac72de8f4f7c6219479216dba 100644 ---- a/react-native.mjs -+++ b/react-native.mjs -@@ -1774,7 +1774,35 @@ function resolvePendingNativeMVCPAdjust(ctx, newScroll) { - } - return false; - } -+// T3 patch: while following the end, a size-only change keeps the end in the same pass that -+// repositions the items. Native end following otherwise runs a frame later, after MVCP has -+// anchored the top row, so the feed visibly jumps twice. -+function shouldHoldEndOnSizeChange(ctx, dataChanged) { -+ const state = ctx.state; -+ return !dataChanged && !!state.props.maintainScrollAtEnd && !!state.didFinishInitialScroll && !state.endFollowInterrupted && !state.visibleContentAnchor && state.scrollingTo === void 0 && !state.isDragging && state.userScrollContentSize === void 0 && !!peek$(ctx, "isFollowingEnd"); -+} - function prepareMVCP(ctx, dataChanged, adjustmentSource) { -+ const restore = prepareDefaultMVCP(ctx, dataChanged, adjustmentSource); -+ if (!shouldHoldEndOnSizeChange(ctx, dataChanged)) { -+ return restore; -+ } -+ return () => { -+ if (!shouldHoldEndOnSizeChange(ctx, dataChanged)) { -+ restore == null ? void 0 : restore(); -+ return; -+ } -+ // Content that shrinks under an offset past its new end pulls the native offset back by itself. -+ const endOffset = getScrollRangeEnd(ctx); -+ if (ctx.state.scroll > endOffset) { -+ ctx.state.scroll = endOffset; -+ } -+ const positionDiff = endOffset - ctx.state.scroll; -+ if (Math.abs(positionDiff) > MVCP_POSITION_EPSILON) { -+ requestAdjust(ctx, positionDiff, adjustmentSource); -+ } -+ }; -+} -+function prepareDefaultMVCP(ctx, dataChanged, adjustmentSource) { - var _a3, _b, _c; - const state = ctx.state; - const { idsInView, positions, props } = state; -@@ -5401,6 +5429,11 @@ function updateItemSizesBatch(ctx, measurements) { - const result = {}; - const previousTotalSize = state.totalSize; - for (const measurement of measurements) { -+ // T3 patch: Fabric's measure() reports NaN for a container with no layout yet. A NaN size makes -+ // totalSize NaN, and since NaN !== NaN, useArr$ returns a new snapshot on every read until React -+ // throws "Maximum update depth exceeded". The container's onLayout reports its real size later. -+ const measuredSize = state.props.horizontal ? measurement.size.width : measurement.size.height; -+ if (!Number.isFinite(measuredSize)) continue; - const ownsMeasuredItem = measurement.containerId === void 0 || isContainerItemCurrent(ctx, measurement.containerId, measurement.itemKey); - if (ownsMeasuredItem) { - const index = state.indexByKey.get(measurement.itemKey); -diff --git a/react.js b/react.js -index 515545471e08426fc90856256db9491db0ca4b92..b741735df1fbc0c954ed48f15590abce727d5336 100644 ---- a/react.js -+++ b/react.js -@@ -5635,6 +5635,19 @@ function updateOneItemSize(ctx, itemKey, sizeObj, resolvedMeasurementItem, notif - } - - // src/core/measureContainersInLayoutEffect.ts -+// T3 patch: measure rows by their layout box, as ResizeObserver does. getBoundingClientRect -+// includes ancestor transforms, so rows that mount while a dialog scales in measure short and -+// stay packed too tightly until they re-render. -+function measureContainerLayoutSize(element) { -+ const rect = element.getBoundingClientRect(); -+ if (Math.abs(rect.width - element.offsetWidth) < 1 && Math.abs(rect.height - element.offsetHeight) < 1) { -+ return { height: rect.height, width: rect.width }; -+ } -+ const style = getComputedStyle(element); -+ const height = Number.parseFloat(style.height); -+ const width = Number.parseFloat(style.width); -+ return Number.isFinite(height) && Number.isFinite(width) ? { height, width } : { height: rect.height, width: rect.width }; -+} - function measureContainersInLayoutEffect(ctx, targetContainerIds = null) { - var _a3, _b, _c; - const dataChangeEpoch = ctx.state.dataChangeEpoch; -@@ -5646,13 +5659,13 @@ function measureContainersInLayoutEffect(ctx, targetContainerIds = null) { - const element = viewRef == null ? void 0 : viewRef.current; - if (itemKey !== void 0 && element && isContainerItemCurrent(ctx, containerId, itemKey)) { - const generation = (_b = ctx.state.containerItemGenerations[containerId]) != null ? _b : 0; -- const rect = element.getBoundingClientRect(); -- setContainerLayoutBaseline(element, rect); -+ const size = measureContainerLayoutSize(element); -+ setContainerLayoutBaseline(element, size); - measurements.push({ - containerId, - generation, - itemKey, -- size: { height: rect.height, width: rect.width } -+ size - }); - } - } -@@ -6296,9 +6309,8 @@ function processContainerLayout({ containerId, ctx, rectangle, ref, state }) { - var _a4; - if (state.itemKey === currentItemKey) { - const element = ref.current; -- const rect = (_a4 = element == null ? void 0 : element.getBoundingClientRect) == null ? void 0 : _a4.call(element); -- if (rect) { -- layout = { height: rect.height, width: rect.width }; -+ if (element) { -+ layout = measureContainerLayoutSize(element); - } - applyLayout(); - } -diff --git a/react.mjs b/react.mjs -index ce08abe7ee62e8940f9c6ff169829244bd6bb736..fce79caef8387e517cbab8051b213cb57b1df590 100644 ---- a/react.mjs -+++ b/react.mjs -@@ -5614,6 +5614,19 @@ function updateOneItemSize(ctx, itemKey, sizeObj, resolvedMeasurementItem, notif - } - - // src/core/measureContainersInLayoutEffect.ts -+// T3 patch: measure rows by their layout box, as ResizeObserver does. getBoundingClientRect -+// includes ancestor transforms, so rows that mount while a dialog scales in measure short and -+// stay packed too tightly until they re-render. -+function measureContainerLayoutSize(element) { -+ const rect = element.getBoundingClientRect(); -+ if (Math.abs(rect.width - element.offsetWidth) < 1 && Math.abs(rect.height - element.offsetHeight) < 1) { -+ return { height: rect.height, width: rect.width }; -+ } -+ const style = getComputedStyle(element); -+ const height = Number.parseFloat(style.height); -+ const width = Number.parseFloat(style.width); -+ return Number.isFinite(height) && Number.isFinite(width) ? { height, width } : { height: rect.height, width: rect.width }; -+} - function measureContainersInLayoutEffect(ctx, targetContainerIds = null) { - var _a3, _b, _c; - const dataChangeEpoch = ctx.state.dataChangeEpoch; -@@ -5625,13 +5638,13 @@ function measureContainersInLayoutEffect(ctx, targetContainerIds = null) { - const element = viewRef == null ? void 0 : viewRef.current; - if (itemKey !== void 0 && element && isContainerItemCurrent(ctx, containerId, itemKey)) { - const generation = (_b = ctx.state.containerItemGenerations[containerId]) != null ? _b : 0; -- const rect = element.getBoundingClientRect(); -- setContainerLayoutBaseline(element, rect); -+ const size = measureContainerLayoutSize(element); -+ setContainerLayoutBaseline(element, size); - measurements.push({ - containerId, - generation, - itemKey, -- size: { height: rect.height, width: rect.width } -+ size - }); - } - } -@@ -6275,9 +6288,8 @@ function processContainerLayout({ containerId, ctx, rectangle, ref, state }) { - var _a4; - if (state.itemKey === currentItemKey) { - const element = ref.current; -- const rect = (_a4 = element == null ? void 0 : element.getBoundingClientRect) == null ? void 0 : _a4.call(element); -- if (rect) { -- layout = { height: rect.height, width: rect.width }; -+ if (element) { -+ layout = measureContainerLayoutSize(element); - } - applyLayout(); - } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 70431202c4b6..7c7e1e954800 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -284,7 +284,7 @@ overrides: expo-sharing: 58.0.22 expo-widgets: 58.0.27 '@ff-labs/fff-node': 0.11.0 - '@legendapp/list': 3.7.2 + '@legendapp/list': 3.7.3 '@pierre/diffs': 1.7.0-beta.4 '@react-native-ai/apple': 0.12.0 '@react-native-menu/menu': 2.0.0 @@ -370,7 +370,6 @@ patchedDependencies: '@effect/vitest@4.1.2': 299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7 '@expo/ui@58.0.27': 9f2547678939f4ec78fe45163b6455aad63d3c80353d7e0cc783f6a61a7ccc2f '@ff-labs/fff-node@0.11.0': 93f62a76399b435a76588b2bef237db0a1e85880c1ac0d0759c416e9cc579252 - '@legendapp/list@3.7.2': fc8470158c72676c35f43a0a84f90e53105c3eedd930e242534a37ff4159a3ef '@muse-code/sdk@1.4.6': 7b495b607fc5d76b444c7c4d58821e839726a30e6f3c53564f0d59f2d5b42101 '@pierre/diffs@1.7.0-beta.4': b24b206d14c79de95be10322b96490b82e41cc13c8a02c7378aaf8e03623431b '@react-native-ai/apple@0.12.0': 2d09870c2848d185cb05b53ed823a46e12dba519324d8dd8e584e28731990f9d @@ -566,8 +565,8 @@ importers: specifier: 4.2.13 version: 4.2.13 '@legendapp/list': - specifier: 3.7.2 - version: 3.7.2(patch_hash=fc8470158c72676c35f43a0a84f90e53105c3eedd930e242534a37ff4159a3ef)(react-dom@19.3.0(react@19.3.0))(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0) + specifier: 3.7.3 + version: 3.7.3(react-dom@19.3.0(react@19.3.0))(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0) '@material/material-color-utilities': specifier: 0.3.0 version: 0.3.0 @@ -1090,8 +1089,8 @@ importers: specifier: ^5.3.0 version: 5.3.0 '@legendapp/list': - specifier: 3.7.2 - version: 3.7.2(patch_hash=fc8470158c72676c35f43a0a84f90e53105c3eedd930e242534a37ff4159a3ef)(react-dom@19.3.0(react@19.3.0))(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0) + specifier: 3.7.3 + version: 3.7.3(react-dom@19.3.0(react@19.3.0))(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0) '@noble/hashes': specifier: 'catalog:' version: 1.8.0 @@ -4952,8 +4951,8 @@ packages: cpu: [x64] os: [win32] - '@legendapp/list@3.7.2': - resolution: {integrity: sha512-StFy5qjOHHuxHKjenwLq500S/z+zuF43hj8iqXhX9EMtzeOagPfsnMRWphvBG4CYBvMTX6VzgLjN5BzzwY1jDA==} + '@legendapp/list@3.7.3': + resolution: {integrity: sha512-trGu1i4xo1+r6gG6GI3qrrZAfYHbB25uVj32/KnxhaQ7/eW4AqzhM5cW21Oye4dpg+180Ts1aejRuI8z6Xc4eg==} peerDependencies: react: '*' react-dom: '*' @@ -15598,7 +15597,7 @@ snapshots: '@koromix/koffi-win32-x64@3.3.6': optional: true - '@legendapp/list@3.7.2(patch_hash=fc8470158c72676c35f43a0a84f90e53105c3eedd930e242534a37ff4159a3ef)(react-dom@19.3.0(react@19.3.0))(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0)': + '@legendapp/list@3.7.3(react-dom@19.3.0(react@19.3.0))(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0)': dependencies: react: 19.3.0 use-sync-external-store: 1.7.0(react@19.3.0) diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 5c66aef02dda..04f881d6f124 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -54,7 +54,7 @@ catalog: "@effect/sql-sqlite-do": 4.1.2 "@effect/vitest": 4.1.2 "@electron-webauthn/macos": 1.3.1 - "@legendapp/list": 3.7.2 + "@legendapp/list": 3.7.3 "@noble/curves": 1.9.1 "@noble/hashes": 1.8.0 "@pierre/diffs": 1.7.0-beta.4 @@ -115,7 +115,7 @@ overrides: expo-sharing: 58.0.22 expo-widgets: 58.0.27 "@ff-labs/fff-node": 0.11.0 - "@legendapp/list": 3.7.2 + "@legendapp/list": 3.7.3 "@pierre/diffs": 1.7.0-beta.4 "@react-native-ai/apple": 0.12.0 "@react-native-menu/menu": 2.0.0 @@ -282,8 +282,6 @@ patchedDependencies: alchemy@2.0.0-beta.85: patches/alchemy@2.0.0-beta.85.patch # Android: a marker orient other than "auto" or a number (auto-start-reverse) no longer throws. react-native-svg@15.16.1: patches/react-native-svg@15.16.1.patch - # iOS: a feed following its end keeps the end through a size-only reflow in one pass. - "@legendapp/list@3.7.2": patches/@legendapp__list@3.7.2.patch # Android: double-tap zoom no longer cancels itself, and taps near a link open it. react-native-pdf-jsi@6.1.0: patches/react-native-pdf-jsi@6.1.0.patch @@ -319,7 +317,7 @@ publicHoistPattern: - "@cursor/sdk-*" minimumReleaseAgeExclude: - - "@legendapp/list@3.7.2" + - "@legendapp/list@3.7.3" - "@effect/tsgo-darwin-arm64@0.67.1" - "@effect/tsgo-darwin-x64@0.67.1" - "@effect/tsgo-linux-arm64@0.67.1" From bfd37b2b5341645c5da172e6e2acae9b82c946f8 Mon Sep 17 00:00:00 2001 From: Utkarsh Patil <73941998+UtkarshUsername@users.noreply.github.com> Date: Tue, 17 Nov 2026 23:22:46 +0530 Subject: [PATCH 069/133] feat(speech): recommend local models by language, speed and accuracy (#33336) --- .../features/settings/VoiceModelSection.tsx | 2 +- apps/server/scripts/speech-catalog.test.ts | 32 ++- apps/server/scripts/speech-catalog.ts | 11 +- apps/server/scripts/sync-speech-catalog.ts | 17 +- apps/server/src/speech/catalog.json | 116 +++++----- .../settings/SpeechModelComparison.tsx | 33 +-- .../VoiceSettingsPanel.browser.test.tsx | 203 +++++++++++------- .../settings/VoiceSettingsPanel.tsx | 52 +++-- .../settings/speechModelBrowser.test.ts | 64 +++++- .../components/settings/speechModelBrowser.ts | 13 +- ...useEnvironmentSpeechInput.browser.test.tsx | 47 +++- .../src/speech/useEnvironmentSpeechInput.ts | 33 ++- docs/user/voice-input.md | 6 +- packages/shared/src/speech.test.ts | 182 +++++++++++++++- packages/shared/src/speech.ts | 106 ++++++++- .../src/speechRecommendationPolicy.json | 11 + 16 files changed, 715 insertions(+), 213 deletions(-) create mode 100644 packages/shared/src/speechRecommendationPolicy.json diff --git a/apps/mobile/src/features/settings/VoiceModelSection.tsx b/apps/mobile/src/features/settings/VoiceModelSection.tsx index 0bee9748b19c..0b2a7da5e542 100644 --- a/apps/mobile/src/features/settings/VoiceModelSection.tsx +++ b/apps/mobile/src/features/settings/VoiceModelSection.tsx @@ -148,7 +148,7 @@ function ModelStats(props: { readonly model: EnvironmentSpeechModel; readonly la "speed", <> - {data.secondsPer30s.accelerated} s + {Number(data.secondsPer30s.accelerated.toFixed(2))} s {" "} / 30 s , diff --git a/apps/server/scripts/speech-catalog.test.ts b/apps/server/scripts/speech-catalog.test.ts index 2a68c80f5fed..1ec8fe99b705 100644 --- a/apps/server/scripts/speech-catalog.test.ts +++ b/apps/server/scripts/speech-catalog.test.ts @@ -2,6 +2,8 @@ import * as NodeFS from "node:fs"; import { catalog } from "@handy-computer/models"; +import { recommendSpeechModels } from "@t3tools/shared/speech"; +import policy from "../../../packages/shared/src/speechRecommendationPolicy.json" with { type: "json" }; import { expect, it } from "vite-plus/test"; import manifest from "../package.json" with { type: "json" }; @@ -15,6 +17,8 @@ const generate = (models = catalog.models) => ); it("reproduces the bundled registry byte for byte without upstream requests", async () => { + const { fastCpuMaxWaitSeconds, ...methodology } = catalog.methodology; + expect(policy).toEqual({ ...methodology, fastMaxWaitSeconds: fastCpuMaxWaitSeconds }); expect(NodeFS.readFileSync(new URL("../src/speech/catalog.json", import.meta.url), "utf8")).toBe( await renderSpeechCatalog( catalog.data, @@ -53,18 +57,40 @@ it("reproduces the bundled registry byte for byte without upstream requests", as { ...catalog.data, models: [parakeet], - results: { [parakeet.id]: { accuracy: {}, performance } }, + results: { [parakeet.id]: { accuracy: { en: { error: 3.99 } }, performance } }, }, "0.2.3", "0.4.1", ); expect(result.models[0]?.benchmark.secondsPer30s).toEqual({ - cpu: performance.cpu ? 15 : null, - accelerated: performance.accelerated ? 3 : null, + cpu: performance.cpu ? 30 / performance.cpu : null, + accelerated: performance.accelerated ? 30 / performance.accelerated : null, }); } }); +it("preserves Handy's accelerated balanced pick after filtering T3's offered candidates", () => { + const offered = generate().models; + const sources = catalog.models.filter((model) => + offered.some(({ id }) => id === model.repository), + ); + for (const languages of [["en"], ["de"], ["ja"], ["en", "de"], ["en", "fr"], ["hi", "mr"]]) { + const expected = catalog + .recommendModels(sources, languages) + .find((pick) => pick.status !== "unbenchmarked" && pick.roles.includes("best")); + expect( + recommendSpeechModels(offered, languages, "accelerated").keys().next().value, + languages.join(","), + ).toBe(expected?.model.repository); + } + const excluded = { ...catalog.models[0]!, license: "cc-by-nc-4.0" }; + const allowed = { ...catalog.models[1]!, languages: ["en"] }; + const filtered = generate([excluded, allowed]).models; + expect([...recommendSpeechModels(filtered, ["en"], "accelerated").keys()]).toEqual([ + allowed.repository, + ]); +}); + it("filters restricted licenses, unsupported roles, engines, architectures and files", () => { const model = catalog.models[0]!; for (const override of [ diff --git a/apps/server/scripts/speech-catalog.ts b/apps/server/scripts/speech-catalog.ts index 5e8a6f8d12fe..3af49ceee034 100644 --- a/apps/server/scripts/speech-catalog.ts +++ b/apps/server/scripts/speech-catalog.ts @@ -31,7 +31,7 @@ const ASR_FAMILIES = new Set([ "medasr", ]); -// Preserve Handy's onboarding badges; curation alone also includes specialist models. +// Older clients rank and pick setup models by this flag; current clients use language recommendations. const RECOMMENDED = new Set([ "parakeet-unified-en-0.6b", "nemotron-3.5-asr-streaming-0.6b", @@ -81,9 +81,8 @@ export function generateSpeechCatalog( ids.add(model.repository); filenames.add(file.filename); const languages = [...new Set(model.languages.map(canonicalLanguage))]; - const performance = data.results[model.id]?.performance; - const secondsPer30s = (realtimeFactor: number | undefined) => - realtimeFactor ? Number((BENCHMARK_DICTATION_SECONDS / realtimeFactor).toFixed(2)) : null; + const realtimeFactor = data.results[model.id]?.performance.accelerated; + const cpuFactor = data.results[model.id]?.performance.cpu; const accuracy = Object.fromEntries( languages.flatMap((language) => { const cell = data.results[model.id]?.accuracy[languageIdentity(language)]; @@ -112,8 +111,8 @@ export function generateSpeechCatalog( benchmark: { accuracy, secondsPer30s: { - cpu: secondsPer30s(performance?.cpu), - accelerated: secondsPer30s(performance?.accelerated), + cpu: cpuFactor ? BENCHMARK_DICTATION_SECONDS / cpuFactor : null, + accelerated: realtimeFactor ? BENCHMARK_DICTATION_SECONDS / realtimeFactor : null, }, }, recommended: RECOMMENDED.has(model.id), diff --git a/apps/server/scripts/sync-speech-catalog.ts b/apps/server/scripts/sync-speech-catalog.ts index 1a809502dc45..d9309ae98904 100644 --- a/apps/server/scripts/sync-speech-catalog.ts +++ b/apps/server/scripts/sync-speech-catalog.ts @@ -5,6 +5,7 @@ import * as NodeModule from "node:module"; import * as NodePath from "node:path"; import { catalog } from "@handy-computer/models"; +import { format } from "vite-plus/fmt"; import * as Schema from "effect/Schema"; import manifest from "../package.json" with { type: "json" }; @@ -24,12 +25,26 @@ const expected = await renderSpeechCatalog( sourceManifest.version, manifest.dependencies["transcribe-cpp"], ); +const policyTarget = new URL( + "../../../packages/shared/src/speechRecommendationPolicy.json", + import.meta.url, +); +const { fastCpuMaxWaitSeconds, ...methodology } = catalog.methodology; +const policy = await format( + "speechRecommendationPolicy.json", + JSON.stringify({ ...methodology, fastMaxWaitSeconds: fastCpuMaxWaitSeconds }), +); +if (policy.errors.length > 0) throw new Error("Could not format speech recommendation policy."); if (process.argv.includes("--check")) { - if (NodeFS.readFileSync(target, "utf8") !== expected) { + if ( + NodeFS.readFileSync(target, "utf8") !== expected || + NodeFS.readFileSync(policyTarget, "utf8") !== policy.code + ) { throw new Error("Speech catalog differs; run vp run speech:catalog:sync in apps/server."); } console.log("Bundled speech catalog matches the pinned source."); } else { NodeFS.writeFileSync(target, expected); + NodeFS.writeFileSync(policyTarget, policy.code); console.log(`Generated speech catalog from @handy-computer/models@${sourceManifest.version}.`); } diff --git a/apps/server/src/speech/catalog.json b/apps/server/src/speech/catalog.json index 2a2175ca1863..782211e0ec16 100644 --- a/apps/server/src/speech/catalog.json +++ b/apps/server/src/speech/catalog.json @@ -15,7 +15,7 @@ "languages": ["en"], "benchmark": { "accuracy": { "en": { "grade": "A-", "errorPercent": 3.99 } }, - "secondsPer30s": { "cpu": 2.15, "accelerated": 1.19 } + "secondsPer30s": { "cpu": 2.149767108563239, "accelerated": 1.1867088607594936 } }, "recommended": true, "supportsStreaming": true, @@ -92,7 +92,7 @@ "ro": { "grade": "D", "errorPercent": 28.28 }, "et": { "grade": "F", "errorPercent": 31.84 } }, - "secondsPer30s": { "cpu": 2.83, "accelerated": 1.75 } + "secondsPer30s": { "cpu": 2.8328611898016995, "accelerated": 1.7508024511234315 } }, "recommended": true, "supportsStreaming": true, @@ -116,7 +116,7 @@ "es": { "grade": "B", "errorPercent": 6.54 }, "fr": { "grade": "B-", "errorPercent": 8.53 } }, - "secondsPer30s": { "cpu": 1.38, "accelerated": 0.91 } + "secondsPer30s": { "cpu": 1.3805798435342844, "accelerated": 0.9067553271875473 } }, "recommended": true, "supportsStreaming": false, @@ -165,7 +165,7 @@ "vi": { "grade": "B", "errorPercent": 7.39 }, "ko": { "grade": "B", "errorPercent": 6.57 } }, - "secondsPer30s": { "cpu": 6.96, "accelerated": 3.71 } + "secondsPer30s": { "cpu": 6.960556844547565, "accelerated": 3.7059913526868433 } }, "recommended": true, "supportsStreaming": false, @@ -367,7 +367,7 @@ "yo": { "grade": "F", "errorPercent": 109 }, "zh": { "grade": "C", "errorPercent": 13.13 } }, - "secondsPer30s": { "cpu": 15.58, "accelerated": 7.34 } + "secondsPer30s": { "cpu": 15.584415584415584, "accelerated": 7.343941248470013 } }, "recommended": true, "supportsStreaming": false, @@ -400,7 +400,7 @@ "hi": { "grade": "C", "errorPercent": 14.44 }, "ko": { "grade": "B+", "errorPercent": 5.27 } }, - "secondsPer30s": { "cpu": 51.28, "accelerated": 39.47 } + "secondsPer30s": { "cpu": 51.282051282051285, "accelerated": 39.473684210526315 } }, "recommended": false, "supportsStreaming": true, @@ -471,7 +471,7 @@ "el": { "grade": "F", "errorPercent": 32.25 }, "mt": { "grade": "C-", "errorPercent": 17.01 } }, - "secondsPer30s": { "cpu": 2.26, "accelerated": 1.3 } + "secondsPer30s": { "cpu": 2.2573363431151243, "accelerated": 1.3043478260869565 } }, "recommended": false, "supportsStreaming": false, @@ -542,7 +542,7 @@ "sv": { "grade": "C", "errorPercent": 15.25 }, "uk": { "grade": "B", "errorPercent": 6.84 } }, - "secondsPer30s": { "cpu": 2.2, "accelerated": 1.2 } + "secondsPer30s": { "cpu": 2.1969974368363236, "accelerated": 1.196888090963495 } }, "recommended": false, "supportsStreaming": false, @@ -561,7 +561,7 @@ "languages": ["en"], "benchmark": { "accuracy": { "en": { "grade": "A-", "errorPercent": 4.11 } }, - "secondsPer30s": { "cpu": 2.1, "accelerated": 1.09 } + "secondsPer30s": { "cpu": 2.102312543798178, "accelerated": 1.0934937124111537 } }, "recommended": false, "supportsStreaming": false, @@ -642,7 +642,7 @@ "hu": { "grade": "F", "errorPercent": 56.24 }, "mk": { "grade": "F", "errorPercent": 35.09 } }, - "secondsPer30s": { "cpu": 5.67, "accelerated": 3.09 } + "secondsPer30s": { "cpu": 5.665722379603399, "accelerated": 3.091190108191654 } }, "recommended": false, "supportsStreaming": false, @@ -725,7 +725,7 @@ "sl": { "grade": "F", "errorPercent": 75.22 }, "sv": { "grade": "F", "errorPercent": 75.36 } }, - "secondsPer30s": { "cpu": 5.48, "accelerated": 3.4 } + "secondsPer30s": { "cpu": 5.484460694698355, "accelerated": 3.3955857385398978 } }, "recommended": false, "supportsStreaming": false, @@ -796,7 +796,7 @@ "ru": { "grade": "B", "errorPercent": 7.83 }, "uk": { "grade": "C+", "errorPercent": 10.58 } }, - "secondsPer30s": { "cpu": 3.6, "accelerated": 2.12 } + "secondsPer30s": { "cpu": 3.603603603603604, "accelerated": 2.1231422505307855 } }, "recommended": false, "supportsStreaming": false, @@ -815,7 +815,7 @@ "languages": ["en"], "benchmark": { "accuracy": { "en": { "grade": "A", "errorPercent": 3.58 } }, - "secondsPer30s": { "cpu": 11.95, "accelerated": 7.55 } + "secondsPer30s": { "cpu": 11.952191235059763, "accelerated": 7.547169811320755 } }, "recommended": false, "supportsStreaming": false, @@ -837,7 +837,7 @@ "en": { "grade": "A-", "errorPercent": 4.88 }, "ar": { "grade": "C+", "errorPercent": 11.06 } }, - "secondsPer30s": { "cpu": 6.96, "accelerated": 3.61 } + "secondsPer30s": { "cpu": 6.960556844547565, "accelerated": 3.6122817579771223 } }, "recommended": false, "supportsStreaming": false, @@ -860,7 +860,7 @@ "en": { "grade": "B+", "errorPercent": 5.49 }, "ja": { "grade": "B-", "errorPercent": 8.5 } }, - "secondsPer30s": { "cpu": 3.78, "accelerated": 2.8 } + "secondsPer30s": { "cpu": 3.7759597230962867, "accelerated": 2.7958993476234855 } }, "recommended": false, "supportsStreaming": false, @@ -879,7 +879,7 @@ "languages": ["ru"], "benchmark": { "accuracy": { "ru": { "grade": "B+", "errorPercent": 5.53 } }, - "secondsPer30s": { "cpu": 2.62, "accelerated": 0.85 } + "secondsPer30s": { "cpu": 2.618943692710607, "accelerated": 0.8480565371024735 } }, "recommended": false, "supportsStreaming": false, @@ -898,7 +898,7 @@ "languages": ["ru"], "benchmark": { "accuracy": { "ru": { "grade": "B+", "errorPercent": 5.35 } }, - "secondsPer30s": { "cpu": 3.81, "accelerated": 2 } + "secondsPer30s": { "cpu": 3.8095238095238093, "accelerated": 1.9973368841544608 } }, "recommended": false, "supportsStreaming": false, @@ -917,7 +917,7 @@ "languages": ["en"], "benchmark": { "accuracy": { "en": { "grade": "A-", "errorPercent": 4.61 } }, - "secondsPer30s": { "cpu": 1.74, "accelerated": 1.31 } + "secondsPer30s": { "cpu": 1.7401392111368912, "accelerated": 1.312048983162038 } }, "recommended": false, "supportsStreaming": false, @@ -943,7 +943,7 @@ "pt": { "grade": "B-", "errorPercent": 9.8 }, "ja": { "grade": "B", "errorPercent": 6.3 } }, - "secondsPer30s": { "cpu": 10.81, "accelerated": 6.5 } + "secondsPer30s": { "cpu": 10.81081081081081, "accelerated": 6.500541711809317 } }, "recommended": false, "supportsStreaming": false, @@ -962,7 +962,7 @@ "languages": ["en"], "benchmark": { "accuracy": { "en": { "grade": "F", "errorPercent": 37.48 } }, - "secondsPer30s": { "cpu": 1.16, "accelerated": 0.42 } + "secondsPer30s": { "cpu": 1.1598685482312006, "accelerated": 0.4209935447656469 } }, "recommended": false, "supportsStreaming": false, @@ -981,7 +981,7 @@ "languages": ["en"], "benchmark": { "accuracy": { "en": { "grade": "B+", "errorPercent": 6.11 } }, - "secondsPer30s": { "cpu": 0.6, "accelerated": 0.39 } + "secondsPer30s": { "cpu": 0.5996402158704777, "accelerated": 0.39238767902687854 } }, "recommended": false, "supportsStreaming": false, @@ -1000,7 +1000,7 @@ "languages": ["en"], "benchmark": { "accuracy": { "en": { "grade": "B", "errorPercent": 6.52 } }, - "secondsPer30s": { "cpu": 2.24, "accelerated": 1.14 } + "secondsPer30s": { "cpu": 2.236302646291465, "accelerated": 1.1387360030366294 } }, "recommended": false, "supportsStreaming": true, @@ -1081,7 +1081,7 @@ "hu": { "grade": "F", "errorPercent": 32.84 }, "mk": { "grade": "C-", "errorPercent": 18.22 } }, - "secondsPer30s": { "cpu": 12.15, "accelerated": 7.34 } + "secondsPer30s": { "cpu": 12.14574898785425, "accelerated": 7.343941248470013 } }, "recommended": false, "supportsStreaming": false, @@ -1106,7 +1106,7 @@ "ja": { "grade": "B", "errorPercent": 7.63 }, "ko": { "grade": "B-", "errorPercent": 8.27 } }, - "secondsPer30s": { "cpu": 1.52, "accelerated": 1.08 } + "secondsPer30s": { "cpu": 1.5201418799087916, "accelerated": 1.0834236186348862 } }, "recommended": false, "supportsStreaming": false, @@ -1134,7 +1134,7 @@ "nl": { "grade": "B", "errorPercent": 6.57 }, "hi": { "grade": "B-", "errorPercent": 8.93 } }, - "secondsPer30s": { "cpu": 53.57, "accelerated": 27.65 } + "secondsPer30s": { "cpu": 53.57142857142857, "accelerated": 27.649769585253456 } }, "recommended": false, "supportsStreaming": false, @@ -1336,7 +1336,7 @@ "yo": { "grade": "F", "errorPercent": 118.5 }, "zh": { "grade": "D", "errorPercent": 23.06 } }, - "secondsPer30s": { "cpu": 5.12, "accelerated": 2.57 } + "secondsPer30s": { "cpu": 5.1194539249146755, "accelerated": 2.5651988029072252 } }, "recommended": false, "supportsStreaming": false, @@ -1540,7 +1540,7 @@ "yue": { "grade": "F", "errorPercent": 34.62 }, "zh": { "grade": "B-", "errorPercent": 8.5 } }, - "secondsPer30s": { "cpu": 20.98, "accelerated": 9.69 } + "secondsPer30s": { "cpu": 20.97902097902098, "accelerated": 9.693053311793214 } }, "recommended": false, "supportsStreaming": false, @@ -1562,7 +1562,7 @@ "zh": { "grade": "B-", "errorPercent": 8.1 }, "en": { "grade": "A-", "errorPercent": 4.14 } }, - "secondsPer30s": { "cpu": 31.25, "accelerated": 14.85 } + "secondsPer30s": { "cpu": 31.25, "accelerated": 14.851485148514852 } }, "recommended": false, "supportsStreaming": false, @@ -1766,7 +1766,7 @@ "yue": { "grade": "D", "errorPercent": 22.06 }, "zh": { "grade": "B-", "errorPercent": 7.98 } }, - "secondsPer30s": { "cpu": 30.93, "accelerated": 15.04 } + "secondsPer30s": { "cpu": 30.927835051546392, "accelerated": 15.037593984962406 } }, "recommended": false, "supportsStreaming": false, @@ -1790,7 +1790,7 @@ "es": { "grade": "B", "errorPercent": 6.73 }, "fr": { "grade": "B", "errorPercent": 7.22 } }, - "secondsPer30s": { "cpu": 3.39, "accelerated": 1.94 } + "secondsPer30s": { "cpu": 3.3898305084745766, "accelerated": 1.937984496124031 } }, "recommended": false, "supportsStreaming": false, @@ -1809,7 +1809,7 @@ "languages": ["ru"], "benchmark": { "accuracy": { "ru": { "grade": "B-", "errorPercent": 8.42 } }, - "secondsPer30s": { "cpu": 2.54, "accelerated": 0.75 } + "secondsPer30s": { "cpu": 2.5369978858350954, "accelerated": 0.7543374402816192 } }, "recommended": false, "supportsStreaming": false, @@ -1828,7 +1828,7 @@ "languages": ["ru"], "benchmark": { "accuracy": { "ru": { "grade": "B-", "errorPercent": 8.07 } }, - "secondsPer30s": { "cpu": 2.9, "accelerated": 1.12 } + "secondsPer30s": { "cpu": 2.9013539651837523, "accelerated": 1.1219147344801796 } }, "recommended": false, "supportsStreaming": false, @@ -1854,7 +1854,7 @@ "pt": { "grade": "B-", "errorPercent": 9.6 }, "ja": { "grade": "B", "errorPercent": 6.44 } }, - "secondsPer30s": { "cpu": 10.89, "accelerated": 6.47 } + "secondsPer30s": { "cpu": 10.88929219600726, "accelerated": 6.472491909385114 } }, "recommended": false, "supportsStreaming": false, @@ -1879,7 +1879,7 @@ "es": { "grade": "A-", "errorPercent": 4.08 }, "pt": { "grade": "B+", "errorPercent": 5.57 } }, - "secondsPer30s": { "cpu": 13.99, "accelerated": 7.51 } + "secondsPer30s": { "cpu": 13.986013986013987, "accelerated": 7.509386733416771 } }, "recommended": false, "supportsStreaming": false, @@ -1904,7 +1904,7 @@ "es": { "grade": "B", "errorPercent": 6.53 }, "pt": { "grade": "C+", "errorPercent": 10.61 } }, - "secondsPer30s": { "cpu": 11.54, "accelerated": 6.46 } + "secondsPer30s": { "cpu": 11.538461538461538, "accelerated": 6.458557588805167 } }, "recommended": false, "supportsStreaming": false, @@ -1923,7 +1923,7 @@ "languages": ["en"], "benchmark": { "accuracy": { "en": { "grade": "C+", "errorPercent": 12.25 } }, - "secondsPer30s": { "cpu": 1.28, "accelerated": 0.84 } + "secondsPer30s": { "cpu": 1.277139208173691, "accelerated": 0.8429334082607474 } }, "recommended": false, "supportsStreaming": false, @@ -1942,7 +1942,7 @@ "languages": ["en"], "benchmark": { "accuracy": { "en": { "grade": "B", "errorPercent": 7.87 } }, - "secondsPer30s": { "cpu": 3.1, "accelerated": 2.1 } + "secondsPer30s": { "cpu": 3.103983445421625, "accelerated": 2.100840336134454 } }, "recommended": false, "supportsStreaming": true, @@ -1961,7 +1961,7 @@ "languages": ["en"], "benchmark": { "accuracy": { "en": { "grade": "B-", "errorPercent": 8.55 } }, - "secondsPer30s": { "cpu": 2.22, "accelerated": 1.38 } + "secondsPer30s": { "cpu": 2.2164758034724787, "accelerated": 1.3780431786862655 } }, "recommended": false, "supportsStreaming": true, @@ -1980,7 +1980,7 @@ "languages": ["en"], "benchmark": { "accuracy": { "en": { "grade": "C-", "errorPercent": 18.18 } }, - "secondsPer30s": { "cpu": 0.53, "accelerated": 0.51 } + "secondsPer30s": { "cpu": 0.5331437711036076, "accelerated": 0.5071851225697379 } }, "recommended": false, "supportsStreaming": true, @@ -1999,7 +1999,7 @@ "languages": ["en"], "benchmark": { "accuracy": { "en": { "grade": "C", "errorPercent": 14.13 } }, - "secondsPer30s": { "cpu": 0.73, "accelerated": 0.5 } + "secondsPer30s": { "cpu": 0.7260406582768635, "accelerated": 0.4964421644878372 } }, "recommended": false, "supportsStreaming": false, @@ -2021,7 +2021,7 @@ "en": { "grade": "B+", "errorPercent": 5.13 }, "zh": { "grade": "B-", "errorPercent": 9.23 } }, - "secondsPer30s": { "cpu": 19.11, "accelerated": 9.79 } + "secondsPer30s": { "cpu": 19.108280254777068, "accelerated": 9.787928221859707 } }, "recommended": false, "supportsStreaming": false, @@ -2040,7 +2040,7 @@ "languages": ["en"], "benchmark": { "accuracy": { "en": { "grade": "B", "errorPercent": 6.43 } }, - "secondsPer30s": { "cpu": 2.21, "accelerated": 1.11 } + "secondsPer30s": { "cpu": 2.210759027266028, "accelerated": 1.1051759071652238 } }, "recommended": false, "supportsStreaming": true, @@ -2111,7 +2111,7 @@ "sv": { "grade": "C", "errorPercent": 13.26 }, "uk": { "grade": "B", "errorPercent": 6.53 } }, - "secondsPer30s": { "cpu": 2.2, "accelerated": 1.2 } + "secondsPer30s": { "cpu": 2.2026431718061676, "accelerated": 1.1954572624028692 } }, "recommended": false, "supportsStreaming": false, @@ -2130,7 +2130,7 @@ "languages": ["en"], "benchmark": { "accuracy": { "en": { "grade": "B+", "errorPercent": 5.53 } }, - "secondsPer30s": { "cpu": 1.98, "accelerated": 1.05 } + "secondsPer30s": { "cpu": 1.9788918205804749, "accelerated": 1.048951048951049 } }, "recommended": false, "supportsStreaming": false, @@ -2149,7 +2149,7 @@ "languages": ["en"], "benchmark": { "accuracy": { "en": { "grade": "B+", "errorPercent": 5.61 } }, - "secondsPer30s": { "cpu": 3.36, "accelerated": 1.79 } + "secondsPer30s": { "cpu": 3.3613445378151257, "accelerated": 1.7873100983020553 } }, "recommended": false, "supportsStreaming": false, @@ -2220,7 +2220,7 @@ "sv": { "grade": "C-", "errorPercent": 16.42 }, "uk": { "grade": "B-", "errorPercent": 8.11 } }, - "secondsPer30s": { "cpu": 2.2, "accelerated": 1.2 } + "secondsPer30s": { "cpu": 2.2002200220022003, "accelerated": 1.2014417300760913 } }, "recommended": false, "supportsStreaming": false, @@ -2239,7 +2239,7 @@ "languages": ["en"], "benchmark": { "accuracy": { "en": { "grade": "A-", "errorPercent": 4.57 } }, - "secondsPer30s": { "cpu": 2.02, "accelerated": 1.11 } + "secondsPer30s": { "cpu": 2.0208824520040416, "accelerated": 1.107011070110701 } }, "recommended": false, "supportsStreaming": false, @@ -2258,7 +2258,7 @@ "languages": ["en"], "benchmark": { "accuracy": { "en": { "grade": "A-", "errorPercent": 4.45 } }, - "secondsPer30s": { "cpu": 3.49, "accelerated": 1.87 } + "secondsPer30s": { "cpu": 3.492433061699651, "accelerated": 1.8650917003419334 } }, "recommended": false, "supportsStreaming": false, @@ -2277,7 +2277,7 @@ "languages": ["en"], "benchmark": { "accuracy": { "en": { "grade": "A-", "errorPercent": 4.68 } }, - "secondsPer30s": { "cpu": 3.22, "accelerated": 1.76 } + "secondsPer30s": { "cpu": 3.2206119162640903, "accelerated": 1.7605633802816902 } }, "recommended": false, "supportsStreaming": false, @@ -2296,7 +2296,7 @@ "languages": ["en"], "benchmark": { "accuracy": { "en": { "grade": "A-", "errorPercent": 4.24 } }, - "secondsPer30s": { "cpu": 3.41, "accelerated": 1.82 } + "secondsPer30s": { "cpu": 3.4071550255536627, "accelerated": 1.8242626938279112 } }, "recommended": false, "supportsStreaming": false, @@ -2526,7 +2526,7 @@ "yo": { "grade": "F", "errorPercent": 103.28 }, "zh": { "grade": "F", "errorPercent": 36.21 } }, - "secondsPer30s": { "cpu": 1.55, "accelerated": 1.03 } + "secondsPer30s": { "cpu": 1.5519917227108124, "accelerated": 1.033947957952783 } }, "recommended": false, "supportsStreaming": false, @@ -2545,7 +2545,7 @@ "languages": ["en"], "benchmark": { "accuracy": { "en": { "grade": "B", "errorPercent": 7.6 } }, - "secondsPer30s": { "cpu": 1.46, "accelerated": 0.94 } + "secondsPer30s": { "cpu": 1.4563106796116503, "accelerated": 0.9370607527721381 } }, "recommended": false, "supportsStreaming": false, @@ -2747,7 +2747,7 @@ "yo": { "grade": "F", "errorPercent": 113.72 }, "zh": { "grade": "C-", "errorPercent": 19.32 } }, - "secondsPer30s": { "cpu": 31.25, "accelerated": 14.96 } + "secondsPer30s": { "cpu": 31.25, "accelerated": 14.962593516209477 } }, "recommended": false, "supportsStreaming": false, @@ -2949,7 +2949,7 @@ "yo": { "grade": "F", "errorPercent": 96 }, "zh": { "grade": "C", "errorPercent": 15.39 } }, - "secondsPer30s": { "cpu": 31.25, "accelerated": 14.93 } + "secondsPer30s": { "cpu": 31.25, "accelerated": 14.92537313432836 } }, "recommended": false, "supportsStreaming": false, @@ -2968,7 +2968,7 @@ "languages": ["en"], "benchmark": { "accuracy": { "en": { "grade": "A-", "errorPercent": 4.88 } }, - "secondsPer30s": { "cpu": 14.53, "accelerated": 6.81 } + "secondsPer30s": { "cpu": 14.527845036319613, "accelerated": 6.81044267877412 } }, "recommended": false, "supportsStreaming": false, @@ -2987,7 +2987,7 @@ "languages": ["en"], "benchmark": { "accuracy": { "en": { "grade": "B+", "errorPercent": 6.14 } }, - "secondsPer30s": { "cpu": 4.79, "accelerated": 2.4 } + "secondsPer30s": { "cpu": 4.7923322683706076, "accelerated": 2.404809619238477 } }, "recommended": false, "supportsStreaming": false, @@ -3189,7 +3189,7 @@ "yo": { "grade": "F", "errorPercent": 102.29 }, "zh": { "grade": "F", "errorPercent": 41.91 } }, - "secondsPer30s": { "cpu": 0.75, "accelerated": 0.7 } + "secondsPer30s": { "cpu": 0.7546220601182241, "accelerated": 0.696217219772569 } }, "recommended": false, "supportsStreaming": false, @@ -3208,7 +3208,7 @@ "languages": ["en"], "benchmark": { "accuracy": { "en": { "grade": "C+", "errorPercent": 10.72 } }, - "secondsPer30s": { "cpu": 0.73, "accelerated": 0.63 } + "secondsPer30s": { "cpu": 0.727802037845706, "accelerated": 0.6318449873631002 } }, "recommended": false, "supportsStreaming": false, diff --git a/apps/web/src/components/settings/SpeechModelComparison.tsx b/apps/web/src/components/settings/SpeechModelComparison.tsx index 4842c688b36d..724de8d68d34 100644 --- a/apps/web/src/components/settings/SpeechModelComparison.tsx +++ b/apps/web/src/components/settings/SpeechModelComparison.tsx @@ -51,12 +51,12 @@ export function ModelBenchmarks({ }: { model: EnvironmentSpeechModel; languages: readonly string[]; - tier: SpeechBenchmarkTier; + tier: SpeechBenchmarkTier | undefined; /** Plain facts, such as language count and size, shown after the scores. */ facts: readonly string[]; }) { const data = model.benchmark; - const seconds = data?.secondsPer30s[tier]; + const seconds = tier === undefined ? undefined : data?.secondsPer30s[tier]; const visible = !data ? [] : languages.length @@ -82,18 +82,23 @@ export function ModelBenchmarks({ ); })} - - Speed:{" "} - {tier === "cpu" && data && data.secondsPer30s.cpu === undefined ? ( - "update server" - ) : seconds == null ? ( - "not benchmarked" - ) : ( - <> - {seconds} s / 30 s - - )} - + {data ? ( + + Speed:{" "} + {seconds === undefined ? ( + "update server for this benchmark" + ) : seconds === null ? ( + "not benchmarked" + ) : ( + <> + + {Number(seconds.toFixed(2))} s + {" "} + / 30 s + + )} + + ) : null} {facts.map((fact) => ( {fact} ))} diff --git a/apps/web/src/components/settings/VoiceSettingsPanel.browser.test.tsx b/apps/web/src/components/settings/VoiceSettingsPanel.browser.test.tsx index c0107483461c..5c918f943008 100644 --- a/apps/web/src/components/settings/VoiceSettingsPanel.browser.test.tsx +++ b/apps/web/src/components/settings/VoiceSettingsPanel.browser.test.tsx @@ -148,7 +148,7 @@ it.each([{ cpu: null, accelerated: 2.1 }, { cpu: 5, accelerated: null }, { accel secondsPer30s, }, }; - const cpuBenchmark = `Speed: ${secondsPer30s.cpu === undefined ? "update server" : secondsPer30s.cpu === null ? "not benchmarked" : `${secondsPer30s.cpu} s / 30 s`}`; + const cpuBenchmark = `Speed: ${secondsPer30s.cpu === undefined ? "update server for this benchmark" : secondsPer30s.cpu === null ? "not benchmarked" : `${secondsPer30s.cpu} s / 30 s`}`; const gpuBenchmark = `Speed: ${secondsPer30s.accelerated === null ? "not benchmarked" : `${secondsPer30s.accelerated} s / 30 s`}`; const fetch = globalThis.fetch; using _network = vi.spyOn(globalThis, "fetch").mockImplementation((input, init) => { @@ -256,9 +256,9 @@ it("tests the selected model after download and preserves its transcript across supportsStreaming: false, supportsTranslation: false, acceleration: "cpu", + benchmarkTier: "cpu", modelUnloadTimeout: "never", gpuDevices: [], - benchmarkTier: "cpu", } satisfies EnvironmentSpeechStatus; let installed = false; const fetch = globalThis.fetch; @@ -290,7 +290,7 @@ it("tests the selected model after download and preserves its transcript across en: { grade: "A-", errorPercent: 4 }, fr: { grade: "B+", errorPercent: 5.5 }, }, - secondsPer30s: { cpu: 5, accelerated: 2.1 }, + secondsPer30s: { accelerated: 2.1, cpu: 5 }, }, } : {}), @@ -387,81 +387,128 @@ it("tests the selected model after download and preserves its transcript across ); }); -it("loads the models of a relay-connected destination", async () => { - const target = new RelayConnectionTarget({ - environmentId: EnvironmentId.make("voice-relay"), - label: "MacBook Pro", - }); - const prepared = { - environmentId: target.environmentId, - label: target.label, - httpBaseUrl: window.location.origin, - socketUrl: "ws://localhost", - httpAuthorization: { - _tag: "Dpop" as const, - accessToken: "stale-access-token", - expiresAtEpochMs: 4_102_444_800_000, - }, - target, - }; - const model: EnvironmentSpeechModel = { - id: "tiny", - name: "Tiny", - description: "", - size: 100, - languages: ["en"], - accuracy: 1, - speed: 1, - recommended: false, - supportsStreaming: false, - supportsTranslation: false, - supportsLanguageDetection: false, - active: false, - state: "downloadable", - }; - const status = { - supported: true, - state: "missing-model", - modelId: model.id, - model: model.name, - size: model.size, - supportsStreaming: false, - supportsTranslation: false, - acceleration: "cpu", - modelUnloadTimeout: "never", - gpuDevices: [], - benchmarkTier: "cpu", - } satisfies EnvironmentSpeechStatus; - const authorizations: Array = []; - const fetch = globalThis.fetch; - using _network = vi.spyOn(globalThis, "fetch").mockImplementation((input, init) => { - const url = new URL(input instanceof Request ? input.url : input, window.location.href); - if (url.pathname === "/api/voice/status") { - authorizations.push(new Headers(init?.headers).get("authorization")); - return Promise.resolve(Response.json(status)); +it.each([ + { tier: "cpu", legacy: false }, + { tier: "accelerated", legacy: false }, + { tier: "cpu", legacy: true }, +] as const)( + "loads relay models using the server tier $tier (legacy: $legacy)", + async ({ tier, legacy }) => { + const target = new RelayConnectionTarget({ + environmentId: EnvironmentId.make("voice-relay"), + label: "MacBook Pro", + }); + const prepared = { + environmentId: target.environmentId, + label: target.label, + httpBaseUrl: window.location.origin, + socketUrl: "ws://localhost", + httpAuthorization: { + _tag: "Dpop" as const, + accessToken: "stale-access-token", + expiresAtEpochMs: 4_102_444_800_000, + }, + target, + }; + const model = { + id: "gpu", + name: "GPU pick", + description: "", + size: 100, + languages: ["en"], + benchmark: { + accuracy: { en: { grade: "A", errorPercent: 4 } }, + secondsPer30s: { cpu: 20, accelerated: 1 }, + }, + accuracy: 1, + speed: 1, + recommended: false, + supportsStreaming: false, + supportsTranslation: false, + supportsLanguageDetection: false, + active: false, + state: "downloadable", + } satisfies EnvironmentSpeechModel; + const status = { + supported: true, + state: "missing-model", + modelId: model.id, + model: model.name, + size: model.size, + supportsStreaming: false, + supportsTranslation: false, + acceleration: "auto", + benchmarkTier: tier, + modelUnloadTimeout: "never", + gpuDevices: [{ id: "remote-gpu", name: "Remote GPU" }], + } satisfies EnvironmentSpeechStatus; + const cpuModel = { + ...model, + id: "cpu", + name: "CPU pick", + benchmark: { + accuracy: { en: { grade: "B+", errorPercent: 6 } }, + secondsPer30s: { cpu: 1, accelerated: 8 }, + }, + }; + const { benchmarkTier: _tier, ...legacyStatus } = status; + const models = [model, cpuModel]; + const authorizations: Array = []; + const fetch = globalThis.fetch; + using _network = vi.spyOn(globalThis, "fetch").mockImplementation((input, init) => { + const url = new URL(input instanceof Request ? input.url : input, window.location.href); + if (url.pathname === "/api/voice/status") { + authorizations.push(new Headers(init?.headers).get("authorization")); + return Promise.resolve( + Response.json(legacy ? { ...legacyStatus, acceleration: "cpu", gpuDevices: [] } : status), + ); + } + if (url.pathname === "/api/voice/models") + return Promise.resolve( + Response.json({ + models: legacy + ? models.map(({ benchmark, ...entry }) => ({ + ...entry, + benchmark: { + accuracy: benchmark.accuracy, + secondsPer30s: benchmark.secondsPer30s.accelerated, + }, + })) + : models, + }), + ); + return fetch(input, init); + }); + using notify = vi.spyOn(toastManager, "add").mockReturnValue("test"); + // Restored even when an assertion fails, unlike `withImplementation`. + using _destination = vi.mocked(useVoiceTranscriptionDestination).mockImplementation(() => ({ + environmentId: target.environmentId, + label: target.label, + grantId: "test", + prepared, + })); + await using screen = await render( + {}}> + + , + ); + await vi.waitFor(() => expect(authorizations.length + notify.mock.calls.length).not.toBe(0)); + expect(notify).not.toHaveBeenCalled(); + expect(authorizations).toEqual(["DPoP relay-access-token"]); + const region = screen.getByRole("region", { name: "Transcription models" }); + await vi.waitFor(() => expect(region.element().textContent).toContain("CPU pick")); + if (legacy) { + expect(region.element().textContent).toContain("update server for this benchmark"); + expect(region.element().textContent).not.toContain("Recommended"); + } else { + const winner = tier === "cpu" ? "CPU pick" : "GPU pick"; + await vi.waitFor(() => + expect(region.element().firstElementChild?.textContent).toContain(winner + "Recommended"), + ); + expect(region.element().textContent).toContain("Speed: 1 s / 30 s"); } - if (url.pathname === "/api/voice/models") - return Promise.resolve(Response.json({ models: [model] })); - return fetch(input, init); - }); - using notify = vi.spyOn(toastManager, "add").mockReturnValue("test"); - // Restored even when an assertion fails, unlike `withImplementation`. - using _destination = vi.mocked(useVoiceTranscriptionDestination).mockImplementation(() => ({ - environmentId: target.environmentId, - label: target.label, - grantId: "test", - prepared, - })); - await using screen = await render( - {}}> - - , - ); - await vi.waitFor(() => expect(authorizations.length + notify.mock.calls.length).not.toBe(0)); - expect(notify).not.toHaveBeenCalled(); - expect(authorizations).toEqual(["DPoP relay-access-token"]); - await expect.element(screen.getByText("Tiny", { exact: true })).toBeVisible(); -}); + }, +); it("recovers from a failed download progress poll without notifying, but reports a failed initial load", async () => { const target = new PrimaryConnectionTarget({ @@ -495,9 +542,9 @@ it("recovers from a failed download progress poll without notifying, but reports supportsStreaming: false, supportsTranslation: false, acceleration: "cpu", + benchmarkTier: "cpu", modelUnloadTimeout: "never", gpuDevices: [], - benchmarkTier: "cpu", }; const unavailable = () => new Response(null, { status: 503 }); const readModels = vi diff --git a/apps/web/src/components/settings/VoiceSettingsPanel.tsx b/apps/web/src/components/settings/VoiceSettingsPanel.tsx index 91d73a0d07f1..33db68b72cb8 100644 --- a/apps/web/src/components/settings/VoiceSettingsPanel.tsx +++ b/apps/web/src/components/settings/VoiceSettingsPanel.tsx @@ -30,7 +30,11 @@ import { } from "@t3tools/contracts"; import { createModelSelection, pickModelSelection } from "@t3tools/shared/model"; import { resolveSpeechPostProcessingModelSelection } from "@t3tools/shared/serverSettings"; -import { cloudSpeechLanguages } from "@t3tools/shared/speech"; +import { + cloudSpeechLanguages, + recommendSpeechModels, + type SpeechRecommendationRole, +} from "@t3tools/shared/speech"; import { ArrowDownUpIcon, AudioLinesIcon, @@ -176,7 +180,8 @@ const spellingsOf = (words: SpeechCustomWords) => type ModelCardProps = { readonly model: EnvironmentSpeechModel; readonly comparisonLanguages: readonly string[]; - readonly benchmarkTier: SpeechBenchmarkTier; + readonly recommendation: SpeechRecommendationRole | undefined; + readonly benchmarkTier: SpeechBenchmarkTier | undefined; readonly busy: boolean; readonly canCancel: boolean; readonly onDownload: () => void; @@ -217,11 +222,23 @@ function ModelCard(props: ModelCardProps) {
{model.name} - {model.recommended ? ( + {props.recommendation ? ( } - label="Recommended" - tooltip="A good default pick for the languages it covers." + label={ + props.recommendation === "recommended" + ? "Recommended" + : props.recommendation === "faster" + ? "Faster" + : "More accurate" + } + tooltip={ + props.recommendation === "recommended" + ? "Balanced accuracy and speed for your selected languages on Handy’s reference benchmarks." + : props.recommendation === "faster" + ? "Quicker than Recommended on this reference tier, with useful accuracy." + : "Higher accuracy with a longer reference processing budget for your selected languages." + } /> ) : null} {model.supportsStreaming ? ( @@ -871,14 +888,20 @@ function SpeechModelBrowser(props: { selectedLanguages.length === 0 ? "All languages" : selectedLanguages.map(languageLabel).join(", "); - const sortedModels = filterSpeechModels(models, { - search, - languages: selectedLanguages, - downloadedOnly, - sort, - accuracyLanguage, - benchmarkTier: status?.supported ? status.benchmarkTier : "accelerated", - }); + const benchmarkTier = status?.supported ? status.benchmarkTier : undefined; + const recommendations = recommendSpeechModels(models, selectedLanguages, benchmarkTier); + const sortedModels = filterSpeechModels( + models, + { + search, + languages: selectedLanguages, + downloadedOnly, + sort, + accuracyLanguage, + benchmarkTier, + }, + recommendations, + ); const activeModel = models.find((model) => model.active); const renderedModels = activeModel && !sortedModels.includes(activeModel) @@ -898,7 +921,7 @@ function SpeechModelBrowser(props: {
@@ -1018,6 +1041,7 @@ function SpeechModelBrowser(props: { busy: controlsDisabled, canCancel, comparisonLanguages: selectedLanguages, + recommendation: recommendations.get(model.id), benchmarkTier: status.benchmarkTier, onDownload: () => void run( diff --git a/apps/web/src/components/settings/speechModelBrowser.test.ts b/apps/web/src/components/settings/speechModelBrowser.test.ts index 890d43cee048..9a3f969b60da 100644 --- a/apps/web/src/components/settings/speechModelBrowser.test.ts +++ b/apps/web/src/components/settings/speechModelBrowser.test.ts @@ -1,5 +1,6 @@ import type { EnvironmentSpeechModel } from "@t3tools/contracts"; import { expect, it } from "vite-plus/test"; +import { recommendSpeechModels } from "@t3tools/shared/speech"; import { filterSpeechModels } from "./speechModelBrowser"; @@ -31,9 +32,9 @@ const models: readonly EnvironmentSpeechModel[] = [ benchmark: { accuracy: { en: { grade: "A", errorPercent: 3.8 }, - fr: { grade: "B", errorPercent: 8 }, + fr: { grade: "B", errorPercent: 7 }, }, - secondsPer30s: { cpu: 2, accelerated: 2 }, + secondsPer30s: { accelerated: 2, cpu: 1 }, }, }, { @@ -47,7 +48,7 @@ const models: readonly EnvironmentSpeechModel[] = [ en: { grade: "A", errorPercent: 3.2 }, fr: { grade: "B", errorPercent: 9 }, }, - secondsPer30s: { cpu: 1, accelerated: 1 }, + secondsPer30s: { accelerated: 1, cpu: 3 }, }, }, { @@ -58,7 +59,7 @@ const models: readonly EnvironmentSpeechModel[] = [ active: false, state: "verifying", languages: ["en"], - benchmark: { accuracy: {}, secondsPer30s: { cpu: null, accelerated: null } }, + benchmark: { accuracy: {}, secondsPer30s: { accelerated: null, cpu: null } }, }, ]; @@ -100,3 +101,58 @@ it("combines text, all selected languages, and completed downloads without retai ).toEqual(["fast"]); expect(filterSpeechModels(models, { ...options, search: "small" })).toEqual([]); }); + +it("ranks language recommendations before the rest without changing explicit sorts or search badges", () => { + const catalog = models.map((model) => ({ + ...model, + active: false, + state: "downloadable" as const, + })); + const options = { + search: "", + languages: ["en"], + downloadedOnly: false, + sort: "recommended", + accuracyLanguage: "en", + benchmarkTier: "accelerated", + } as const; + expect(filterSpeechModels(catalog, options).map(({ id }) => id)).toEqual([ + "fast", + "active", + "small", + "pending", + ]); + expect( + filterSpeechModels(catalog, { ...options, languages: ["en", "fr"] }).map(({ id }) => id), + ).toEqual(["small", "fast", "active"]); + expect(filterSpeechModels(catalog, { ...options, languages: [] }).map(({ id }) => id)).toEqual( + catalog.map(({ id }) => id), + ); + expect(filterSpeechModels(catalog, { ...options, sort: "size" }).map(({ id }) => id)).toEqual([ + "small", + "fast", + "active", + "pending", + ]); + expect( + filterSpeechModels(catalog, { ...options, sort: "speed", benchmarkTier: "cpu" }).map( + ({ id }) => id, + ), + ).toEqual(["small", "fast", "active", "pending"]); + expect( + filterSpeechModels(catalog, { ...options, sort: "accuracy", languages: ["en", "fr"] }).map( + ({ id }) => id, + ), + ).toEqual(["fast", "small", "active"]); + expect( + filterSpeechModels(catalog, { ...options, sort: "speed", languages: ["en", "fr"] }).map( + ({ id }) => id, + ), + ).toEqual(["fast", "small", "active"]); + expect(filterSpeechModels(catalog, { ...options, search: "small" }).map(({ id }) => id)).toEqual([ + "small", + ]); + expect( + recommendSpeechModels(catalog, options.languages, options.benchmarkTier).has("small"), + ).toBe(false); +}); diff --git a/apps/web/src/components/settings/speechModelBrowser.ts b/apps/web/src/components/settings/speechModelBrowser.ts index e08fcde0ae94..f0acb6a45e1c 100644 --- a/apps/web/src/components/settings/speechModelBrowser.ts +++ b/apps/web/src/components/settings/speechModelBrowser.ts @@ -1,4 +1,5 @@ import type { EnvironmentSpeechModel, SpeechBenchmarkTier } from "@t3tools/contracts"; +import { recommendSpeechModels } from "@t3tools/shared/speech"; export type SpeechModelSort = "recommended" | "size" | "accuracy" | "speed"; @@ -6,7 +7,7 @@ const modelSortOrder = (model: EnvironmentSpeechModel) => { if (model.active) return 0; if (model.state === "installed") return 1; if (model.state === "downloading" || model.state === "verifying") return 2; - return model.recommended ? 3 : 4; + return 3; }; export function filterSpeechModels( @@ -17,10 +18,12 @@ export function filterSpeechModels( readonly downloadedOnly: boolean; readonly sort: SpeechModelSort; readonly accuracyLanguage: string; - readonly benchmarkTier: SpeechBenchmarkTier; + readonly benchmarkTier: SpeechBenchmarkTier | undefined; }, + recommendations = recommendSpeechModels(models, options.languages, options.benchmarkTier), ) { const query = options.search.trim().toLocaleLowerCase(); + const ranks = new Map([...recommendations.keys()].map((id, index) => [id, index])); const score = (model: EnvironmentSpeechModel) => { switch (options.sort) { case "size": @@ -28,9 +31,11 @@ export function filterSpeechModels( case "accuracy": return model.benchmark?.accuracy[options.accuracyLanguage]?.errorPercent ?? Infinity; case "speed": - return model.benchmark?.secondsPer30s[options.benchmarkTier] ?? Infinity; + return options.benchmarkTier === undefined + ? Infinity + : (model.benchmark?.secondsPer30s[options.benchmarkTier] ?? Infinity); case "recommended": - return modelSortOrder(model); + return modelSortOrder(model) * 4 + (ranks.get(model.id) ?? 3); } }; return models diff --git a/apps/web/src/speech/useEnvironmentSpeechInput.browser.test.tsx b/apps/web/src/speech/useEnvironmentSpeechInput.browser.test.tsx index 16bf2d577ac3..c0fde564ce97 100644 --- a/apps/web/src/speech/useEnvironmentSpeechInput.browser.test.tsx +++ b/apps/web/src/speech/useEnvironmentSpeechInput.browser.test.tsx @@ -42,6 +42,7 @@ const mocks = vi.hoisted(() => ({ primaryEnvironmentId: "primary-env", statusRequests: [] as string[], statusUnavailable: false, + statusTier: "accelerated" as "cpu" | "accelerated", modelState: "ready" as "ready" | "missing-model", statusModelId: "test-model", models: [] as EnvironmentSpeechModel[], @@ -134,9 +135,9 @@ vi.mock("@t3tools/client-runtime/voice-input", async (importOriginal) => ({ supportsStreaming: false, supportsTranslation: false, acceleration: "auto", + benchmarkTier: mocks.statusTier, modelUnloadTimeout: "min_15", gpuDevices: [], - benchmarkTier: "cpu", }; }), downloadEnvironmentSpeechModel: (_prepared: PreparedConnection, modelId: string) => @@ -151,10 +152,14 @@ vi.mock("@t3tools/client-runtime/voice-input", async (importOriginal) => ({ mocks.statusModelId = modelId; return { models: mocks.models }; }), - getEnvironmentSpeechModels: vi.fn(() => + getEnvironmentSpeechModels: vi.fn((_prepared: PreparedConnection, includeBenchmarks = false) => Effect.sync(() => { if (mocks.catalogOffline) throw new Error("Catalog offline"); - return { models: mocks.models }; + return { + models: mocks.models.map(({ benchmark, ...model }) => + includeBenchmarks ? { ...model, ...(benchmark ? { benchmark } : {}) } : model, + ), + }; }), ), postProcessEnvironmentTranscript: ( @@ -225,6 +230,7 @@ function setup(options: { readonly destination?: string | null } = {}) { mocks.statusRequests = []; mocks.statusUnavailable = false; mocks.modelState = "ready"; + mocks.statusTier = "accelerated"; mocks.statusModelId = "test-model"; mocks.models = []; mocks.catalogOffline = false; @@ -491,6 +497,7 @@ function catalogModel( id: string, languages: readonly string[], recommended: boolean, + errorPercent = 4, ): EnvironmentSpeechModel { return { id, @@ -501,6 +508,12 @@ function catalogModel( accuracy: 0, speed: 0, recommended, + benchmark: { + accuracy: Object.fromEntries( + languages.map((language) => [language, { grade: "A", errorPercent }]), + ), + secondsPer30s: { accelerated: 2, cpu: 3 }, + }, supportsStreaming: false, supportsLanguageDetection: languages.length > 1, supportsTranslation: false, @@ -510,26 +523,30 @@ function catalogModel( } it.each([ - ["the browser prefers German", ["de-DE"], undefined, "auto"], - ["the desktop exposes no locale methods", ["de-DE"], {}, "auto"], + ["the browser prefers German", ["de-DE"], undefined, "auto", "accelerated"], + ["the remote environment uses CPU", ["de-DE"], undefined, "auto", "cpu"], + ["the desktop exposes no locale methods", ["de-DE"], {}, "auto", "accelerated"], [ "an older preload exposes only the OS locale", ["en-US"], { getSystemLocale: () => "de-DE" }, "auto", + "accelerated", ], [ "the desktop OS prefers German", ["en-US"], { getPreferredSystemLanguages: () => ["de-DE"] }, "auto", + "accelerated", ], - ["German is the chosen Voice language", ["en-US"], undefined, "de"], + ["German is the chosen Voice language", ["en-US"], undefined, "de", "accelerated"], ])( "offers and downloads a German-capable model when %s", - async (_, languages, bridge, speechLanguage) => { + async (_, languages, bridge, speechLanguage, tier) => { setup({ destination: "env-a" }); mocks.settings = { speechLanguage }; + mocks.statusTier = tier as "cpu" | "accelerated"; using _languages = vi.spyOn(navigator, "languages", "get").mockReturnValue(languages); using _bridge = stubGlobal("desktopBridge", bridge); const englishDefault = "handy-computer/parakeet-unified-en-0.6b-gguf"; @@ -538,16 +555,24 @@ it.each([ mocks.statusModelId = englishDefault; mocks.models = [ { ...catalogModel(englishDefault, ["en"], true), active: true }, - catalogModel(german, ["en", "de", "fr"], true), catalogModel("handy-computer/canary-180m-flash-gguf", ["en", "de", "es", "fr"], true), + { + ...catalogModel(german, ["en", "de", "fr"], false, 2), + benchmark: { + accuracy: { de: { grade: "A", errorPercent: 2 } }, + secondsPer30s: { cpu: 20, accelerated: 2 }, + }, + }, ]; mocks.download.mockResolvedValue(undefined); await using _screen = await render(); await act(() => mocks.voice.start()); expect(mocks.voice.setup.open).toBe(true); await act(() => mocks.voice.setup.download()); - expect(mocks.download).toHaveBeenCalledExactlyOnceWith(german); - expect(mocks.voice.setup.model?.id).toBe(german); + const expected = tier === "cpu" ? "handy-computer/canary-180m-flash-gguf" : german; + expect(mocks.download).toHaveBeenCalledExactlyOnceWith(expected); + expect(mocks.voice.setup.model?.id).toBe(expected); + expect(mocks.voice.setup.model?.recommended).toBe(true); }, ); @@ -607,6 +632,7 @@ it.each([true, false])( mocks.models.push(catalogModel("german", ["de"], true)); // Another client can finish setup while the catalog is offline. mocks.modelState = "ready"; + mocks.statusTier = "accelerated"; await userEvent.click(retry); await expect.element(wizard.getByRole("heading", { name: "german" })).toBeVisible(); await expect.element(download).toBeEnabled(); @@ -641,6 +667,7 @@ it.each([ mocks.download.mockImplementation(async () => { mocks.models = [mocks.models[0]!, { ...mocks.models[1]!, state: landedState }]; mocks.modelState = "ready"; + mocks.statusTier = "accelerated"; }); await using _screen = await render(); await act(() => mocks.voice.start()); diff --git a/apps/web/src/speech/useEnvironmentSpeechInput.ts b/apps/web/src/speech/useEnvironmentSpeechInput.ts index cb9b77799874..3a7b131fc5db 100644 --- a/apps/web/src/speech/useEnvironmentSpeechInput.ts +++ b/apps/web/src/speech/useEnvironmentSpeechInput.ts @@ -14,6 +14,7 @@ import type { EnvironmentSpeechModel, EnvironmentSpeechStatus, ProjectId, + SpeechBenchmarkTier, } from "@t3tools/contracts"; import { resolveProjectSettings } from "@t3tools/shared/projectSettings"; import { chooseSetupSpeechModel } from "@t3tools/shared/speech"; @@ -253,7 +254,11 @@ export function useEnvironmentSpeechInput(input: HookInput) { .then((result) => { if (disposed) return; const model = result.models.find((candidate) => candidate.id === setupModelId) ?? null; - if (model) setSetup((current) => ({ ...current, model })); + if (model) + setSetup((current) => ({ + ...current, + model: { ...model, recommended: current.model?.recommended ?? false }, + })); }) .catch(() => undefined) .finally(() => { @@ -347,20 +352,26 @@ export function useEnvironmentSpeechInput(input: HookInput) { session.adopt(createTarget()); }, [session, input.ownerKey, createTarget]); const loadSetupCatalog = useStableCallback( - async (connection: PreparedConnection, selectedModelId: string, request: number) => { + async ( + connection: PreparedConnection, + selectedModelId: string, + benchmarkTier: SpeechBenchmarkTier, + request: number, + ) => { setSetup({ ...INITIAL_SETUP, open: true }); - const catalog = await runEnvironmentSpeech(getEnvironmentSpeechModels(connection)).catch( - () => null, - ); + const catalog = await runEnvironmentSpeech( + getEnvironmentSpeechModels(connection, true), + ).catch(() => null); if (request !== startRequestRef.current) return; const choice = chooseSetupSpeechModel(catalog?.models ?? [], { selectedModelId, intent: latestRef.current.clientSettings.speechLanguage, preferred: preferredSpeechLanguages(), + benchmarkTier, }); setSetup((current) => ({ ...current, - model: choice?.model ?? null, + model: choice ? { ...choice.model, recommended: choice.recommended } : null, language: choice?.language ?? null, catalogFailed: catalog === null, error: choice @@ -410,7 +421,7 @@ export function useEnvironmentSpeechInput(input: HookInput) { setStatus({ prepared, value: latestStatus }); setQueuedStart(null); if (latestStatus.supported && latestStatus.state === "missing-model") { - return loadSetupCatalog(prepared, latestStatus.modelId, request); + return loadSetupCatalog(prepared, latestStatus.modelId, latestStatus.benchmarkTier, request); } if (!latestStatus.supported) { toastManager.add({ @@ -505,7 +516,13 @@ export function useEnvironmentSpeechInput(input: HookInput) { setOpen: (open: boolean) => setSetup((current) => ({ ...current, open })), retryCatalog: setup.open && setup.catalogFailed && prepared && currentStatus?.supported - ? () => loadSetupCatalog(prepared, currentStatus.modelId, ++startRequestRef.current) + ? () => + loadSetupCatalog( + prepared, + currentStatus.modelId, + currentStatus.benchmarkTier, + ++startRequestRef.current, + ) : null, download: downloadSetupModel, cancelDownload: cancelSetupDownload, diff --git a/docs/user/voice-input.md b/docs/user/voice-input.md index 4da5e0b750a8..31b73218bccc 100644 --- a/docs/user/voice-input.md +++ b/docs/user/voice-input.md @@ -66,8 +66,10 @@ format, such as Core ML, ONNX, or MLX builds of the same model, can’t be used. Select the languages you dictate in to compare models that support all of them. Accuracy shows how often the model got words or characters wrong in each -language; speed is the time to transcribe 30 seconds on a reference GPU. Choose -**All languages** to browse the full catalog. Filtering does not switch your model. +language; speed is the time to transcribe 30 seconds on a reference CPU or GPU, +matching the selected environment's transcription backend. Recommendations use +the same reference tier for every selected language. Choose **All languages** to +browse without a language preference. Filtering does not switch your model. **Advanced** controls GPU or CPU use and when an idle model is unloaded. With hardware set to **Auto**, a recording that fails on the GPU is retried once on that same diff --git a/packages/shared/src/speech.test.ts b/packages/shared/src/speech.test.ts index 6d1829fd67a9..3d02b3d08ce4 100644 --- a/packages/shared/src/speech.test.ts +++ b/packages/shared/src/speech.test.ts @@ -3,6 +3,7 @@ import { DEFAULT_SPEECH_TRANSCRIPTION_OPTIONS, SPEECH_MAX_OPTIONS_BYTES } from " import { chooseSetupSpeechModel, + recommendSpeechModels, decodeSpeechPcmRequest, encodeSpeechPcmRequest, resolveSpeechVocabulary, @@ -79,7 +80,18 @@ describe("chooseSetupSpeechModel", () => { languages: string[], supportsLanguageDetection: boolean, recommended: boolean, - ) => ({ id, languages, supportsLanguageDetection, recommended }); + ) => ({ + id, + languages, + supportsLanguageDetection, + recommended, + benchmark: { + accuracy: Object.fromEntries( + languages.map((language) => [language, { errorPercent: recommended ? 4 : 10 }]), + ), + secondsPer30s: { accelerated: 2, cpu: 3 }, + }, + }); const catalog = [ model("unrecommended", ["en", "de", "es"], true, false), model("english", ["en"], false, true), @@ -146,7 +158,173 @@ describe("chooseSetupSpeechModel", () => { undefined, ], ] as const)("%s", (_, selectedModelId, intent, preferred, expected) => { - const choice = chooseSetupSpeechModel(catalog, { selectedModelId, intent, preferred }); + const choice = chooseSetupSpeechModel(catalog, { + selectedModelId, + intent, + preferred, + benchmarkTier: "accelerated", + }); expect(choice && { id: choice.model.id, language: choice.language }).toEqual(expected); }); + + it("keeps suitable selections and preference order, and falls back safely without measurements", () => { + const best = { + ...catalog[0]!, + benchmark: { + accuracy: { de: { errorPercent: 1 } }, + secondsPer30s: { accelerated: 1, cpu: 2 }, + }, + }; + expect( + chooseSetupSpeechModel([...catalog, { ...best, id: "best" }], { + benchmarkTier: "accelerated", + selectedModelId: "gone", + intent: "auto", + preferred: ["de", "en"], + }), + ).toMatchObject({ model: { id: "best" }, language: "de", recommended: true }); + expect( + chooseSetupSpeechModel([...catalog, { ...best, id: "best" }], { + benchmarkTier: "accelerated", + selectedModelId: "detecting", + intent: "auto", + preferred: ["de", "en"], + }), + ).toMatchObject({ model: { id: "detecting" }, language: "de", recommended: false }); + const unmeasured = catalog.map(({ benchmark: _benchmark, ...model }) => model); + expect( + chooseSetupSpeechModel(unmeasured, { + benchmarkTier: "accelerated", + selectedModelId: "gone", + intent: "auto", + preferred: ["de", "en"], + }), + ).toMatchObject({ model: { id: "unrecommended" }, language: "de", recommended: false }); + expect( + chooseSetupSpeechModel([], { + benchmarkTier: "accelerated", + selectedModelId: "gone", + intent: "auto", + preferred: [], + }), + ).toBeUndefined(); + }); +}); + +describe("recommendSpeechModels", () => { + const model = ( + id: string, + errors: Record, + wait: number | null, + cpu: number | null, + ) => ({ + id, + languages: Object.keys(errors), + benchmark: { + accuracy: Object.fromEntries( + Object.entries(errors).map(([language, errorPercent]) => [language, { errorPercent }]), + ), + secondsPer30s: { accelerated: wait, cpu }, + }, + }); + const models = [ + model("balanced", { en: 4, de: 16 }, 2, 7), + model("fast", { en: 7, de: 7 }, 1, 3), + model("accurate", { en: 2, de: 2 }, 8, 20), + model("incomplete", { en: 1 }, 1, 1), + ]; + + it("balances all requested languages and assigns each model its first role", () => { + expect([...recommendSpeechModels(models.slice(0, 3), ["en"], "accelerated")]).toEqual([ + ["balanced", "recommended"], + ["fast", "faster"], + ["accurate", "accurate"], + ]); + expect([...recommendSpeechModels(models, ["en", "de", "de"], "accelerated")]).toEqual([ + ["fast", "recommended"], + ["accurate", "accurate"], + ]); + expect([...recommendSpeechModels(models.slice(0, 3), ["en"], "cpu")]).toEqual([ + ["fast", "recommended"], + ["balanced", "accurate"], + ]); + expect([...recommendSpeechModels(models, ["en", "de"], "cpu")]).toEqual([ + ["fast", "recommended"], + ]); + }); + + it("offers alternatives only when they improve on the balanced pick on the same tier", () => { + expect([ + ...recommendSpeechModels( + [model("cpu-fast-gpu-slow", { en: 3 }, 4, 1), model("balanced", { en: 3.2 }, 1, 8)], + ["en"], + "accelerated", + ), + ]).toEqual([ + ["balanced", "recommended"], + ["cpu-fast-gpu-slow", "accurate"], + ]); + expect([ + ...recommendSpeechModels( + [model("equal-accuracy", { en: 4 }, 8, 20), model("balanced", { en: 4 }, 2, 20)], + ["en"], + "accelerated", + ), + ]).toEqual([["balanced", "recommended"]]); + expect([ + ...recommendSpeechModels( + [model("balanced", { en: 4 }, 12, 20), model("outside-budget", { en: 2 }, 30, 40)], + ["en"], + "accelerated", + ), + ]).toEqual([["balanced", "recommended"]]); + }); + + it("does not invent measurements, preferences, or a model covering missing languages", () => { + expect(recommendSpeechModels(models, [], "accelerated").size).toBe(0); + expect(recommendSpeechModels(models, ["ja"], "accelerated").size).toBe(0); + expect( + recommendSpeechModels( + [ + model("missing-speed", { en: 1, de: 1 }, null, 1), + { ...model("missing-accuracy", { en: 1 }, 1, 1), languages: ["en", "de"] }, + ], + ["en", "de"], + "accelerated", + ).size, + ).toBe(0); + expect([ + ...recommendSpeechModels([model("no-cpu", { en: 1 }, 1, null)], ["en"], "accelerated"), + ]).toEqual([["no-cpu", "recommended"]]); + expect(recommendSpeechModels([model("no-cpu", { en: 1 }, 1, null)], ["en"], "cpu").size).toBe( + 0, + ); + expect([ + ...recommendSpeechModels([model("cpu-only", { en: 1 }, null, 2)], ["en"], "cpu"), + ]).toEqual([["cpu-only", "recommended"]]); + }); + + it("prefers useful accuracy before speed and relaxes the wait budget before quality", () => { + expect([ + ...recommendSpeechModels( + [model("poor", { en: 25 }, 1, 1), model("slow", { en: 4 }, 12, 20)], + ["en"], + "accelerated", + ), + ]).toEqual([["slow", "recommended"]]); + expect([ + ...recommendSpeechModels( + [model("worse", { en: 30, de: 40 }, 1, 1), model("least-poor", { en: 29, de: 30 }, 20, 40)], + ["en", "de"], + "accelerated", + ), + ]).toEqual([["least-poor", "recommended"]]); + expect([ + ...recommendSpeechModels( + [model("zero", { en: 0, de: 0 }, 1, 1)], + ["en", "de"], + "accelerated", + ), + ]).toEqual([["zero", "recommended"]]); + }); }); diff --git a/packages/shared/src/speech.ts b/packages/shared/src/speech.ts index c5ed9ab14ea0..94c2eb316faa 100644 --- a/packages/shared/src/speech.ts +++ b/packages/shared/src/speech.ts @@ -3,13 +3,102 @@ import { type CloudSpeechProvider, SPEECH_MAX_OPTIONS_BYTES, type SpeechCustomWords, + type SpeechBenchmarkTier, SpeechTranscriptionOptions, } from "@t3tools/contracts"; import * as Schema from "effect/Schema"; +import recommendationPolicy from "./speechRecommendationPolicy.json" with { type: "json" }; const decodeOptions = Schema.decodeUnknownSync(Schema.fromJsonString(SpeechTranscriptionOptions)); const encodeOptions = Schema.encodeSync(Schema.fromJsonString(SpeechTranscriptionOptions)); +export type SpeechRecommendationRole = "recommended" | "faster" | "accurate"; +type RecommendationModel = { + readonly id: string; + readonly languages: readonly string[]; + readonly benchmark?: { + readonly accuracy: Readonly>; + readonly secondsPer30s: { + readonly cpu?: number | null; + readonly accelerated: number | null; + }; + }; +}; + +/** Reference accuracy/speed picks; no preference or incomplete measurements get no badge. */ +export function recommendSpeechModels( + models: readonly RecommendationModel[], + languages: readonly string[], + tier: SpeechBenchmarkTier | undefined, +) { + const wanted = [...new Set(languages)]; + const roles = new Map(); + if (wanted.length === 0 || tier === undefined) return roles; + const policy = recommendationPolicy; + const scored = models.flatMap((model) => { + if (!wanted.every((language) => model.languages.includes(language))) return []; + const errors = wanted.map((language) => model.benchmark?.accuracy[language]?.errorPercent); + const wait = model.benchmark?.secondsPer30s[tier]; + if ( + wait == null || + !Number.isFinite(wait) || + wait < 0 || + errors.some((error) => error === undefined || !Number.isFinite(error) || error < 0) + ) + return []; + const measured = errors as number[]; + const error = Math.exp( + measured.reduce((sum, value) => sum + Math.log(value), 0) / measured.length, + ); + return [ + { + id: model.id, + error, + worst: Math.max(...measured), + wait, + cost: error + policy.waitWeight * Math.max(0, wait - policy.freeWaitSeconds), + }, + ]; + }); + if (scored.length === 0) return roles; + const useful = scored.filter((model) => model.worst < policy.maxLanguageErrorPercent); + const pool = useful.length ? useful : scored; + const lowest = (items: typeof scored, score: (item: (typeof scored)[number]) => number) => + items.reduce<(typeof scored)[number] | undefined>( + (best, item) => (best === undefined || score(item) < score(best) ? item : best), + undefined, + ); + const withinBudget = pool.filter((model) => model.wait <= policy.overallMaxWaitSeconds); + const best = ( + useful.length + ? lowest(withinBudget.length ? withinBudget : pool, (model) => model.cost) + : lowest(pool, (model) => model.worst + model.error / 1000) + )!; + const quicker = pool.filter((model) => model.wait < best.wait); + const fast = useful.length + ? (lowest( + quicker.filter((model) => model.wait <= policy.fastMaxWaitSeconds), + (model) => model.error, + ) ?? lowest(quicker, (model) => model.wait + model.error / 1000)) + : undefined; + const accurate = useful.length + ? lowest( + pool.filter( + (model) => model.error < best.error && model.wait <= policy.accurateMaxWaitSeconds, + ), + (model) => model.error, + ) + : undefined; + for (const [model, role] of [ + [best, "recommended"], + [fast, "faster"], + [accurate, "accurate"], + ] as const) { + if (model && !roles.has(model.id)) roles.set(model.id, role); + } + return roles; +} + export function cloudSpeechDisclosure(provider: CloudSpeechProvider, environment: string) { return provider === "openrouter" ? `After you stop, ${environment} sends the recording to OpenRouter. OpenRouter chooses who runs your model. T3 requests zero data retention; your OpenRouter account may allow safety retention.` @@ -37,16 +126,13 @@ export function effectiveSpeechLanguage( } /** - * The model first-run setup offers: the selected one, else a recommended one, else any that the + * The model first-run setup offers: the selected one, else the benchmark pick, else any that the * server would really transcribe the person's language with. Without a language hint, * offer only the selected model, without a recommendation. */ export function chooseSetupSpeechModel< - Model extends { - readonly id: string; - readonly languages: readonly string[]; + Model extends RecommendationModel & { readonly supportsLanguageDetection: boolean; - readonly recommended: boolean; }, >( models: readonly Model[], @@ -54,22 +140,26 @@ export function chooseSetupSpeechModel< readonly selectedModelId: string; readonly intent: string; readonly preferred: readonly string[]; + readonly benchmarkTier: SpeechBenchmarkTier | undefined; }, ) { if (input.intent === "auto" && input.preferred.length === 0) { const model = models.find(({ id }) => id === input.selectedModelId); - return model && { model, language: null }; + return model && { model, language: null, recommended: false }; } for (const language of input.intent === "auto" ? input.preferred : [input.intent]) { const capable = models.filter((model) => { const effective = effectiveSpeechLanguage(model, input.intent); return effective === language || (effective === "auto" && model.languages.includes(language)); }); + const recommendedId = recommendSpeechModels(capable, [language], input.benchmarkTier) + .keys() + .next().value; const model = capable.find(({ id }) => id === input.selectedModelId) ?? - capable.find(({ recommended }) => recommended) ?? + capable.find(({ id }) => id === recommendedId) ?? capable[0]; - if (model) return { model, language }; + if (model) return { model, language, recommended: model.id === recommendedId }; } return undefined; } diff --git a/packages/shared/src/speechRecommendationPolicy.json b/packages/shared/src/speechRecommendationPolicy.json new file mode 100644 index 000000000000..108de86b4383 --- /dev/null +++ b/packages/shared/src/speechRecommendationPolicy.json @@ -0,0 +1,11 @@ +{ + "dictationSeconds": 30, + "freeWaitSeconds": 3, + "waitWeight": 0.5, + "overallMaxWaitSeconds": 5, + "maxLanguageErrorPercent": 20, + "noteMinErrorPercent": 15, + "experimentalMaxErrorPercent": 30, + "accurateMaxWaitSeconds": 10, + "fastMaxWaitSeconds": 4 +} From 38f7761148fae79048dac35663d9035918e192c5 Mon Sep 17 00:00:00 2001 From: Simone Date: Tue, 17 Nov 2026 19:08:20 +0100 Subject: [PATCH 070/133] fix(shared): keep literal quotes in POSIX PATH directories (#38238) Co-authored-by: Simone <185146821+Lucenx9@users.noreply.github.com> Co-authored-by: Julius Marminge --- .../provider/AntigravityInstallation.test.ts | 7 ++- .../src/provider/AntigravityInstallation.ts | 3 +- packages/shared/src/shell.test.ts | 44 ++++++++++--------- packages/shared/src/shell.ts | 15 ++++--- 4 files changed, 38 insertions(+), 31 deletions(-) diff --git a/apps/server/src/provider/AntigravityInstallation.test.ts b/apps/server/src/provider/AntigravityInstallation.test.ts index 8de41a4b3b36..41b3675ff936 100644 --- a/apps/server/src/provider/AntigravityInstallation.test.ts +++ b/apps/server/src/provider/AntigravityInstallation.test.ts @@ -1066,8 +1066,11 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("Antigravity inst const baseDir = yield* fs .makeTempDirectoryScoped({ prefix: "t3-agy-cli-test-" }) .pipe(Effect.flatMap((directory) => fs.realPath(directory))); - const cliDirectory = path.join(baseDir, "cli"); + const cliDirectory = path.join(baseDir, 'cli" '); yield* fs.makeDirectory(cliDirectory); + const siblingDirectory = path.join(baseDir, 'cli"'); + yield* fs.makeDirectory(siblingDirectory); + yield* fs.writeFileString(path.join(siblingDirectory, "agy"), "other cli", { mode: 0o755 }); const cli = path.join(cliDirectory, "antigravity"); const alias = path.join(cliDirectory, "agy"); const other = path.join(cliDirectory, "custom-acp"); @@ -1115,7 +1118,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("Antigravity inst const windowsDirectory = path.join(baseDir, `windows-${name}`); yield* fs.makeDirectory(windowsDirectory); yield* fs.writeFileString(path.join(windowsDirectory, name), "cli"); - const selected = yield* windows.resolve("agy", { PATH: windowsDirectory }); + const selected = yield* windows.resolve("agy", { PATH: `"${windowsDirectory}"` }); expect(selected.harnessPath).toBeNull(); expect((yield* fs.realPath(selected.executablePath)).toLowerCase()).toBe( (yield* fs.realPath(path.join(windowsDirectory, name))).toLowerCase(), diff --git a/apps/server/src/provider/AntigravityInstallation.ts b/apps/server/src/provider/AntigravityInstallation.ts index f16849e2f56e..b7c61d7a0bcf 100644 --- a/apps/server/src/provider/AntigravityInstallation.ts +++ b/apps/server/src/provider/AntigravityInstallation.ts @@ -367,8 +367,7 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma ? Object.entries(processEnvironment).findLast(([key]) => key.toUpperCase() === "PATH")?.[1] : processEnvironment.PATH; const candidates: string[] = []; - for (const directory of (pathValue ?? "").split(platform === "win32" ? ";" : ":")) { - const entry = directory.trim().replace(/^"|"$/gu, ""); + for (const entry of (pathValue ?? "").split(platform === "win32" ? ";" : ":")) { if (entry.length === 0) continue; const resolved = yield* commandPath(command, { ...processEnvironment, PATH: entry }); if (resolved !== null) candidates.push(resolved); diff --git a/packages/shared/src/shell.test.ts b/packages/shared/src/shell.test.ts index ac5c59c75237..ac587dd1b5cd 100644 --- a/packages/shared/src/shell.test.ts +++ b/packages/shared/src/shell.test.ts @@ -530,31 +530,35 @@ describe("mergePathValues", () => { expect(mergePathValues("/opt/bin :/opt/bin", "/opt/bin :/usr/bin", "linux")).toBe( "/opt/bin :/opt/bin:/usr/bin", ); + expect(mergePathValues('/opt/bin"', "/opt/bin", "linux")).toBe('/opt/bin":/opt/bin'); }); }); effectIt.layer(NodeServices.layer)("resolveCommandPath", (it) => { - it.effect("finds executables in a POSIX PATH directory ending in whitespace", () => - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const cwd = yield* fs.makeTempDirectoryScoped({ directory: ".", prefix: "t3-path-" }); - const directory = `${cwd}/bin \u00a0`; - yield* fs.makeDirectory(directory); - const executable = `${directory}/audit-command`; - yield* fs.writeFileString(executable, "#!/bin/sh\n"); - yield* fs.chmod(executable, 0o755); - const env = { PATH: directory }; + // Windows rejects `"` in file names. + it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")( + "finds executables in a POSIX PATH directory ending in whitespace and quotes", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const cwd = yield* fs.makeTempDirectoryScoped({ directory: ".", prefix: "t3-path-" }); + const directory = `${cwd}/bin \u00a0"`; + yield* fs.makeDirectory(directory); + const executable = `${directory}/audit-command`; + yield* fs.writeFileString(executable, "#!/bin/sh\n"); + yield* fs.chmod(executable, 0o755); + const env = { PATH: directory }; - expect( - yield* resolveCommandPath("audit-command", { env }).pipe( - Effect.provideService(HostProcess.Platform, "linux"), - Effect.provideService(CommandResolutionCache, new Map()), - ), - ).toBe(path.join(directory, "audit-command")); - const resolveExecutable = yield* SpawnExecutableResolution; - expect(resolveExecutable("audit-command", "linux", env)).toBe(executable); - }), + expect( + yield* resolveCommandPath("audit-command", { env }).pipe( + Effect.provideService(HostProcess.Platform, "linux"), + Effect.provideService(CommandResolutionCache, new Map()), + ), + ).toBe(path.join(directory, "audit-command")); + const resolveExecutable = yield* SpawnExecutableResolution; + expect(resolveExecutable("audit-command", "linux", env)).toBe(executable); + }), ); const recordProbes = (env: NodeJS.ProcessEnv) => diff --git a/packages/shared/src/shell.ts b/packages/shared/src/shell.ts index fd881c5fcd83..d9343fce09fe 100644 --- a/packages/shared/src/shell.ts +++ b/packages/shared/src/shell.ts @@ -106,7 +106,7 @@ function resolveSpawnExecutableWithNode( } for (const pathEntry of (readEnvPath(env) ?? "").split(pathDelimiterForPlatform(platform))) { - const normalizedPathEntry = stripWrappingQuotes(trimPathEntry(pathEntry, platform)); + const normalizedPathEntry = normalizePathEntry(pathEntry, platform); if (normalizedPathEntry.length === 0) continue; for (const candidate of candidates) { const candidatePath = path.join(normalizedPathEntry, candidate); @@ -453,20 +453,21 @@ export const readEnvironmentFromWindowsShell = Effect.fn("shell.readEnvironmentF }, ); -function stripWrappingQuotes(value: string): string { - return value.replace(/^"+|"+$/g, ""); -} - function trimPathEntry(entry: string, platform: NodeJS.Platform): string { return platform === "win32" ? entry.trim() : entry; } +// POSIX PATH entries are literal: whitespace and quotes are part of the directory name. +function normalizePathEntry(entry: string, platform: NodeJS.Platform): string { + return platform === "win32" ? entry.trim().replace(/^"+|"+$/g, "") : entry; +} + function pathDelimiterForPlatform(platform: NodeJS.Platform): string { return platform === "win32" ? WINDOWS_PATH_DELIMITER : POSIX_PATH_DELIMITER; } function normalizePathEntryForComparison(entry: string, platform: NodeJS.Platform): string { - const normalized = stripWrappingQuotes(trimPathEntry(entry, platform)); + const normalized = normalizePathEntry(entry, platform); return platform === "win32" ? normalized.toLowerCase() : normalized; } @@ -675,7 +676,7 @@ const findOnPath = Effect.fnUntraced(function* ( const pathEntries: string[] = []; const seenPathEntries = new Set(); for (const entry of pathValue.split(pathDelimiterForPlatform(platform))) { - const pathEntry = stripWrappingQuotes(trimPathEntry(entry, platform)); + const pathEntry = normalizePathEntry(entry, platform); if (pathEntry.length === 0 || seenPathEntries.has(pathEntry)) continue; seenPathEntries.add(pathEntry); From 1063b42768cb2ae43f123a220b6a2188df4b5998 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Tue, 17 Nov 2026 19:23:44 +0100 Subject: [PATCH 071/133] fix(shared): large MCP SSE results in small chunks parse in linear time (#38249) Co-authored-by: Grok 4.7 Co-authored-by: Julius Marminge --- .../shared/src/mcpResponsePayloads.test.ts | 24 +++++++++++++ packages/shared/src/mcpResponsePayloads.ts | 34 +++++++++++++------ 2 files changed, 47 insertions(+), 11 deletions(-) diff --git a/packages/shared/src/mcpResponsePayloads.test.ts b/packages/shared/src/mcpResponsePayloads.test.ts index d3366d671586..d77eadcd34c5 100644 --- a/packages/shared/src/mcpResponsePayloads.test.ts +++ b/packages/shared/src/mcpResponsePayloads.test.ts @@ -71,6 +71,30 @@ it.effect("reads SSE line endings across byte-chunk boundaries without splitting }), ); +it.effect("reads a multi-megabyte SSE event delivered in small chunks", () => + Effect.gen(function* () { + const text = "x".repeat(8 * 1024 * 1024); + const bytes = new TextEncoder().encode( + `data: ${JSON.stringify({ id: 1, result: { text } })}\n\n`, + ); + let offset = 0; + const response = new Response( + new ReadableStream({ + pull(controller) { + if (offset === bytes.length) return controller.close(); + controller.enqueue(bytes.subarray(offset, offset + 256)); + offset = Math.min(offset + 256, bytes.length); + }, + }), + { headers: { "content-type": "text/event-stream" } }, + ); + const payloads = yield* Stream.runCollect( + responsePayloads(response, (cause) => ({ _tag: "ResponsePayloadError" as const, cause })), + ); + expect(Array.from(payloads)).toEqual([{ id: 1, result: { text } }]); + }), +); + it.effect("picks the SSE reader from the media type alone, whatever its case", () => Effect.gen(function* () { const response = new Response('data: {"id":1}\n\n', { diff --git a/packages/shared/src/mcpResponsePayloads.ts b/packages/shared/src/mcpResponsePayloads.ts index 8c9a38cecf18..0b4b99e7cecf 100644 --- a/packages/shared/src/mcpResponsePayloads.ts +++ b/packages/shared/src/mcpResponsePayloads.ts @@ -3,28 +3,40 @@ import * as Effect from "effect/Effect"; import * as Stream from "effect/Stream"; const SSE_EVENT_SEPARATOR = /(?:\r\n|\r(?!\n)|\n){2}/u; +// A separator is at most four characters, so one that a new chunk completes starts within the +// last three characters already read. Scanning only those plus the chunk keeps parsing linear. +const SEPARATOR_OVERLAP = 3; + +function sseEventData(rawEvent: string): string { + return rawEvent + .split(/\r\n|\r|\n/u) + .filter((line) => line.startsWith("data:")) + .map((line) => line.slice("data:".length).trimStart()) + .join("\n"); +} async function* sseDataLines( reader: ReadableStreamDefaultReader, ): AsyncGenerator { const decoder = new TextDecoder(); - let buffered = ""; + let eventParts: string[] = []; + let unscanned = ""; while (true) { const { done, value } = await reader.read(); if (done) return; - buffered += decoder.decode(value, { stream: true }); - let separator = SSE_EVENT_SEPARATOR.exec(buffered); + let text = unscanned + decoder.decode(value, { stream: true }); + let separator = SSE_EVENT_SEPARATOR.exec(text); while (separator !== null) { - const rawEvent = buffered.slice(0, separator.index); - buffered = buffered.slice(separator.index + separator[0].length); - const data = rawEvent - .split(/\r\n|\r|\n/u) - .filter((line) => line.startsWith("data:")) - .map((line) => line.slice("data:".length).trimStart()) - .join("\n"); + eventParts.push(text.slice(0, separator.index)); + const data = sseEventData(eventParts.join("")); + eventParts = []; + text = text.slice(separator.index + separator[0].length); if (data.length > 0) yield data; - separator = SSE_EVENT_SEPARATOR.exec(buffered); + separator = SSE_EVENT_SEPARATOR.exec(text); } + const scannedLength = Math.max(0, text.length - SEPARATOR_OVERLAP); + eventParts.push(text.slice(0, scannedLength)); + unscanned = text.slice(scannedLength); } } From 68108be900aac53cad3ae90d80d3225bca13f513 Mon Sep 17 00:00:00 2001 From: nikalezah <67012982+nikalezah@users.noreply.github.com> Date: Tue, 17 Nov 2026 23:27:02 +0500 Subject: [PATCH 072/133] fix(web): minimap previews show cited assistant text, not the raw link (#38250) Co-authored-by: Julius Marminge --- .../chat/timelineMinimapItems.test.ts | 37 ++++++++++++++++++- .../components/chat/timelineMinimapItems.ts | 26 +++++++++---- 2 files changed, 53 insertions(+), 10 deletions(-) diff --git a/apps/web/src/components/chat/timelineMinimapItems.test.ts b/apps/web/src/components/chat/timelineMinimapItems.test.ts index 776cd39096a8..aa752812cd22 100644 --- a/apps/web/src/components/chat/timelineMinimapItems.test.ts +++ b/apps/web/src/components/chat/timelineMinimapItems.test.ts @@ -1,6 +1,11 @@ import { describe, expect, it } from "vite-plus/test"; -import { MessageId } from "@t3tools/contracts"; -import { ATTACHMENT_ONLY_BOOTSTRAP_PROMPT } from "@t3tools/shared/composerContextReferences"; +import { EnvironmentId, MessageId, ThreadId } from "@t3tools/contracts"; +import { serializeAssistantCitation } from "@t3tools/shared/assistantCitations"; +import { + ATTACHMENT_ONLY_BOOTSTRAP_PROMPT, + formatComposerContextReference, + toComposerContextId, +} from "@t3tools/shared/composerContextReferences"; import { deriveTimelineMinimapItems, resolveTimelineMinimapPreview } from "./timelineMinimapItems"; @@ -45,4 +50,32 @@ describe("resolveTimelineMinimapPreview", () => { }); expect(preview?.assistantText).toBe("Started a thread and Fix CI."); }); + + it("previews a quote, a context chip and a file link in the user's message as their text", () => { + const quote = serializeAssistantCitation({ + version: 1, + environmentId: EnvironmentId.make("env-1"), + threadId: ThreadId.make("thread-1"), + messageId: MessageId.make("assistant-1"), + text: "The cache misses on a cold start.", + start: 0, + end: 33, + prefix: "", + suffix: "", + }); + const file = formatComposerContextReference({ + kind: "file", + contextId: toComposerContextId("readme"), + label: "README.md", + }); + const preview = resolveTimelineMinimapPreview({ + id: "turn-1", + rowIndex: 0, + userText: `${quote}\nWhere do ${file} and [math.ts](src/math.ts) cover this?`, + assistantText: null, + }); + expect(preview?.userText).toBe( + "The cache misses on a cold start. Where do README.md and math.ts cover this?", + ); + }); }); diff --git a/apps/web/src/components/chat/timelineMinimapItems.ts b/apps/web/src/components/chat/timelineMinimapItems.ts index 386abbaa013a..151a02d88175 100644 --- a/apps/web/src/components/chat/timelineMinimapItems.ts +++ b/apps/web/src/components/chat/timelineMinimapItems.ts @@ -1,5 +1,9 @@ +import { assistantCitationsToPlainText } from "@t3tools/shared/assistantCitations"; import { parseThreadLinkHref } from "@t3tools/shared/threadLinks"; -import { isAttachmentOnlyBootstrapPrompt } from "@t3tools/shared/composerContextReferences"; +import { + isAttachmentOnlyBootstrapPrompt, + replaceComposerContextReferences, +} from "@t3tools/shared/composerContextReferences"; import type { Nodes } from "mdast"; import remarkGfm from "remark-gfm"; import remarkParse from "remark-parse"; @@ -94,8 +98,12 @@ export function markdownPlainText(markdown: string): string { return markdownNodeText(markdownPreviewParser.parse(markdown)).replace(/\s+/g, " ").trim(); } -function compactMinimapPreview(text: string | null | undefined) { - const compact = text?.replace(/\s+/g, " ").trim() ?? ""; +// The tooltip shows a few lines; bound parsing work for long messages and streaming responses. +function markdownMinimapPreview(markdown: string | null) { + if (markdown === null) return null; + const compact = markdownNodeText(markdownPreviewParser.parse(markdown.slice(0, 1_500))) + .replace(/\s+/g, " ") + .trim(); return compact.length > 0 ? compact : null; } @@ -106,12 +114,14 @@ export function resolveTimelineMinimapPreview( ? null : { ...item, - userText: compactMinimapPreview(item.userText), - // The tooltip shows three lines; bound parsing work while long responses stream. - assistantText: compactMinimapPreview( - item.assistantText === null + // Before markdown parsing, which would reduce a citation link to "Assistant quote". + userText: markdownMinimapPreview( + item.userText === null ? null - : markdownNodeText(markdownPreviewParser.parse(item.assistantText.slice(0, 1_500))), + : assistantCitationsToPlainText( + replaceComposerContextReferences(item.userText, (reference) => reference.label), + ), ), + assistantText: markdownMinimapPreview(item.assistantText), }; } From e5d757f51b342a5ebc50312790e39a1baca61194 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 17 Nov 2026 10:33:49 -0800 Subject: [PATCH 073/133] fix(server): t3_thread_launch without a workspace follows the worktree default (#38261) --- .../src/mcp/toolkits/project/handlers.test.ts | 53 +++++++++++++ .../src/mcp/toolkits/project/handlers.ts | 77 +++++++++++++++++-- 2 files changed, 125 insertions(+), 5 deletions(-) diff --git a/apps/server/src/mcp/toolkits/project/handlers.test.ts b/apps/server/src/mcp/toolkits/project/handlers.test.ts index 6e78c0617f54..2bfcd896b380 100644 --- a/apps/server/src/mcp/toolkits/project/handlers.test.ts +++ b/apps/server/src/mcp/toolkits/project/handlers.test.ts @@ -51,6 +51,7 @@ const clientLaunchHarness = (input: { readonly runtimeModeCeiling: RuntimeMode; readonly defaultRuntimeMode?: RuntimeMode; readonly newWorktreesStartFromOrigin?: boolean; + readonly defaultThreadEnvMode?: "local" | "worktree"; readonly fallbackModel?: ModelSelection; readonly providers?: readonly ServerProvider[]; /** Where Settings saves a project's model; the legacy project field stays null. */ @@ -83,6 +84,9 @@ const clientLaunchHarness = (input: { ...(input.newWorktreesStartFromOrigin === undefined ? {} : { newWorktreesStartFromOrigin: input.newWorktreesStartFromOrigin }), + ...(input.defaultThreadEnvMode === undefined + ? {} + : { defaultThreadEnvMode: input.defaultThreadEnvMode }), ...(input.overrideModel === undefined ? {} : { @@ -684,6 +688,55 @@ it.effect("a worktree launch that omits startFromOrigin follows the new-worktree }), ); +it.effect("a launch that omits its workspace follows the new-threads-in-a-worktree default", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + for (const source of ["setting", "t3.json"] as const) { + const repo = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-launch-env-mode-" }); + const launched: Array = []; + const { projectId, dependencies } = clientLaunchHarness({ + runtimeModeCeiling: "auto", + launched, + workspaceRoot: repo, + ...(source === "setting" ? { defaultThreadEnvMode: "worktree" as const } : {}), + }); + const git = yield* GitVcsDriver.GitVcsDriver.pipe(Effect.provide(dependencies)); + for (const args of [ + ["init", "-b", "main"], + ["-c", "user.email=t@t", "-c", "user.name=t", "commit", "--allow-empty", "-m", "init"], + ]) { + yield* git.execute({ operation: "test.setupRepo", cwd: repo, args }); + } + if (source === "t3.json") + yield* fileSystem.writeFileString( + `${repo}/t3.json`, + JSON.stringify({ defaultThreadEnvMode: "worktree" }), + ); + const toolkit = yield* ProjectToolkit.pipe( + Effect.provide( + McpToolAccess.HandlersLayer.layer(ProjectHandlers.layer).pipe( + Layer.provide(dependencies), + ), + ), + ); + for (const workspaceStrategy of [undefined, { type: "root" as const }]) { + yield* toolkit + .handle("t3_thread_launch", { + title: "Fix", + projectId, + ...(workspaceStrategy === undefined ? {} : { workspaceStrategy }), + }) + .pipe(Stream.unwrap, Stream.runCollect, Effect.provide(dependencies)); + } + + expect( + launched.map((launch) => launch.workspaceStrategy.type), + source, + ).toEqual(["worktree", "root"]); + } + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), +); + it.effect("a launch into a new worktree creates nothing when its branch collides", () => Effect.gen(function* () { const launched: Array = []; diff --git a/apps/server/src/mcp/toolkits/project/handlers.ts b/apps/server/src/mcp/toolkits/project/handlers.ts index d4e026806496..86e3350bbf22 100644 --- a/apps/server/src/mcp/toolkits/project/handlers.ts +++ b/apps/server/src/mcp/toolkits/project/handlers.ts @@ -3,7 +3,9 @@ import { MessageId, ThreadId, OrchestratorMcpFailure, + type OrchestrationV2ThreadLaunchWorkspaceStrategy, ProjectId, + T3_PROJECT_FILE_NAME, } from "@t3tools/contracts"; import * as Digest from "effect/crypto/Digest"; import * as Effect from "effect/Effect"; @@ -25,7 +27,11 @@ import * as ServerSettings from "../../../serverSettings.ts"; import * as ProviderRegistry from "../../../provider/ProviderRegistry.ts"; import * as DateTime from "effect/DateTime"; import { resolveNewThreadModelSelection } from "@t3tools/shared/usageLimits"; -import { resolveProjectSettings } from "@t3tools/shared/projectSettings"; +import { + resolveProjectFileBackedSetting, + resolveProjectSettings, +} from "@t3tools/shared/projectSettings"; +import { parseT3ProjectFile } from "@t3tools/shared/t3ProjectFile"; import { resolveRuntimeMode } from "../../delegatedTaskModes.ts"; import * as McpInvocationContext from "../../McpInvocationContext.ts"; import * as McpToolAccess from "../../McpToolAccess.ts"; @@ -93,6 +99,56 @@ const assertProjectWorktree = Effect.fn("mcp.assertProjectWorktree")(function* ( }); }); +/** The composer falls back to the project's t3.json when no setting picks the mode. */ +const projectFileThreadEnvMode = Effect.fn("mcp.projectFileThreadEnvMode")(function* ( + workspaceRoot: string, +) { + const fileSystem = yield* FileSystem.FileSystem; + const contents = yield* fileSystem + .readFileString(`${workspaceRoot}/${T3_PROJECT_FILE_NAME}`) + .pipe(Effect.orElseSucceed(() => null)); + return resolveProjectFileBackedSetting( + "defaultThreadEnvMode", + null, + contents === null ? null : parseT3ProjectFile(contents), + ).value; +}); + +/** Branches from the checkout's current branch, as the composer does; a checkout with no commit or a detached HEAD stays shared. */ +const defaultWorktreeStrategy = Effect.fn("mcp.defaultWorktreeStrategy")(function* ( + workspaceRoot: string, +): Effect.fn.Return< + OrchestrationV2ThreadLaunchWorkspaceStrategy | undefined, + OrchestratorMcpFailure, + GitVcsDriver.GitVcsDriver +> { + const git = yield* GitVcsDriver.GitVcsDriver; + const hasCommit = yield* git.resolveCommit({ cwd: workspaceRoot, revision: "HEAD" }).pipe( + Effect.as(true), + Effect.orElseSucceed(() => false), + ); + if (!hasCommit) return undefined; + // symbolic-ref skips the index, so a held index lock cannot drop the launch into the shared checkout. + const head = yield* git + .execute({ + operation: "mcp.defaultWorktreeStrategy", + cwd: workspaceRoot, + args: ["symbolic-ref", "--quiet", "--short", "HEAD"], + allowNonZeroExit: true, + timeoutMs: 5_000, + }) + .pipe(Effect.orElseSucceed(() => null)); + if (head?.exitCode === 1) return undefined; + const branch = head?.exitCode === 0 ? head.stdout.trim() : ""; + if (branch.length === 0) + return yield* new OrchestratorMcpFailure({ + code: "orchestration_error", + message: + "Could not read the project's current branch for the new worktree. No thread was created. Retry, or pass workspaceStrategy.", + }); + return { type: "worktree" as const, baseRef: branch }; +}); + /** A fixed-length id, so a long key fits in the scratch folder name derived from it. */ const launchCommandId = Effect.fn("mcp.launchCommandId")(function* ( namespace: string, @@ -207,17 +263,28 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, { (settings) => resolveProjectSettings(settings, projectId, project).settings, ), ); + // An outside caller that names no workspace follows the new-threads-in-a-worktree + // default, as the composer does. + const requestedStrategy = + input.workspaceStrategy === undefined && + caller === undefined && + project !== undefined && + projectSettings !== undefined && + (projectSettings.defaultThreadEnvMode ?? + (yield* projectFileThreadEnvMode(project.workspaceRoot))) === "worktree" + ? yield* defaultWorktreeStrategy(project.workspaceRoot) + : input.workspaceStrategy; // An omitted startFromOrigin follows the new-worktree setting, as the composer and // t3_worktree_handoff do. Otherwise a stale local branch silently becomes the base. const strategy = projectSettings !== undefined && - input.workspaceStrategy?.type === "worktree" && - input.workspaceStrategy.startFromOrigin === undefined + requestedStrategy?.type === "worktree" && + requestedStrategy.startFromOrigin === undefined ? { - ...input.workspaceStrategy, + ...requestedStrategy, startFromOrigin: projectSettings.newWorktreesStartFromOrigin, } - : input.workspaceStrategy; + : requestedStrategy; // Reject unresolved base refs and blocked branch names before accepting a launch; worktree provisioning happens later. if (!replaying && strategy?.type === "worktree") yield* ThreadLaunch.ThreadLaunchService.pipe( From 6ab633f6d6e8273f08a060137ab64463638787ce Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 17 Nov 2026 11:07:33 -0800 Subject: [PATCH 074/133] fix(server): Android SDK detection looks past an ANDROID_HOME that is not an SDK (#38278) --- .../server/src/device/LocalDeviceHost.test.ts | 17 +++++++ apps/server/src/device/LocalDeviceHost.ts | 44 +++++++++---------- 2 files changed, 37 insertions(+), 24 deletions(-) diff --git a/apps/server/src/device/LocalDeviceHost.test.ts b/apps/server/src/device/LocalDeviceHost.test.ts index 721a7b26370c..b29b80a64783 100644 --- a/apps/server/src/device/LocalDeviceHost.test.ts +++ b/apps/server/src/device/LocalDeviceHost.test.ts @@ -549,6 +549,23 @@ describe("Android SDK availability", () => { }), ); + // regression: #38268 an ANDROID_HOME that is not an SDK must not stop detection + it.effect("falls back past an ANDROID_HOME that is not an SDK", () => + Effect.gen(function* () { + const complete = [ + "/parent/sdk/platform-tools/adb", + "/parent/sdk/emulator/emulator", + "/parent/sdk/cmdline-tools/latest/bin/avdmanager", + ]; + for (const environment of [ + { ANDROID_HOME: "/parent", ANDROID_SDK_ROOT: "/parent/sdk" }, + { ANDROID_HOME: "/parent", PATH: "/parent/sdk/platform-tools" }, + ]) { + expect(yield* diagnose(complete, environment)).toBeNull(); + } + }), + ); + it.effect("discovers the standard macOS SDK without ANDROID_HOME", () => Effect.gen(function* () { const root = "/test/home/Library/Android/sdk"; diff --git a/apps/server/src/device/LocalDeviceHost.ts b/apps/server/src/device/LocalDeviceHost.ts index 161e2b345cca..50089af431ff 100644 --- a/apps/server/src/device/LocalDeviceHost.ts +++ b/apps/server/src/device/LocalDeviceHost.ts @@ -133,7 +133,9 @@ const androidSdk = Effect.gen(function* () { const platform = yield* HostProcess.Platform; const windows = platform === "win32"; const home = environment.HOME ?? environment.USERPROFILE ?? ""; - const explicit = environment.ANDROID_HOME?.trim() || environment.ANDROID_SDK_ROOT?.trim(); + const explicit = [environment.ANDROID_HOME?.trim(), environment.ANDROID_SDK_ROOT?.trim()].filter( + (root): root is string => !!root, + ); const exists = (file: string) => fs.exists(file).pipe(Effect.orElseSucceed(() => false)); const adbBinary = windows ? "adb.exe" : "adb"; const avdmanagerBinary = windows ? "avdmanager.bat" : "avdmanager"; @@ -142,7 +144,6 @@ const androidSdk = Effect.gen(function* () { const emulator = yield* exists( path.join(root, "emulator", windows ? "emulator.exe" : "emulator"), ); - if (!explicit && !adb && !emulator) return null; const avdmanager = yield* exists( path.join(root, "cmdline-tools", "latest", "bin", avdmanagerBinary), ); @@ -150,33 +151,28 @@ const androidSdk = Effect.gen(function* () { !avdmanager && (yield* exists(path.join(root, "tools", "bin", avdmanagerBinary))); return { root, adb, emulator, avdmanager, legacyAvdmanager }; }); - const candidates = explicit - ? [explicit] - : [ - path.join(home, "Library", "Android", "sdk"), - path.join(home, "Android", "Sdk"), - path.join( - environment.LOCALAPPDATA ?? path.join(home, "AppData", "Local"), - "Android", - "Sdk", - ), - ]; + const candidates = [ + ...explicit, + path.join(home, "Library", "Android", "sdk"), + path.join(home, "Android", "Sdk"), + path.join(environment.LOCALAPPDATA ?? path.join(home, "AppData", "Local"), "Android", "Sdk"), + ]; for (const root of candidates) { const sdk = yield* inspect(root); - if (sdk) return sdk; + if (sdk.adb || sdk.emulator) return sdk; } // PATH entries can be slow to stat (network shares), so only consult them after the standard locations miss. - if (!explicit) { - const searchPath = environment.PATH ?? environment.Path ?? ""; - for (const directory of searchPath.split(windows ? ";" : ":")) { - if (!directory) continue; - const adb = path.join(directory, adbBinary); - if (!(yield* exists(adb))) continue; - const resolved = yield* fs.realPath(adb).pipe(Effect.orElseSucceed(() => adb)); - const sdk = yield* inspect(path.dirname(path.dirname(resolved))); - if (sdk) return sdk; - } + const searchPath = environment.PATH ?? environment.Path ?? ""; + for (const directory of searchPath.split(windows ? ";" : ":")) { + if (!directory) continue; + const adb = path.join(directory, adbBinary); + if (!(yield* exists(adb))) continue; + const resolved = yield* fs.realPath(adb).pipe(Effect.orElseSucceed(() => adb)); + const sdk = yield* inspect(path.dirname(path.dirname(resolved))); + if (sdk.adb || sdk.emulator) return sdk; } + // No real SDK anywhere: report what the configured root is missing. + if (explicit[0]) return yield* inspect(explicit[0]); return { root: null, adb: false, emulator: false, avdmanager: false, legacyAvdmanager: false }; }); From a774d7f473e968e7ee8911bc9906c97397f4b98a Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 17 Nov 2026 11:13:38 -0800 Subject: [PATCH 075/133] fix(server): issue links on a custom GitHub Enterprise hostname resolve (#38269) --- apps/server/src/issue/IssueService.test.ts | 9 ++++++ apps/server/src/issue/IssueService.ts | 25 +++++++++++++-- .../client-runtime/src/issueLinks.test.ts | 7 +++++ packages/client-runtime/src/issueLinks.ts | 24 ++++++++++++-- .../src/shared/definition.ts | 17 ++++++---- .../GitHubSourceControlProvider.test.ts | 29 +++++++++++++++++ .../src/server/GitHubSourceControlProvider.ts | 31 ++++++++++++++++++- .../src/shared/definition.ts | 6 ++-- 8 files changed, 134 insertions(+), 14 deletions(-) diff --git a/apps/server/src/issue/IssueService.test.ts b/apps/server/src/issue/IssueService.test.ts index f42a1aea6f56..57f795e6c549 100644 --- a/apps/server/src/issue/IssueService.test.ts +++ b/apps/server/src/issue/IssueService.test.ts @@ -275,6 +275,15 @@ describe("IssueService", () => { host: "gitea.test", }); + // A GitHub Enterprise Server's hostname need not say "github"; its project vouches for it. + const enterprise = yield* makeService({ + projects: [project({ id: "ghes", repository: "acme/web", host: "code.acme.test" })], + trackers: [fakeTracker()], + }); + expect( + yield* enterprise.resolveUrl("https://code.acme.test/acme/web/issues/7"), + ).toMatchObject({ projectId: "ghes", host: "code.acme.test", key: "7", writable: true }); + // Another host is not reachable through this project's credentials at all. const elsewhere = yield* Effect.flip(service.detail({ ...own, host: "ghe.example.test" })); expect(elsewhere).toMatchObject({ diff --git a/apps/server/src/issue/IssueService.ts b/apps/server/src/issue/IssueService.ts index 2832ab04d15b..8f18b80a985a 100644 --- a/apps/server/src/issue/IssueService.ts +++ b/apps/server/src/issue/IssueService.ts @@ -9,6 +9,7 @@ import { IssueOperationError, IssueTrackerKind, IssueUnavailableError, + SourceControlProviderKind, type IssueCandidates, type IssueCommentInput, type IssueCommentsPage, @@ -640,10 +641,30 @@ const make = Effect.gen(function* () { return { projectId, tracker: own.tracker, host: own.host, scope: own.scope }; }); + /** A host whose hostname does not name it, such as GitHub Enterprise Server, is vouched for by a project on it. */ + const parseOnProjectHost = (value: string) => { + const url = parseUrl(value); + if (url === null) return Effect.succeed(null); + return listProjects({ host: url.hostname, authority: url.host.toLowerCase() }).pipe( + Effect.map(({ supported }) => { + for (const project of supported) { + const parsed = sourceControlDefinitions.parseIssueUrl( + value, + SourceControlProviderKind.make(project.tracker), + ); + if (parsed !== null) return parsed; + } + return null; + }), + ); + }; + const resolveUrl: IssueService["Service"]["resolveUrl"] = Effect.fn("IssueService.resolveUrl")( function* (url, preferredProjectId) { - const gitHost = sourceControlDefinitions.parseIssueUrl(url); - const standalone = gitHost === null ? findStandaloneIssueUrl(registry.standalone, url) : null; + const recognized = sourceControlDefinitions.parseIssueUrl(url); + const standalone = + recognized === null ? findStandaloneIssueUrl(registry.standalone, url) : null; + const gitHost = recognized ?? (standalone === null ? yield* parseOnProjectHost(url) : null); const parsed = gitHost === null ? standalone diff --git a/packages/client-runtime/src/issueLinks.test.ts b/packages/client-runtime/src/issueLinks.test.ts index 004b526d99cf..eef7524db4f8 100644 --- a/packages/client-runtime/src/issueLinks.test.ts +++ b/packages/client-runtime/src/issueLinks.test.ts @@ -56,6 +56,13 @@ describe("resolveIssueLinkTarget", () => { ], }); expect(target?.ref.projectId).toBe("ported"); + + // An Enterprise Server's hostname need not say "github"; its project vouches for it. + const custom = resolveIssueLinkTarget({ + url: "https://code.acme.test/acme/web/issues/7", + projects: [enterprise("custom", "code.acme.test")], + }); + expect(custom?.ref).toMatchObject({ projectId: "custom", host: "code.acme.test", key: "7" }); }); it.each([ diff --git a/packages/client-runtime/src/issueLinks.ts b/packages/client-runtime/src/issueLinks.ts index 528ea16f12d3..3509bbbf33ed 100644 --- a/packages/client-runtime/src/issueLinks.ts +++ b/packages/client-runtime/src/issueLinks.ts @@ -30,6 +30,24 @@ function linkAuthority(url: string): string | null { } } +/** A host whose hostname does not name it, such as GitHub Enterprise Server, is vouched for by a project on it. */ +function parseIssueLink( + url: string, + authority: string | null, + projects: ReadonlyArray, +) { + const parsed = sourceControlClients.parseIssueUrl(url); + if (parsed !== null || authority === null) return parsed; + const hostname = new URL(url).hostname.toLowerCase(); + for (const project of projects) { + const binding = projectIssueBinding(project); + if (binding === null || (binding.host !== hostname && binding.host !== authority)) continue; + const known = sourceControlClients.parseIssueUrl(url, project.repositoryIdentity?.provider); + if (known !== null) return known; + } + return null; +} + /** * The reference an issue link resolves to, and the project it is read through: the project whose * tracker binding is that host and scope, else any project on the same tracker and host lending @@ -42,11 +60,11 @@ export function resolveIssueLinkTarget(input: { readonly projects: ReadonlyArray; readonly preferredProjectId?: string | undefined; }): { readonly project: Project; readonly ref: IssueRef } | null { - const parsed = sourceControlClients.parseIssueUrl(input.url); - if (parsed === null) return null; - const { definition, link } = parsed; // A link names its server's port; a binding does only when its remote or web URL did. const authority = linkAuthority(input.url); + const parsed = parseIssueLink(input.url, authority, input.projects); + if (parsed === null) return null; + const { definition, link } = parsed; const onHost = input.projects.flatMap((project) => { const binding = projectIssueBinding(project); return binding === null || diff --git a/packages/source-control-core/src/shared/definition.ts b/packages/source-control-core/src/shared/definition.ts index d8e22b811fc9..acd85f0c877a 100644 --- a/packages/source-control-core/src/shared/definition.ts +++ b/packages/source-control-core/src/shared/definition.ts @@ -274,8 +274,11 @@ export interface SourceControlDefinition { readonly parseCommitUrl?: (url: URL, known: boolean) => CommitLink | null; /** Null when the URL is not one of this host's change requests. */ readonly parseChangeRequestUrl: (url: URL) => ParsedChangeRequestUrl | null; - /** Null when the URL is not one of this host's issues. Absent for a host with none. */ - readonly parseIssueUrl?: (url: URL) => IssueLink | null; + /** + * Null when the URL is not one of this host's issues. Absent for a host with none. `known` is + * set when the caller already knows this host serves the URL's repository. + */ + readonly parseIssueUrl?: (url: URL, known: boolean) => IssueLink | null; /** * The repository URL when `url` is a page inside one of this host's repositories. `known` is set * when the caller already knows this host serves the URL's repository. Off a known host, return @@ -670,9 +673,10 @@ export interface SourceControlDefinitionRegistry { readonly findByPublicDomain: (hostname: string) => SourceControlDefinition | undefined; /** The first host, in registry order, that reads `url` as one of its change requests. */ readonly parseChangeRequestUrl: (url: string) => ParsedChangeRequest | null; - /** The first host, in registry order, that reads `url` as one of its issues. */ + /** The first host, in registry order, that reads `url` as one of its issues, or `kind` alone. */ readonly parseIssueUrl: ( url: string, + kind?: SourceControlProviderKind, ) => { readonly definition: SourceControlDefinition; readonly link: IssueLink } | null; readonly parseCommitUrl: (url: string, kind?: SourceControlProviderKind) => ParsedCommit | null; readonly findByChangeRequestUrl: (url: string) => SourceControlDefinition | undefined; @@ -792,11 +796,12 @@ export function makeSourceControlDefinitionRegistry( ); }, parseChangeRequestUrl, - parseIssueUrl: (value) => { + parseIssueUrl: (value, kind) => { const url = httpUrl(value); if (url === null) return null; - for (const definition of claimOrder) { - const link = definition.parseIssueUrl?.(url) ?? null; + const preferred = kind === undefined ? undefined : byKind.get(kind); + for (const definition of kind === undefined ? claimOrder : preferred ? [preferred] : []) { + const link = definition.parseIssueUrl?.(url, preferred !== undefined) ?? null; if (link !== null) return { definition, link }; } return null; diff --git a/packages/source-control-github/src/server/GitHubSourceControlProvider.test.ts b/packages/source-control-github/src/server/GitHubSourceControlProvider.test.ts index d848a1f54be3..816f855d8643 100644 --- a/packages/source-control-github/src/server/GitHubSourceControlProvider.test.ts +++ b/packages/source-control-github/src/server/GitHubSourceControlProvider.test.ts @@ -265,6 +265,35 @@ const githubContext = (host: string) => ({ }); describe("GitHubSourceControlProvider repository resolution", () => { + // regression: #38251 an Enterprise Server's hostname need not say "github"; a gh login vouches for it + it.effect.each([ + ["github", "github"], + ["unknown", "unknown"], + ] as const)("refines a remote on an unknown host the gh login reads as %s", ([seen, expected]) => + Effect.gen(function* () { + const provider = yield* makeProvider({}); + const remoteUrl = "https://code.acme.test/acme/web.git"; + const identity = { + canonicalKey: "code.acme.test/acme/web", + locator: { source: "git-remote" as const, remoteName: "origin", remoteUrl }, + rootPath: "/repo", + provider: SourceControlProviderKind.make("unknown"), + }; + const refined = yield* provider.refineRepositoryIdentity!({ + identity, + resolveContext: ({ context }) => + Effect.succeed({ + ...context, + provider: { ...context.provider, kind: SourceControlProviderKind.make(seen) }, + }), + }); + assert.deepStrictEqual(refined, { + ...identity, + provider: SourceControlProviderKind.make(expected), + }); + }), + ); + it.effect("reads the repository gh would pick from the remotes", () => { const paths: string[] = []; const { layer } = harness({ diff --git a/packages/source-control-github/src/server/GitHubSourceControlProvider.ts b/packages/source-control-github/src/server/GitHubSourceControlProvider.ts index a7733d6dd5ee..7ff3d4a9b4d8 100644 --- a/packages/source-control-github/src/server/GitHubSourceControlProvider.ts +++ b/packages/source-control-github/src/server/GitHubSourceControlProvider.ts @@ -61,7 +61,11 @@ import { type SourceControlManagedCliDiscoverySpec, } from "@t3tools/source-control-core/server/discovery"; import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost"; -import { readSourceControlHostSettings } from "@t3tools/source-control-core/shared/definition"; +import { + parseGitRemoteHost, + readSourceControlHostSettings, + unknownRemoteProvider, +} from "@t3tools/source-control-core/shared/definition"; import * as GitHubClient from "../shared/definition.ts"; import { @@ -339,6 +343,30 @@ class GitHubFailure extends Schema.TaggedError()("GitHubFailure", const failure = (detail: string, cause?: unknown) => new GitHubFailure({ detail, cause }); +// A gh login confirms a GitHub Enterprise Server whose hostname does not identify its provider. +const refineRepositoryIdentity: NonNullable< + SourceControlProvider.SourceControlProvider["Service"]["refineRepositoryIdentity"] +> = Effect.fn("GitHubSourceControlProvider.refineRepositoryIdentity")(function* ({ + identity, + resolveContext, +}) { + if (!identity.rootPath || (identity.provider !== undefined && identity.provider !== "unknown")) + return identity; + const remote = parseGitRemoteHost(identity.locator.remoteUrl); + if (remote === null) return identity; + const context = yield* resolveContext({ + cwd: identity.rootPath, + context: { + provider: unknownRemoteProvider(remote), + remoteName: identity.locator.remoteName, + remoteUrl: identity.locator.remoteUrl, + }, + }); + return context?.provider.kind === "github" + ? { ...identity, provider: SourceControlProviderKind.make("github") } + : identity; +}); + const PULL_REQUEST_NOT_FOUND = "Pull request not found. Check the PR number or URL and try again."; const REPOSITORY_NOT_FOUND = "Repository not found. Check the owner and name and try again."; @@ -968,6 +996,7 @@ export const make = Effect.gen(function* () { return SourceControlProvider.SourceControlProvider.of({ kind: SourceControlProviderKind.make("github"), + refineRepositoryIdentity, resolveRemoteWebHost: Effect.fn("GitHubSourceControlProvider.resolveRemoteWebHost")( ({ context }) => Effect.succeed(gitHubApiHostForRemote(context.remoteUrl)), ), diff --git a/packages/source-control-github/src/shared/definition.ts b/packages/source-control-github/src/shared/definition.ts index dbc8ac9f80e2..a143b3787fde 100644 --- a/packages/source-control-github/src/shared/definition.ts +++ b/packages/source-control-github/src/shared/definition.ts @@ -101,8 +101,10 @@ export const definition = defineSourceControl({ parseCommitUrl: (url, known) => known || isGitHubHost(url.hostname) ? parseCommitPath(url, COMMIT_PATH) : null, parseChangeRequestUrl: (url) => parseChangeRequestPath(url, CHANGE_REQUEST_PATH), - // `/issues/` is too generic a path to believe from a host that is not GitHub's. - parseIssueUrl: (url) => (isGitHubHost(url.hostname) ? parseIssuePath(url, ISSUE_PATH) : null), + // `/issues/` is too generic a path to believe from a host that is not GitHub's, unless a known + // project's host vouches for it as a GitHub Enterprise Server. + parseIssueUrl: (url, known) => + known || isGitHubHost(url.hostname) ? parseIssuePath(url, ISSUE_PATH) : null, repositoryUrlFromPage: (url) => isGitHubHost(url.hostname) ? repositoryUrlFromPagePath(url, REPOSITORY_PAGE_PATH) : null, // GitHub writes every bare reference through `/issues/`, including pull requests. From f92c5e8f98246ea5537e3ea002fb7bb8ffd84451 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Tue, 17 Nov 2026 20:19:07 +0100 Subject: [PATCH 076/133] fix(web): review summary line comments keep which side they refer to (#38276) Co-authored-by: Grok 4.7 Co-authored-by: Julius Marminge --- .../pullRequest/pullRequestDetail.logic.test.ts | 15 +++++++++++++++ .../pullRequest/pullRequestDetail.logic.ts | 14 ++++++++++---- 2 files changed, 25 insertions(+), 4 deletions(-) diff --git a/apps/web/src/components/pullRequest/pullRequestDetail.logic.test.ts b/apps/web/src/components/pullRequest/pullRequestDetail.logic.test.ts index 1f348f57afd1..4f25b26f3276 100644 --- a/apps/web/src/components/pullRequest/pullRequestDetail.logic.test.ts +++ b/apps/web/src/components/pullRequest/pullRequestDetail.logic.test.ts @@ -1215,6 +1215,21 @@ describe("adding a remark to the chat", () => { ].join("\n\n"), ); + const beforeContext = buildPullRequestCommentContext( + { + ...pullRequest, + reviewThreads: reviewThreads.map((thread) => ({ ...thread, side: "left" as const })), + reviewThreadsTruncated: false, + }, + { kind: "comment", comment: review }, + )!; + const beforeRecord = reviewCommentContextRecord(beforeContext); + const beforePrompt = projectComposerContextForProvider({ + text: formatComposerContextReference(beforeRecord), + records: [beforeRecord], + }); + expect(beforePrompt).toContain("`src/main.rs` line 12 (before)"); + const sent = reviewCommentContextRecord( buildPullRequestCommentContext( { ...pullRequest, reviewThreads, reviewThreadsTruncated: false }, diff --git a/apps/web/src/components/pullRequest/pullRequestDetail.logic.ts b/apps/web/src/components/pullRequest/pullRequestDetail.logic.ts index f93b23d8d984..94677bce8eee 100644 --- a/apps/web/src/components/pullRequest/pullRequestDetail.logic.ts +++ b/apps/web/src/components/pullRequest/pullRequestDetail.logic.ts @@ -927,11 +927,17 @@ function reviewThreadText(thread: PullRequestReviewThread): string { .trim(); } +/** A thread's line, marked when it is numbered as in the base branch, the diff's left side. */ +function reviewThreadLine(thread: PullRequestReviewThread): string | null { + return thread.line === null ? null : `${thread.line}${thread.side === "left" ? " (before)" : ""}`; +} + function reviewThreadContext( thread: PullRequestReviewThread, pullRequestNumber: number, ): ReviewCommentContext { const lineIndex = Math.max(0, (thread.line ?? 1) - 1); + const line = reviewThreadLine(thread); return { id: `pull-request-finding:${thread.id}`, sectionId: `pull-request:${pullRequestNumber}`, @@ -939,8 +945,7 @@ function reviewThreadContext( filePath: thread.path, startIndex: lineIndex, endIndex: lineIndex, - rangeLabel: - thread.line === null ? "file" : `L${thread.line}${thread.side === "left" ? " (before)" : ""}`, + rangeLabel: line === null ? "file" : `L${line}`, // Strip bot bookkeeping comments before bounding finding text. text: bounded(reviewThreadText(thread)), diff: "", @@ -1340,8 +1345,9 @@ function reviewLineComments( if (body === null || !pullRequestAnchorMatchesUrl(anchor.anchor, lineComment.reviewUrl)) { return []; } - const line = thread.line === null ? "" : ` line ${thread.line}`; - return [`${lineComment.author?.login ?? "ghost"} on \`${thread.path}\`${line}: ${body}`]; + const line = reviewThreadLine(thread); + const at = line === null ? "" : ` line ${line}`; + return [`${lineComment.author?.login ?? "ghost"} on \`${thread.path}\`${at}: ${body}`]; }), ); // Threads or their replies can be partly loaded; then an empty match proves nothing. From 74b1f97ce9e8891975bb29d10a4de1fdb0505863 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Tue, 17 Nov 2026 20:44:29 +0100 Subject: [PATCH 077/133] fix(web): reopening Settings reloads WSL distributions (#38281) Co-authored-by: Grok 4.7 Co-authored-by: Julius Marminge --- .../settings/ConnectionsSettings.tsx | 4 +- apps/web/src/state/desktopWslState.test.ts | 72 +++++++++++++++++++ apps/web/src/state/desktopWslState.ts | 18 ++--- packages/client-runtime/src/state/runtime.ts | 2 +- 4 files changed, 85 insertions(+), 11 deletions(-) create mode 100644 apps/web/src/state/desktopWslState.test.ts diff --git a/apps/web/src/components/settings/ConnectionsSettings.tsx b/apps/web/src/components/settings/ConnectionsSettings.tsx index 9d309a8b90fa..1776f4f440f3 100644 --- a/apps/web/src/components/settings/ConnectionsSettings.tsx +++ b/apps/web/src/components/settings/ConnectionsSettings.tsx @@ -99,7 +99,7 @@ import { desktopNetworkAccessStateAtom, refreshDesktopNetworkAccessState, } from "~/state/desktopNetworkAccess"; -import { desktopWslStateAtom, refreshDesktopWslState } from "~/state/desktopWslState"; +import { desktopWslAccessStateAtom, refreshDesktopWslState } from "~/state/desktopWslState"; import { useDesktopUpdateState } from "~/state/desktopUpdate"; import { type EnvironmentPresentation, @@ -415,7 +415,7 @@ function ConnectionsSettingsContent({ showsAccess && canManageLocalBackend && desktopBridge ? desktopNetworkAccessStateAtom : null, ); const desktopWsl = useEnvironmentQuery( - showsAccess && canManageLocalBackend && desktopBridge ? desktopWslStateAtom : null, + showsAccess && canManageLocalBackend && desktopBridge ? desktopWslAccessStateAtom : null, ); const desktopWslState = desktopWsl.data; const desktopWslError = desktopWslMutationError ?? desktopWsl.error; diff --git a/apps/web/src/state/desktopWslState.test.ts b/apps/web/src/state/desktopWslState.test.ts new file mode 100644 index 000000000000..2dbe316a3e81 --- /dev/null +++ b/apps/web/src/state/desktopWslState.test.ts @@ -0,0 +1,72 @@ +import type { DesktopWslState } from "@t3tools/contracts"; +import { AsyncResult, AtomRegistry } from "effect/reactivity"; +import { expect, it, vi } from "vite-plus/test"; + +import { desktopWslAccessStateAtom, desktopWslStateAtom } from "./desktopWslState"; + +const ubuntuOnly: DesktopWslState = { + enabled: false, + distro: null, + available: true, + wslOnly: false, + distros: [{ name: "Ubuntu", isDefault: true, version: 2 }], + preflightError: null, +}; +const withDebian: DesktopWslState = { + ...ubuntuOnly, + distros: [...ubuntuOnly.distros, { name: "Debian", isDefault: false, version: 2 }], +}; + +it("refetches on every Access visit and reuses a fresh result for Search", async () => { + const pending = Promise.withResolvers(); + const getWslState = vi + .fn<() => Promise>() + .mockResolvedValueOnce(ubuntuOnly) + .mockReturnValueOnce(pending.promise); + vi.stubGlobal("window", { desktopBridge: { getWslState } }); + using _now = vi.spyOn(Date, "now").mockReturnValue(1_000_000); + const tasks: Array<() => void> = []; + const registry = AtomRegistry.make({ + scheduleTask: (task) => { + tasks.push(task); + return () => {}; + }, + }); + const runTasks = () => { + for (const task of tasks.splice(0)) task(); + }; + const settled = (atom: typeof desktopWslStateAtom) => + new Promise((resolve) => { + const unsubscribe = registry.subscribe( + atom, + (result) => { + if (result._tag === "Success" && !result.waiting) { + unsubscribe(); + resolve(result.value); + } + }, + { immediate: true }, + ); + }); + try { + const closeSearch = registry.mount(desktopWslStateAtom); + expect(await settled(desktopWslStateAtom)).toEqual(ubuntuOnly); + closeSearch(); + runTasks(); + + registry.mount(desktopWslStateAtom)(); + runTasks(); + expect(getWslState).toHaveBeenCalledTimes(1); + + const closeAccess = registry.mount(desktopWslAccessStateAtom); + runTasks(); + expect(getWslState).toHaveBeenCalledTimes(2); + expect(AsyncResult.getOrThrow(registry.get(desktopWslAccessStateAtom))).toEqual(ubuntuOnly); + pending.resolve(withDebian); + expect(await settled(desktopWslAccessStateAtom)).toEqual(withDebian); + closeAccess(); + } finally { + registry.dispose(); + vi.unstubAllGlobals(); + } +}); diff --git a/apps/web/src/state/desktopWslState.ts b/apps/web/src/state/desktopWslState.ts index 2115f80eaf7f..56df4d87a317 100644 --- a/apps/web/src/state/desktopWslState.ts +++ b/apps/web/src/state/desktopWslState.ts @@ -1,3 +1,4 @@ +import { revalidateOnMount } from "@t3tools/client-runtime/state/runtime"; import type { DesktopBridge, DesktopWslState } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; @@ -5,9 +6,8 @@ import { Atom } from "effect/reactivity"; import { appAtomRegistry } from "~/rpc/atomRegistry"; -const DESKTOP_WSL_STATE_STALE_TIME_MS = 30_000; - type DesktopWslStateBridge = Pick; +const WSL_SEARCH_STALE_TIME_MS = 30_000; class DesktopWslStateUnavailableError extends Schema.TaggedError()( "DesktopWslStateUnavailableError", @@ -44,17 +44,19 @@ function createDesktopWslStateAtom(getBridge: () => DesktopWslStateBridge | unde }); return Atom.make(loadDesktopWslState()).pipe( - Atom.swr({ - staleTime: DESKTOP_WSL_STATE_STALE_TIME_MS, - revalidateOnMount: true, - }), Atom.keepAlive, Atom.withLabel("desktop:wsl-state:load"), ); } -export const desktopWslStateAtom = createDesktopWslStateAtom(getDesktopWslStateBridge); +const desktopWslStateCache = createDesktopWslStateAtom(getDesktopWslStateBridge); + +export const desktopWslStateAtom = desktopWslStateCache.pipe( + revalidateOnMount(WSL_SEARCH_STALE_TIME_MS), +); + +export const desktopWslAccessStateAtom = desktopWslStateCache.pipe(revalidateOnMount(0)); export function refreshDesktopWslState(): void { - appAtomRegistry.refresh(desktopWslStateAtom); + appAtomRegistry.refresh(desktopWslStateCache); } diff --git a/packages/client-runtime/src/state/runtime.ts b/packages/client-runtime/src/state/runtime.ts index 736b10fdeeac..e61ac52f5e5b 100644 --- a/packages/client-runtime/src/state/runtime.ts +++ b/packages/client-runtime/src/state/runtime.ts @@ -573,7 +573,7 @@ const isStale = (result: AsyncResult.AsyncResult, staleTimeMs: * TTL skips on a remount; this layer has no TTL (a transform drops it) while `self` keeps the cache. * It reads `self` as a dependency, not a subscription, so `self` goes idle with its last reader. */ -const revalidateOnMount = +export const revalidateOnMount = (staleTimeMs: number) => ( self: Atom.Atom>, From 2df750e0c94559c9e917d68826f642499e9c9a1c Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 17 Nov 2026 11:50:55 -0800 Subject: [PATCH 078/133] fix(web): MCP app full screen header clears the native window controls (#38303) --- apps/web/src/components/chat/McpAppFrame.tsx | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/apps/web/src/components/chat/McpAppFrame.tsx b/apps/web/src/components/chat/McpAppFrame.tsx index fc20323c1c44..cb35ed33f709 100644 --- a/apps/web/src/components/chat/McpAppFrame.tsx +++ b/apps/web/src/components/chat/McpAppFrame.tsx @@ -36,6 +36,7 @@ import { useTurnItemDetail } from "~/state/queries"; import { mcpAppEnvironment } from "~/state/mcpApps"; import { useAtomCommand } from "~/state/use-atom-command"; import { observeResize } from "~/lib/observeResize"; +import { useNativeTitlebarHeight } from "~/lib/windowControlsOverlay"; const commandFailure = (result: { readonly cause: Parameters[0]["cause"]; @@ -90,6 +91,7 @@ export function McpAppFrame(props: { }) { const { app } = props; const theme = useHtmlRenderTheme(); + const nativeTitlebarHeight = useNativeTitlebarHeight(); const frameRef = useRef(null); const boxRef = useRef(null); const [width, setWidth] = useState(0); @@ -453,6 +455,8 @@ export function McpAppFrame(props: { ? "fixed inset-0 m-0 flex h-dvh max-h-none w-dvw max-w-none flex-col border-0 bg-background p-0" : "block! static! m-0 border-0 bg-transparent p-0 text-inherit", )} + // Keep the header clear of the native window controls. + style={fullscreen ? { paddingTop: nativeTitlebarHeight } : undefined} > {fullscreen ? (
Date: Tue, 17 Nov 2026 21:00:39 +0100 Subject: [PATCH 079/133] fix(server): images from refused Claude starts survive a fresh-session recovery (#38241) Co-authored-by: Grok 4.7 Co-authored-by: Julius Marminge --- .../ProviderTurnStartService.ts | 9 ++++----- .../testkit/ProviderSwitch.integration.test.ts | 17 ++++++++++++++--- 2 files changed, 18 insertions(+), 8 deletions(-) diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts index 21f400057792..28f8f474cd6a 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts @@ -1049,11 +1049,8 @@ export const layer: Layer.Layer< ...loadedProviderThread, contextUsage: handoffUsage, }; - // The resume fallback summary already covers every earlier run in order. A - // retry copy after it would rank older missed requests as the newest history. const missedRuns = projection.runs.filter( (source) => - !resumeFellBack && source.ordinal < run.ordinal && source.providerThreadId === providerThread.id && (source.status === "failed" || source.status === "interrupted") && @@ -1097,8 +1094,10 @@ export const layer: Layer.Layer< const missedItems = missedHistory.filter( (item) => !coveredItemIds.has(item.id) && historicalMessage(item) !== null, ); + // The resume fallback summary already covers every earlier run in order. A + // retry copy after it would rank older missed requests as the newest history. const handoffs = - missedItems.length === 0 + missedItems.length === 0 || resumeFellBack ? [] : [ yield* contextHandoffService.prepareProviderHandoff({ @@ -1494,7 +1493,7 @@ export const layer: Layer.Layer< } } resumedHandoffContext = undefined; - resumedRetryHandoff = { handoffs: [], attachments: [] }; + resumedRetryHandoff = undefined; if (!(yield* isCurrentAttemptInStatus("starting"))) return undefined; // Another client is still writing to the native thread. A fresh // session here would silently split the conversation from it. diff --git a/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts b/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts index e1b2572d8d1a..a05636033eb8 100644 --- a/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts +++ b/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts @@ -1973,9 +1973,16 @@ describe("orchestration v2 provider switching", () => { new ClaudeBackgroundWorkBlocksQueryReplacementError(), true, ], - ] as const)("keeps the native session after turns refused for %s", ([, refusalCause, inject]) => + [ + "background work followed by a lost native session", + new ClaudeBackgroundWorkBlocksQueryReplacementError(), + false, + true, + ], + ] as const)("retains missed images after %s", ([, refusalCause, inject, loseSession]) => Effect.gen(function* () { const cwd = yield* checkpointWorkspace("refused-start-keeps-native"); + const failResumeOnce = yield* Ref.make(false); const capturedTurns = yield* Ref.make>([]); const injectedHistory = yield* Ref.make>([]); const refuseStarts = yield* Ref.make(0); @@ -1990,6 +1997,7 @@ describe("orchestration v2 provider switching", () => { capturedTurns, refuseStarts, refusalCause, + failResumeOnce, nativeThreadGeneration: generation, ...(inject === true ? { injectedHistory } : {}), }), @@ -2047,12 +2055,15 @@ describe("orchestration v2 provider switching", () => { yield* Ref.set(refuseStarts, 2); assert.equal(yield* run(2), "failed"); assert.equal(yield* run(3), "failed"); + yield* Ref.set(failResumeOnce, loseSession === true); assert.equal(yield* run(4), "completed"); const turns = yield* Ref.get(capturedTurns); assert.equal(turns.length, 2); - assert.equal(yield* Ref.get(generation), 1); - assert.equal(turns[1]?.nativeThreadId, turns[0]?.nativeThreadId); + assert.equal(yield* Ref.get(generation), loseSession === true ? 2 : 1); + if (loseSession !== true) { + assert.equal(turns[1]?.nativeThreadId, turns[0]?.nativeThreadId); + } const delivered = `${turns[1]?.text}${JSON.stringify(yield* Ref.get(injectedHistory))}`; assert.include(delivered, "Request 2"); assert.include(delivered, "Request 3"); From de7b5e05f6a95573f65c923727fe84542a5b86e9 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 17 Nov 2026 12:03:43 -0800 Subject: [PATCH 080/133] fix(server): t3_thread_read names the thread a pasted link points to (#38301) --- .../src/mcp/OrchestratorMcpService.test.ts | 25 +++++++++++ apps/server/src/mcp/threadAccess.ts | 45 +++++++++++++++---- 2 files changed, 62 insertions(+), 8 deletions(-) diff --git a/apps/server/src/mcp/OrchestratorMcpService.test.ts b/apps/server/src/mcp/OrchestratorMcpService.test.ts index 6c488afe7d98..802f3dfd761e 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.test.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.test.ts @@ -30,6 +30,7 @@ import { type ServerProvider, } from "@t3tools/contracts"; import { checkpointWorkspace } from "@t3tools/provider-testing/replayWorkspace"; +import { formatThreadLink, hostedThreadLink } from "@t3tools/shared/threadLinks"; import * as DateTime from "effect/DateTime"; import * as Deferred from "effect/Deferred"; import * as Duration from "effect/Duration"; @@ -4634,6 +4635,30 @@ describe("OrchestratorMcpService thread lookup", () => { }), ); + it.effect("points a pasted thread link at the thread it names", () => + Effect.gen(function* () { + const delegated = liveThreadShell(ThreadId.make("thread:delegated-task:command%3Amcp%3Aabc")); + const ref = { environmentId: client.environmentId, threadId: delegated.id }; + const sent = yield* Ref.make(0); + yield* Effect.gen(function* () { + const mcp = yield* OrchestratorMcpService.OrchestratorMcpService; + for (const link of [ + `t3-thread://v2/${ref.environmentId}/${ref.threadId}`, + formatThreadLink(ref, "Delegated task"), + hostedThreadLink(ref), + ]) { + const read = yield* mcp + .readThread(client, { threadId: ThreadId.make(link) }) + .pipe(Effect.flip); + assert.equal(read.code, "thread_not_found"); + assert.include(read.message, `\`${delegated.id}\``); + assert.include(read.message, "is a thread link"); + assert.notInclude(read.message, "no longer available"); + } + }).pipe(Effect.provide(service([delegated], sent))); + }), + ); + it.effect("keeps the plain message for an id that matches nothing", () => Effect.gen(function* () { const { read, send, wait } = yield* failuresFor([]); diff --git a/apps/server/src/mcp/threadAccess.ts b/apps/server/src/mcp/threadAccess.ts index 8cce38949cdd..f387f481e24a 100644 --- a/apps/server/src/mcp/threadAccess.ts +++ b/apps/server/src/mcp/threadAccess.ts @@ -4,6 +4,7 @@ import type { } from "../orchestration-v2/ProjectionStore.ts"; import { CommandId, + type EnvironmentId, OrchestratorMcpFailure, type ProjectId, type ProviderInstanceId, @@ -12,6 +13,12 @@ import { ThreadId, type OrchestrationV2ThreadShell, } from "@t3tools/contracts"; +import { + hasThreadLinks, + parseThreadLinkHref, + threadLinkCandidates, + threadLinkRefs, +} from "@t3tools/shared/threadLinks"; import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Effect from "effect/Effect"; @@ -32,8 +39,22 @@ const suggestedThreadId = (threadId: ThreadId) => { return encoded === rest ? null : ThreadId.make(`${delegatedTaskPrefix}${encoded}`); }; +// A pasted link (bare, Markdown, or hosted) names its thread; only this environment's can be read here. +const candidateThreadIds = (threadId: ThreadId, environmentId: EnvironmentId) => { + if (!hasThreadLinks(threadId)) { + const suggested = suggestedThreadId(threadId); + return suggested === null ? [] : [suggested]; + } + const link = parseThreadLinkHref(threadId); + const refs = + link === null + ? threadLinkRefs(threadId, environmentId) + : threadLinkCandidates(link, environmentId); + return refs.filter((ref) => ref.environmentId === environmentId).map((ref) => ref.threadId); +}; + /** - * Agents paste bare uuids for `mcp:` threads and unencoded delegated-task ids. + * Agents paste bare uuids for `mcp:` threads, unencoded delegated-task ids, and thread links. * The id is never rewritten, so permission checks keyed on it still hold; the miss * only names a live thread the caller could read by its full id. Ids from another * machine miss here too. The link hint is static: listing links probes peers. @@ -44,13 +65,21 @@ export const threadNotFound = Effect.fn("OrchestratorMcpService.threadNotFound") threadId: ThreadId, message: string, ) { - const suggested = suggestedThreadId(threadId); - const shell = - suggested === null - ? null - : yield* threads.getThreadShell(suggested).pipe(Effect.orElseSucceed(() => null)); - const mcpHint = - shell === null || shell.deletedAt !== null ? "" : ` Did you mean \`${suggested}\`?`; + let suggested: ThreadId | null = null; + for (const candidate of candidateThreadIds(threadId, scope.environmentId)) { + const shell = yield* threads.getThreadShell(candidate).pipe(Effect.orElseSucceed(() => null)); + if (shell !== null && shell.deletedAt === null) { + suggested = candidate; + break; + } + } + if (suggested !== null && hasThreadLinks(threadId)) { + return yield* new OrchestratorMcpFailure({ + code: "thread_not_found", + message: `\`${threadId}\` is a thread link, not a thread id. Pass \`${suggested}\` instead.`, + }); + } + const mcpHint = suggested === null ? "" : ` Did you mean \`${suggested}\`?`; const caller = scope.thread === undefined ? null From fd7d2aec5e437eea0d644fe47c3645efcc7cb4b9 Mon Sep 17 00:00:00 2001 From: Patryk Slowinski Date: Tue, 17 Nov 2026 20:05:05 +0000 Subject: [PATCH 081/133] fix(azure-devops): issue list no longer fails looking up the signed-in account (#38069) --- .../server/AzureDevOpsIssueTracker.test.ts | 9 ++++++ .../src/server/AzureDevOpsIssueTracker.ts | 31 ++----------------- .../src/server/azureDevOpsIssueJson.ts | 15 --------- 3 files changed, 12 insertions(+), 43 deletions(-) diff --git a/packages/source-control-azure-devops/src/server/AzureDevOpsIssueTracker.test.ts b/packages/source-control-azure-devops/src/server/AzureDevOpsIssueTracker.test.ts index 9c70956d3f6c..5bd495bca73e 100644 --- a/packages/source-control-azure-devops/src/server/AzureDevOpsIssueTracker.test.ts +++ b/packages/source-control-azure-devops/src/server/AzureDevOpsIssueTracker.test.ts @@ -290,6 +290,15 @@ describe("AzureDevOpsIssueTracker", () => { }).pipe(Effect.provide(NodeFileSystem.layer)), ); + it.effect("names the viewer without a request that a sign-in could refuse", () => + Effect.gen(function* () { + const api = yield* tracker((args) => { + throw new Error(`unexpected az invocation ${args.join(" ")}`); + }); + expect(yield* api.getViewer({ cwd: "/w", host: "dev.azure.com" })).toBe("@Me"); + }), + ); + it.effect("refuses a scope that is not organization/project without a request", () => Effect.gen(function* () { let requests = 0; diff --git a/packages/source-control-azure-devops/src/server/AzureDevOpsIssueTracker.ts b/packages/source-control-azure-devops/src/server/AzureDevOpsIssueTracker.ts index e04d5149daf7..40dfd6df986e 100644 --- a/packages/source-control-azure-devops/src/server/AzureDevOpsIssueTracker.ts +++ b/packages/source-control-azure-devops/src/server/AzureDevOpsIssueTracker.ts @@ -26,7 +26,6 @@ import { closedStateNames, workItemStates, decodeCommentsJson, - decodeProfileJson, decodeUpdatesJson, decodeWorkItemJson, decodeWorkItemsJson, @@ -580,33 +579,9 @@ export const make: Effect.Effect< kind: KIND, capabilities: CAPABILITIES, - // The profile the token belongs to, which is what WIQL's `@Me` resolves to. Its email is the - // `uniqueName` every identity on a work item carries, so the two compare. - getViewer: (input) => - read({ - cwd: input.cwd, - operation: "getViewer", - args: [ - "devops", - "invoke", - "--detect", - "true", - "--area", - "profile", - "--resource", - "profiles", - "--api-version", - REST_API_VERSION, - "--route-parameters", - "id=me", - ], - decode: decodeProfileJson, - }).pipe( - Effect.filterOrFail( - (login) => login !== null, - () => refused("getViewer", "Azure DevOps could not name the signed-in account."), - ), - ), + // Listing filters with WIQL's `@Me`, so nothing compares against a name. Looking one up + // needs a profile host that a PAT saved for one organization cannot reach. + getViewer: () => Effect.succeed("@Me"), listIssues: Effect.fn("AzureDevOpsIssueTracker.listIssues")(function* (input) { const cursor = input.cursor === undefined ? undefined : parseCursor(input.cursor); diff --git a/packages/source-control-azure-devops/src/server/azureDevOpsIssueJson.ts b/packages/source-control-azure-devops/src/server/azureDevOpsIssueJson.ts index 6b932648d3a5..6d7a4486e9dc 100644 --- a/packages/source-control-azure-devops/src/server/azureDevOpsIssueJson.ts +++ b/packages/source-control-azure-devops/src/server/azureDevOpsIssueJson.ts @@ -425,18 +425,3 @@ export function pullRequestNumberOf(relation: typeof Relation.Type): number | nu const number = decodeURIComponent(match[1]!).split("/").at(-1) ?? ""; return /^[1-9]\d{0,9}$/.test(number) ? Number(number) : null; } - -const Profile = Schema.Struct({ - emailAddress: Schema.optional(Schema.NullOr(Schema.String)), - displayName: Schema.optional(Schema.NullOr(Schema.String)), -}); - -const decodeProfile = decodeJsonResult(Profile); - -/** `GET profile/profiles/me` names the signed-in account, which WIQL's `@Me` compares against. */ -export function decodeProfileJson(raw: string): Result.Result { - return Result.map( - decodeProfile(raw), - (profile) => trimmed(profile.emailAddress) ?? trimmed(profile.displayName), - ); -} From 439c96550c670281170b090e48ffd5ef32d16941 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 17 Nov 2026 12:11:41 -0800 Subject: [PATCH 082/133] fix(server): review diffs no longer stall on large reordered files (#38308) --- apps/server/src/vcs/GitVcsDriverCore.test.ts | 12 +++++------- apps/server/src/vcs/GitVcsDriverCore.ts | 1 - 2 files changed, 5 insertions(+), 8 deletions(-) diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.ts index 302200c08993..6cb91ad2dd04 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.test.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts @@ -4702,7 +4702,7 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); - it.effect("reads Changes totals without minimizing and keeps review diffs minimal", () => + it.effect("reads Changes totals and review diffs without minimizing", () => Effect.gen(function* () { const cwd = yield* makeTmpDir(); const { initialBranch } = yield* initRepoWithCommit(cwd); @@ -4734,10 +4734,8 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { deletions: Number(deletions), }); - const [additions, removals] = minimalStat.split("\t"); - const minimalPatch = yield* git(cwd, [ + const defaultPatch = yield* git(cwd, [ "diff", - "--minimal", "--patch", "--no-color", "--no-ext-diff", @@ -4754,11 +4752,11 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { path: "repeated.txt", previousPath: null, changeType: "change", - additions: Number(additions), - deletions: Number(removals), + additions: Number(insertions), + deletions: Number(deletions), }, ]); - assert.strictEqual(source.diff.trim(), minimalPatch); + assert.strictEqual(source.diff.trim(), defaultPatch); } }), ); diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index 466724edba7e..48664332e760 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -4239,7 +4239,6 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const diffArgs = [ ...REVIEW_DIFF_ARGS, - "--minimal", ...(input.ignoreWhitespace ? ["--ignore-all-space"] : []), ]; const readStats = Effect.fn("GitVcsDriver.getReviewDiffPreview.stat")(function* ( From b3df47942a528f172065e7a1c04d07632d68a4ce Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 17 Nov 2026 12:16:45 -0800 Subject: [PATCH 083/133] fix(ci): a PR title edit no longer cancels the native fingerprint check (#38316) --- .github/workflows/mobile-fingerprint-check.yml | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/.github/workflows/mobile-fingerprint-check.yml b/.github/workflows/mobile-fingerprint-check.yml index 437f16c4684b..11d2ee60e122 100644 --- a/.github/workflows/mobile-fingerprint-check.yml +++ b/.github/workflows/mobile-fingerprint-check.yml @@ -19,12 +19,15 @@ on: types: [opened, synchronize, reopened, edited] concurrency: - group: mobile-fingerprint-check-${{ github.event.pull_request.number }} + # A title or body edit gets its own group, so it cannot cancel the PR's real + # run and leave a cancelled check on the head commit. + group: mobile-fingerprint-check-${{ github.event.action == 'edited' && !github.event.changes.base && format('edit-{0}', github.run_id) || github.event.pull_request.number }} cancel-in-progress: true jobs: fingerprint: name: Native fingerprint diff + if: github.event.action != 'edited' || github.event.changes.base runs-on: blacksmith-8vcpu-ubuntu-2404 permissions: contents: read From e3949714e3a513c0fa3a6eab0ea3c140f9c5399a Mon Sep 17 00:00:00 2001 From: Bilal Bakr <62337003+Bil0000@users.noreply.github.com> Date: Tue, 17 Nov 2026 23:17:32 +0300 Subject: [PATCH 084/133] fix(web): restore the Issues right panel shortcut (#38309) Co-authored-by: Julius Marminge --- apps/web/src/components/issue/IssuesPage.tsx | 22 +++++++++++++++++-- ...issues-shortcut-toggles-right-panel.e2e.ts | 22 +++++++++++++++++++ 2 files changed, 42 insertions(+), 2 deletions(-) create mode 100644 scripts/scenarios/issues-shortcut-toggles-right-panel.e2e.ts diff --git a/apps/web/src/components/issue/IssuesPage.tsx b/apps/web/src/components/issue/IssuesPage.tsx index b676dc74eb57..368eba36449c 100644 --- a/apps/web/src/components/issue/IssuesPage.tsx +++ b/apps/web/src/components/issue/IssuesPage.tsx @@ -32,7 +32,7 @@ import { UserCheckIcon, UsersIcon, } from "lucide-react"; -import { Fragment, useEffect, useState, type ReactNode } from "react"; +import { Fragment, useEffect, useEffectEvent, useState, type ReactNode } from "react"; import { RefreshIcon } from "~/components/ui/refresh-icon"; import { IssueDetailPanel } from "~/components/issue/IssueDetailPanel"; @@ -70,9 +70,10 @@ import { } from "~/components/ui/empty"; import { Menu, MenuPopup, MenuRadioGroup, MenuRadioItem, MenuTrigger } from "~/components/ui/menu"; import { SidebarInset } from "~/components/ui/sidebar"; +import { isCommandPaletteOpen } from "~/commandPaletteBus"; import { isElectron } from "~/env"; import { useLiveRefresh } from "~/hooks/useLiveRefresh"; -import { shortcutLabelForCommand } from "~/keybindings"; +import { resolveShortcutCommand, shortcutLabelForCommand } from "~/keybindings"; import { isTerminalFocused } from "~/lib/terminalFocus"; import { usePanelAnimationSettings, usePanelPresence } from "~/panelAnimations"; import { @@ -404,6 +405,23 @@ export function IssuesPage() { selectSurfaceInUrl(panelSurface); }; + const onRightPanelKeyDown = useEffectEvent((event: KeyboardEvent) => { + if (event.defaultPrevented || isCommandPaletteOpen() || panelSurface === null) return; + const command = resolveShortcutCommand(event, keybindings, { + context: { ...getShortcutContext(), rightPanelOpen: rightPanelState.isOpen }, + }); + if (command !== "rightPanel.toggle") return; + event.preventDefault(); + event.stopPropagation(); + if (!event.repeat) toggleRightPanel(); + }); + + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes to the document right panel shortcut + useEffect(() => { + document.addEventListener("keydown", onRightPanelKeyDown); + return () => document.removeEventListener("keydown", onRightPanelKeyDown); + }, []); + // Every writable scope the workspace has, for the composer. const showTracker = groups.length > 1; diff --git a/scripts/scenarios/issues-shortcut-toggles-right-panel.e2e.ts b/scripts/scenarios/issues-shortcut-toggles-right-panel.e2e.ts new file mode 100644 index 000000000000..00007afdfc44 --- /dev/null +++ b/scripts/scenarios/issues-shortcut-toggles-right-panel.e2e.ts @@ -0,0 +1,22 @@ +import { expect } from "e2e"; + +import { test, WEB } from "./t3.ts"; + +test( + "The right panel shortcut closes and reopens the Issues panel", + WEB, + async ({ t3, app, browser, screen }) => { + await t3.project("demo"); + await t3.open("/issues?selectedProjectId=demo&tracker=github&scope=example/demo&key=42"); + + const toggle = screen.getByRole("button", "Toggle right panel"); + await screen.getByRole("button", { name: "Toggle right panel", pressed: true }).waitFor(); + + await browser.keyboard.press("ControlOrMeta+Alt+b"); + await app.screenshot("after-close-shortcut"); + await expect(toggle).toHaveAttribute("aria-pressed", "false"); + + await browser.keyboard.press("ControlOrMeta+Alt+b"); + await expect(toggle).toHaveAttribute("aria-pressed", "true"); + }, +); From 13ecf5b22ee9b135f75ad8b78cd120e3c5379037 Mon Sep 17 00:00:00 2001 From: Yash Singh Date: Tue, 17 Nov 2026 14:21:27 -0600 Subject: [PATCH 085/133] feat(cursor): edit earlier messages by rewinding the Cursor agent (#38262) Co-authored-by: Cursor --- docs/user/cursor.md | 9 +- .../src/server/CursorAgentSdk.test.ts | 58 +++++++++ .../src/server/CursorAgentSdk.ts | 70 ++++++++++ .../src/server/adapter.test.ts | 96 ++++++++++++-- .../provider-cursor/src/server/adapter.ts | 120 ++++++++++++++++-- .../provider-cursor/src/server/status.test.ts | 2 +- packages/provider-cursor/src/server/status.ts | 2 +- 7 files changed, 329 insertions(+), 28 deletions(-) diff --git a/docs/user/cursor.md b/docs/user/cursor.md index a71080de9308..f10ca24fb596 100644 --- a/docs/user/cursor.md +++ b/docs/user/cursor.md @@ -54,14 +54,17 @@ The adapter supports: - Cursor `task` subagents, projected as read-only child app threads with their tool activity and final result. -The public SDK does not currently expose native agent fork, conversation rollback, or interactive -approval callbacks. A text-only steer reaches the current run without restarting it. +The public SDK does not currently expose native agent fork or interactive approval callbacks. A +text-only steer reaches the current run without restarting it. When Cursor cannot deliver the steer, the same message is queued for the next turn after this run finishes. If you press Stop, that follow-up stays held until you resume the queue. Steers with attachments and provider or runtime changes that must apply immediately interrupt and restart the run. Same-provider Cursor forks use the orchestrator's portable full-thread context handoff into a fresh -Cursor agent. The SDK has in-process custom callback tools, but the V2 adapter intentionally uses the +Cursor agent. **Edit from here** and checkpoint rollback rewind the same Cursor agent to just before +the selected message, as `cursor-agent`'s `/rewind` does, so it keeps its exact earlier history. +Rewinding to the thread's first message starts a fresh Cursor agent instead. +The SDK has in-process custom callback tools, but the V2 adapter intentionally uses the authenticated, thread-scoped MCP server instead. Portable handoffs summarize eligible timeline items and can omit the end of long messages. Read diff --git a/packages/provider-cursor/src/server/CursorAgentSdk.test.ts b/packages/provider-cursor/src/server/CursorAgentSdk.test.ts index 8809849c53b6..842fcd59a272 100644 --- a/packages/provider-cursor/src/server/CursorAgentSdk.test.ts +++ b/packages/provider-cursor/src/server/CursorAgentSdk.test.ts @@ -205,6 +205,64 @@ describe("CursorAgentSdkRunner", () => { }).pipe(Effect.provide(NodeServices.layer)), ); + it.effect("rewinds the agent to the state its first unwound run started from", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const workspace = yield* fileSystem.makeTempDirectoryScoped({ prefix: "cursor-rewind-" }); + const loaders = yield* Effect.promise(() => + vi.importActual("./sdk.ts"), + ); + const sdk = loaders.loadCursorSdk(); + const store = new sdk.JsonlLocalAgentStore(workspace); + const platform = yield* Effect.promise(() => + sdk.createAgentPlatform({ localStore: store, workspaceRef: workspace }), + ); + const { agent, run: first } = yield* Effect.promise(() => + platform.store.createAgent({ agentId: "agent-rewind", workspaceRef: workspace }), + ); + const finishRun = (runId: string, state: string) => + Effect.promise(async () => { + const checkpoint = await platform.checkpointStore.saveCheckpoint(agent.agentId, { + toBinary: () => new TextEncoder().encode(state), + }); + await platform.store.patchCheckpoint(agent.agentId, runId, checkpoint); + await platform.store.markRunTerminal(agent.agentId, runId, { status: "FINISHED" }); + return checkpoint.blobId; + }); + const followUp = Effect.promise(() => platform.store.createFollowUpRun(agent.agentId, {})); + const head = Effect.promise( + async () => (await platform.store.getAgent(agent.agentId))?.latestCheckpointRef?.blobId, + ); + + const afterFirst = yield* finishRun(first.runId, "after first"); + const second = yield* followUp; + yield* finishRun(second.runId, "after second"); + const third = yield* followUp; + const afterThird = yield* finishRun(third.runId, "after third"); + + const runner = yield* CursorAgentSdk.makeCursorAgentSdkRunner(() => undefined).pipe( + Effect.provideService(CursorSdk.CursorSdk, { + load: loaders.loadCursorSdk, + loadSqlite: loaders.loadCursorSqlite, + }), + ); + const session = yield* runner.open({ + operation: "resume", + agentId: agent.agentId, + storeCwd: workspace, + options: { apiKey: "synthetic-cursor-key", local: { cwd: workspace, store } }, + threadId: ThreadId.make("rewind"), + providerSessionId: ProviderSessionId.make("rewind"), + }); + + yield* session.rewindAfterRun!(third.runId); + assert.strictEqual(yield* head, afterThird, "nothing ran after the kept run"); + yield* session.rewindAfterRun!(first.runId); + assert.strictEqual(yield* head, afterFirst); + yield* session.close; + }).pipe(Effect.provide(NodeServices.layer)), + ); + it.effect("constructs without loading and reports first-use load failures as runner errors", () => Effect.gen(function* () { const failure = new Error("missing SDK chunk"); diff --git a/packages/provider-cursor/src/server/CursorAgentSdk.ts b/packages/provider-cursor/src/server/CursorAgentSdk.ts index e76d5cf4a6ea..c70ad22145de 100644 --- a/packages/provider-cursor/src/server/CursorAgentSdk.ts +++ b/packages/provider-cursor/src/server/CursorAgentSdk.ts @@ -137,6 +137,11 @@ export interface CursorAgentSdkSession { * run only from its first checkpoint on; before that the conversation lacks the run's request. */ readonly runCheckpointed?: (runId?: string) => Effect.Effect; + /** + * Rewinds the conversation to just before the run after `runId`, as `cursor-agent` /rewind does. + * The open agent keeps its old conversation in memory, so reopen it before the next send. + */ + readonly rewindAfterRun?: (runId: string) => Effect.Effect; readonly close: Effect.Effect; } @@ -277,6 +282,15 @@ export type CursorAgentSdkProtocolLogEvent = readonly agentId: string; }; } + | { + readonly direction: "outgoing"; + readonly stage: "decoded"; + readonly payload: { + readonly type: "agent.rewind"; + readonly agentId: string; + readonly afterRunId: string; + }; + } | { readonly direction: "incoming"; readonly stage: "decoded"; @@ -834,6 +848,62 @@ export const makeCursorAgentSdkRunner = Effect.fn("makeCursorAgentSdkRunner")(fu }, catch: (cause) => runnerError(cause, "agent.run.get"), }), + rewindAfterRun: (runId) => + log({ + direction: "outgoing", + stage: "decoded", + payload: { type: "agent.rewind", agentId: agent.agentId, afterRunId: runId }, + }).pipe( + Effect.andThen( + Effect.tryPromise({ + try: async () => { + const { store, checkpointStore } = await storeView(); + const runs: Array = []; + let cursor: string | undefined; + do { + const page = await store.listRuns( + agent.agentId, + cursor === undefined ? {} : { cursor }, + ); + runs.push(...page.items); + cursor = page.nextCursor; + } while (cursor !== undefined); + const kept = runs.find((candidate) => candidate.runId === runId); + if (kept === undefined) { + throw new Error(`Cursor agent ${agent.agentId} has no run ${runId}.`); + } + const unwound = runs + .filter((candidate) => candidate.turnNumber > kept.turnNumber) + .toSorted((a, b) => a.turnNumber - b.turnNumber)[0]; + if (unwound === undefined) return; + const anchor = unwound.startCheckpointRef?.blobId; + if (anchor === undefined) { + throw new Error(`Cursor run ${unwound.runId} has no starting checkpoint.`); + } + const blobStore = await checkpointStore.getBlobStore(agent.agentId); + const getBlob = + typeof blobStore === "object" && blobStore !== null + ? Reflect.get(blobStore, "getBlob") + : undefined; + if (typeof getBlob !== "function") { + throw new Error("Cursor's checkpoint store cannot read blobs."); + } + const bytes: unknown = await getBlob.call( + blobStore, + undefined, + Buffer.from(anchor, "hex"), + ); + if (!(bytes instanceof Uint8Array)) { + throw new Error(`Cursor checkpoint ${anchor} is missing.`); + } + // Checkpoints are content-addressed, so re-saving the anchor's bytes moves the + // agent's head back to that exact root, like cursor-agent's latestRootBlobId reset. + await checkpointStore.saveCheckpoint(agent.agentId, { toBinary: () => bytes }); + }, + catch: (cause) => runnerError(cause, "agent.rewind"), + }), + ), + ), close: log({ direction: "outgoing", stage: "decoded", diff --git a/packages/provider-cursor/src/server/adapter.test.ts b/packages/provider-cursor/src/server/adapter.test.ts index 9fa8bfe26489..919e5f3de666 100644 --- a/packages/provider-cursor/src/server/adapter.test.ts +++ b/packages/provider-cursor/src/server/adapter.test.ts @@ -6,9 +6,11 @@ import { assert, describe, it } from "@effect/vitest"; import type { InteractionUpdate } from "@cursor/sdk"; import { toolOutputImages } from "@t3tools/shared/toolOutput"; import { + CheckpointId, EnvironmentId, MessageId, NodeId, + type OrchestrationV2ProviderTurn, ProjectId, ProviderInstanceId, ProviderSessionId, @@ -757,6 +759,9 @@ describe("CursorAdapterV2", () => { const fileSystem = yield* FileSystem.FileSystem; const workspace = yield* fileSystem.makeTempDirectoryScoped({ prefix: "cursor-v2-device-" }); const sentMessages: Array = []; + const rewoundAfter: Array = []; + let rewindFails = false; + let createdAgents = 0; const instanceId = ProviderInstanceId.make("cursor"); const threadId = ThreadId.make("cursor-device-thread"); const mcpSessions = yield* McpProviderSessions.McpProviderSessions; @@ -783,11 +788,21 @@ describe("CursorAdapterV2", () => { }).pipe( Effect.provideService(CursorAgentSdk.CursorAgentSdkRunner, { assertComplete: Effect.void, - open: () => - Effect.succeed({ - agentId: "native-cursor-device", + open: (openInput) => { + const agentId = openInput.agentId ?? `native-cursor-device-${++createdAgents}`; + return Effect.succeed({ + agentId, listMessages: Effect.succeed([]), close: Effect.void, + rewindAfterRun: (runId) => + rewindFails + ? Effect.fail( + new CursorAgentSdk.CursorAgentSdkRunnerError({ + method: "agent.rewind", + cause: "store unavailable", + }), + ) + : Effect.sync(() => void rewoundAfter.push(runId)), send: (input) => Effect.sync(() => { sentMessages.push( @@ -795,7 +810,7 @@ describe("CursorAdapterV2", () => { ); const runId = `native-cursor-run-${sentMessages.length}`; return { - agentId: "native-cursor-device", + agentId, runId, wait: Effect.succeed({ id: runId, @@ -807,7 +822,8 @@ describe("CursorAdapterV2", () => { cancel: Effect.void, }; }), - }), + }); + }, }), Effect.provide(TestProviderHost.layer({ cwd: workspace })), ); @@ -817,7 +833,7 @@ describe("CursorAdapterV2", () => { modelSelection, runtimePolicy, }); - const providerThread = yield* runtime.ensureThread({ + let providerThread = yield* runtime.ensureThread({ threadId, modelSelection, runtimePolicy, @@ -848,13 +864,15 @@ describe("CursorAdapterV2", () => { }; // Starts at run 5: a conversation from before device instructions existed, now resumed. let runOrdinal = 4; - const send = Effect.fnUntraced(function* (compact = false) { + let lastProviderTurn: OrchestrationV2ProviderTurn | undefined; + const send = Effect.fnUntraced(function* (compact = false, nativeThreadHasTurns?: boolean) { runOrdinal += 1; const turnInput = { threadId, providerThread, modelSelection, runtimePolicy, + ...(nativeThreadHasTurns === undefined ? {} : { nativeThreadHasTurns }), runId: RunId.make(`cursor-device-run-${runOrdinal}`), runOrdinal, providerTurnOrdinal: runOrdinal, @@ -870,10 +888,13 @@ describe("CursorAdapterV2", () => { }, }; yield* compact ? runtime.compactThread!(turnInput) : runtime.startTurn(turnInput); - yield* runtime.events.pipe( - Stream.filter((event) => event.type === "turn.terminal"), - Stream.runHead, + const events = yield* runtime.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runCollect, ); + const providerTurn = events.findLast((event) => event.type === "provider_turn.updated"); + if (providerTurn?.type === "provider_turn.updated") + lastProviderTurn = providerTurn.providerTurn; const sent = sentMessages.at(-1)!; return { orchestration: sent.includes("## T3 Code orchestration"), @@ -896,6 +917,61 @@ describe("CursorAdapterV2", () => { yield* setDeviceAccess(true); assert.deepEqual(yield* send(), told(false, true), "device access turned on later"); assert.deepEqual(yield* send(), told(false, false)); + + const keptTurn = lastProviderTurn!; + yield* send(); + const rollbackToKept = runtime.rollbackThread({ + providerThread, + target: { + type: "provider_turn", + checkpointId: CheckpointId.make("cursor-device-kept-checkpoint"), + appRunOrdinal: runOrdinal - 1, + providerTurn: keptTurn, + }, + providerThreadTurns: [keptTurn], + }); + rewindFails = true; + yield* Effect.flip(rollbackToKept); + rewindFails = false; + assert.deepEqual( + yield* send(false, true), + told(false, false), + "a failed rewind leaves the conversation, and what it was told, unchanged", + ); + const rewound = yield* rollbackToKept; + assert.deepEqual(rewoundAfter, [keptTurn.nativeTurnRef?.nativeId]); + assert.deepEqual( + rewound.providerThread.nativeThreadRef, + providerThread.nativeThreadRef, + "Cursor rewinds the same agent", + ); + assert.deepEqual( + yield* send(false, true), + told(true, true), + "the rewound conversation may have dropped instructions a later turn carried", + ); + + const rolledBack = yield* runtime.rollbackThread({ + providerThread, + target: { + type: "thread_start", + checkpointId: CheckpointId.make("cursor-device-checkpoint"), + appRunOrdinal: 0, + }, + providerThreadTurns: [], + }); + assert.strictEqual(rolledBack.providerThread.id, providerThread.id); + assert.notStrictEqual( + rolledBack.providerThread.nativeThreadRef?.nativeId, + providerThread.nativeThreadRef?.nativeId, + "a rollback to the thread's start has no checkpoint to rewind onto", + ); + providerThread = rolledBack.providerThread; + assert.deepEqual( + yield* send(false, false), + told(true, true), + "the fresh agent after a rollback has been told nothing", + ); }).pipe( Effect.scoped, Effect.provide( diff --git a/packages/provider-cursor/src/server/adapter.ts b/packages/provider-cursor/src/server/adapter.ts index 04c6aa780e7d..a72773c18ea3 100644 --- a/packages/provider-cursor/src/server/adapter.ts +++ b/packages/provider-cursor/src/server/adapter.ts @@ -90,7 +90,7 @@ export const CursorProviderCapabilitiesV2 = { threads: { canCreateEmptyThread: true, canReadThreadSnapshot: true, - canRollbackThread: false, + canRollbackThread: true, canForkThread: false, canForkFromTurn: false, canForkFromSubagentThread: false, @@ -162,8 +162,8 @@ export const CursorProviderCapabilitiesV2 = { checkpointing: { appCanCheckpointFilesystem: true, supportsNestedCheckpointScopes: true, - providerCanRollbackConversation: false, - providerRollbackReturnsSnapshot: false, + providerCanRollbackConversation: true, + providerRollbackReturnsSnapshot: true, providerCanReadConversationSnapshot: true, }, identity: { @@ -2714,7 +2714,10 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( const delivered = known?.agent === agent.nativeThreadId ? known - : { orchestration: turnInput.runOrdinal > 1, device: false }; + : { + orchestration: turnInput.nativeThreadHasTurns ?? turnInput.runOrdinal > 1, + device: false, + }; const interrupted = yield* Ref.get(interruptedPrompt); const runCheckpointed = (runId?: string) => agent.session.runCheckpointed?.(runId) ?? Effect.succeed(false); @@ -3245,15 +3248,106 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( ), ), ), - rollbackThread: (rollbackInput) => - Effect.fail( - new ProviderAdapter.ProviderAdapterRollbackThreadError({ - driver: CursorAgentSdk.CURSOR_PROVIDER, - providerThreadId: rollbackInput.providerThread.id, - checkpointId: rollbackInput.target.checkpointId, - cause: "Cursor Agent SDK does not expose conversation rollback.", - }), - ), + rollbackThread: Effect.fn("CursorAdapterV2.rollbackThread")( + function* (rollbackInput: ProviderAdapter.ProviderAdapterV2RollbackThreadInput) { + const current = yield* Ref.get(activeTurn); + if (current !== null) { + return yield* new ProviderAdapter.ProviderAdapterProtocolError({ + driver: CursorAgentSdk.CURSOR_PROVIDER, + detail: `Cannot roll back Cursor provider thread ${rollbackInput.providerThread.id} while turn ${current.providerTurnId} is active.`, + }); + } + const threadId = rollbackInput.providerThread.appThreadId ?? input.threadId; + const { target } = rollbackInput; + // The kept turns may predate a compaction, so the instructions are sent again. + const forgetConversation = (agent: string) => + Effect.all([ + Ref.set(told, { agent, orchestration: false, device: false }), + Ref.set(interruptedPrompt, null), + Ref.set(resumedAgent, null), + ]); + const now = yield* DateTime.now; + if (target.type === "provider_turn") { + const keptRunId = target.providerTurn.nativeTurnRef?.nativeId; + if (keptRunId == null) { + return yield* new ProviderAdapter.ProviderAdapterProtocolError({ + driver: CursorAgentSdk.CURSOR_PROVIDER, + detail: `Provider turn ${target.providerTurn.id} has no Cursor run id.`, + }); + } + const agent = yield* openAgent({ + operation: "resume", + agentId: nativeThreadId(rollbackInput.providerThread), + storeCwd: rollbackInput.providerThread.nativeMetadata?.cursorStoreCwd, + threadId, + modelSelection: input.modelSelection, + runtimePolicy: input.runtimePolicy, + }); + if (agent.session.rewindAfterRun === undefined) { + return yield* new ProviderAdapter.ProviderAdapterProtocolError({ + driver: CursorAgentSdk.CURSOR_PROVIDER, + detail: "This Cursor SDK session cannot rewind its conversation.", + }); + } + yield* agent.session.rewindAfterRun(keptRunId); + yield* forgetConversation(agent.nativeThreadId); + yield* agent.session.close.pipe(Effect.ignore); + yield* Ref.set(liveAgent, null); + return { + providerThread: { + ...rollbackInput.providerThread, + providerSessionId: input.providerSessionId, + status: "idle" as const, + updatedAt: now, + }, + providerTurns: [], + messages: [], + runtimeRequests: [], + }; + } + // The first run starts without a checkpoint, so there is nothing to rewind onto. + const opened = yield* openAgent({ + operation: "create", + threadId, + modelSelection: input.modelSelection, + runtimePolicy: input.runtimePolicy, + }); + yield* forgetConversation(opened.nativeThreadId); + return { + providerThread: { + ...rollbackInput.providerThread, + providerSessionId: input.providerSessionId, + nativeThreadRef: { + driver: CursorAgentSdk.CURSOR_PROVIDER, + nativeId: opened.nativeThreadId, + strength: "strong" as const, + }, + nativeConversationHeadRef: null, + nativeMetadata: { + ...rollbackInput.providerThread.nativeMetadata, + cursorStoreCwd: opened.storeCwd, + }, + status: "idle" as const, + updatedAt: now, + }, + providerTurns: [], + messages: [], + runtimeRequests: [], + }; + }, + (effect, rollbackInput) => + effect.pipe( + Effect.mapError( + (cause) => + new ProviderAdapter.ProviderAdapterRollbackThreadError({ + driver: CursorAgentSdk.CURSOR_PROVIDER, + providerThreadId: rollbackInput.providerThread.id, + checkpointId: rollbackInput.target.checkpointId, + cause, + }), + ), + ), + ), forkThread: (forkInput) => Effect.fail( new ProviderAdapter.ProviderAdapterForkThreadError({ diff --git a/packages/provider-cursor/src/server/status.test.ts b/packages/provider-cursor/src/server/status.test.ts index 0ce81df747e3..8a979b51eb81 100644 --- a/packages/provider-cursor/src/server/status.test.ts +++ b/packages/provider-cursor/src/server/status.test.ts @@ -129,7 +129,7 @@ describe("buildCursorProviderSnapshot", () => { message: "Cursor SDK model discovery returned no built-in models.", models: [], slashCommands: [COMPACT_SLASH_COMMAND], - supportsConversationRollback: false, + supportsConversationRollback: true, }); }); }); diff --git a/packages/provider-cursor/src/server/status.ts b/packages/provider-cursor/src/server/status.ts index 570a7ac34f45..df50b2579939 100644 --- a/packages/provider-cursor/src/server/status.ts +++ b/packages/provider-cursor/src/server/status.ts @@ -27,7 +27,7 @@ import * as CursorSdkCatalog from "./CursorSdkCatalog.ts"; const CURSOR_PRESENTATION = { displayName: "Cursor", - supportsConversationRollback: false, + supportsConversationRollback: true, showInteractionModeToggle: true, } as const; const EMPTY_CAPABILITIES: ModelCapabilities = createModelCapabilities({ From 3d7b74a7ea3949185650eaf145852c2064c87a56 Mon Sep 17 00:00:00 2001 From: Ibrahim Elkamali Date: Tue, 17 Nov 2026 22:28:18 +0200 Subject: [PATCH 086/133] fix(server): omit ODF comments from extracted document text (#38313) Co-authored-by: Julius Marminge --- apps/server/src/provider/documentTextWorker.ts | 5 ++++- apps/server/src/provider/userInputAttachments.test.ts | 10 ++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/apps/server/src/provider/documentTextWorker.ts b/apps/server/src/provider/documentTextWorker.ts index 27556d3af9ac..ed67cba63f47 100644 --- a/apps/server/src/provider/documentTextWorker.ts +++ b/apps/server/src/provider/documentTextWorker.ts @@ -105,7 +105,10 @@ function xml(source: string, extension: string): XmlNode { const node = stack.pop()!; const parent = stack.at(-1)!; if (odf && (node.name === "p" || node.name === "h")) collapseOdfWhitespace(node); - if (extension === ".docx" && node.name === "del") { + if ( + (extension === ".docx" && node.name === "del") || + (odf && node.name === "annotation" && parent.name !== "semantics") + ) { parent.children.pop(); return; } diff --git a/apps/server/src/provider/userInputAttachments.test.ts b/apps/server/src/provider/userInputAttachments.test.ts index 88fbf9790a1a..53a670d9c1d7 100644 --- a/apps/server/src/provider/userInputAttachments.test.ts +++ b/apps/server/src/provider/userInputAttachments.test.ts @@ -763,6 +763,16 @@ describe("question answer paths", () => { expected: ["Fee $700"], absent: ["Reviewer", "$500"], }, + { + ext: "odt", + bounded: true, + parts: { + "content.xml": + '

Fee Reviewer2026-01-01T00:00:00JR

Check

$700

was 120

Formula x+yx+y

', + }, + expected: ["Fee $700\n150\nFormula x+yx+y"], + absent: ["Reviewer", "2026-01-01", "JR", "Check", "was 120"], + }, { ext: "docx", bounded: true, From 81fd06998c6656b48265157fa6dea44aed350ba2 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 17 Nov 2026 12:34:11 -0800 Subject: [PATCH 087/133] fix(server): steering onto another Codex instance keeps its context handoff row (#38320) --- .../src/orchestration-v2/Orchestrator.ts | 57 ++++++++++++++++++- .../SelectionRestart.integration.test.ts | 30 +++++++--- 2 files changed, 79 insertions(+), 8 deletions(-) diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 7d1248cebd41..9ca65a32f3cf 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -6157,6 +6157,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio readonly providerThreadId: OrchestrationV2ProviderThread["id"]; readonly providerInstanceId: ProviderInstanceId; readonly modelSwitch?: OrchestrationV2ModelSwitch | undefined; + readonly ordinal?: number; }) { const message: OrchestrationV2ConversationMessage = { createdBy: input.createdBy, @@ -6200,7 +6201,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio providerTurnId: messageInput.providerTurnId, nativeItemRef: null, parentItemId: null, - ordinal: yield* nextTurnItemOrdinal(input.projection), + ordinal: messageInput.ordinal ?? (yield* nextTurnItemOrdinal(input.projection)), status: "completed", title: null, startedAt: now, @@ -6700,6 +6701,59 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio messageId: targetRun.userMessageId, now, }); + const steeringOrdinal = yield* nextTurnItemOrdinal(input.projection); + if (restartHandoff !== null) { + const covered = restartHandoff.coveredRunOrdinals; + const coveredRuns = input.projection.runs.filter( + (run) => run.ordinal >= covered.from && run.ordinal <= covered.to, + ); + yield* emitEvent({ + type: "turn-item.updated", + threadId: input.command.threadId, + runId: targetRun.id, + nodeId: nextRootNodeId, + providerInstanceId: input.modelSelection.instanceId, + occurredAt: now, + payload: { + id: idAllocator.derive.runSignalTurnItem({ + runId: targetRun.id, + signal: `context-handoff:${restartHandoff.id}`, + }), + threadId: input.command.threadId, + runId: targetRun.id, + nodeId: nextRootNodeId, + providerThreadId: restartProviderThread.id, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: steeringOrdinal, + status: "completed", + title: "Provider handoff", + startedAt: now, + completedAt: now, + updatedAt: now, + type: "handoff", + contextHandoffId: restartHandoff.id, + fromProviderThreadIds: restartHandoff.fromProviderThreadIds, + toProviderThreadId: restartHandoff.toProviderThreadId, + fromProviderInstanceIds: Array.from( + new Set(coveredRuns.map((run) => run.providerInstanceId)), + ), + toProviderInstanceId: input.modelSelection.instanceId, + fromModelSelections: Array.from( + new Map( + coveredRuns.map((run) => [ + `${run.modelSelection.instanceId}\0${run.modelSelection.model}`, + run.modelSelection, + ]), + ).values(), + ), + toModel: input.modelSelection.model, + strategy: restartHandoff.strategy, + summary: restartHandoff.summaryText, + }, + }); + } yield* appendSteeringMessage({ runId: targetRun.id, nodeId: nextRootNodeId, @@ -6708,6 +6762,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio providerInstanceId: input.modelSelection.instanceId, // Measured on the pre-restart projection, so the rewritten run is not its own baseline. ...(restartHandoff === null ? modelSwitchSince(input.projection, input.modelSelection) : {}), + ordinal: restartHandoff === null ? steeringOrdinal : steeringOrdinal + 1, }); const interruptedAttemptId = targetRun.activeAttemptId; if (interruptedAttemptId === null) { diff --git a/apps/server/src/orchestration-v2/SelectionRestart.integration.test.ts b/apps/server/src/orchestration-v2/SelectionRestart.integration.test.ts index 7b12f72f4cea..683fb14d44cc 100644 --- a/apps/server/src/orchestration-v2/SelectionRestart.integration.test.ts +++ b/apps/server/src/orchestration-v2/SelectionRestart.integration.test.ts @@ -865,11 +865,22 @@ it.live( }), ); -it.live.each(["active", "idle", "selection-command", "pooled", "separate-home"] as const)( +const accountSwitchModes = [ + "active", + "idle", + "selection-command", + "pooled", + "separate-home", + "active-separate-home", +] as const; + +it.live.each(accountSwitchModes)( "preserves native history only for compatible account switches (%s)", (mode) => Effect.gen(function* () { const name = `shared-home-${mode}`; + const active = mode === "active" || mode === "active-separate-home"; + const separateHome = mode === "separate-home" || mode === "active-separate-home"; const cwd = yield* checkpointWorkspace(name); const threadId = ThreadId.make(`thread:${name}`); const targetId = ProviderInstanceId.make("codex-shadow-account"); @@ -918,8 +929,7 @@ it.live.each(["active", "idle", "selection-command", "pooled", "separate-home"] getMetadata: (instanceId) => Effect.succeed({ driver, - continuationKey: - mode === "separate-home" ? `codex:home:/${instanceId}` : "codex:home:/shared", + continuationKey: separateHome ? `codex:home:/${instanceId}` : "codex:home:/shared", enabled: true, capabilities, }), @@ -929,7 +939,7 @@ it.live.each(["active", "idle", "selection-command", "pooled", "separate-home"] const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; const selection = { ...initialSelection, - model: mode === "active" ? initialSelection.model : "complete", + model: active ? initialSelection.model : "complete", }; yield* orchestrator.dispatch({ type: "thread.create", @@ -949,7 +959,7 @@ it.live.each(["active", "idle", "selection-command", "pooled", "separate-home"] Effect.gen(function* () { const terminal = yield* orchestrator.streamDomainEvents.pipe( Stream.filter((event) => - mode === "active" && step === "first" + active && step === "first" ? event.type === "provider-turn.updated" && event.payload.status === "running" : event.type === "run.updated" && event.payload.status === "completed", ), @@ -994,14 +1004,20 @@ it.live.each(["active", "idle", "selection-command", "pooled", "separate-home"] const second = yield* dispatch( "second", targetSelection, - mode === "active" ? first.runs[0]!.id : undefined, + active ? first.runs[0]!.id : undefined, ); const targetThread = second.providerThreads.find( (thread) => thread.id === second.thread.activeProviderThreadId, )!; - if (mode === "separate-home") { + if (separateHome) { assert.notEqual(targetThread.id, originalThread.id); assert.lengthOf(second.contextHandoffs, 1); + assert.deepEqual( + second.turnItems.flatMap((item) => + item.type === "handoff" ? [item.contextHandoffId] : [], + ), + [second.contextHandoffs[0]!.id], + ); assert.lengthOf(second.contextTransfers, 1); assert.isEmpty(resumes); assert.notEqual(messages[1], "second"); From e9dc20d063e2244aa632fa275ee220ff029d4c28 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 17 Nov 2026 12:35:07 -0800 Subject: [PATCH 088/133] test(server): document extraction slot test no longer races its second waiter (#38322) --- apps/server/src/provider/userInputAttachments.test.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/apps/server/src/provider/userInputAttachments.test.ts b/apps/server/src/provider/userInputAttachments.test.ts index 53a670d9c1d7..79a9f0539534 100644 --- a/apps/server/src/provider/userInputAttachments.test.ts +++ b/apps/server/src/provider/userInputAttachments.test.ts @@ -134,6 +134,8 @@ describe("question answer paths", () => { Effect.provide(Layer.fresh(DocumentText.layer)), Effect.provideService(FileSystem.FileSystem, { ...fs, + // An async probe can let `staying` join only after `leaving` cancelled the lookup. + exists: (file) => Effect.sync(() => NodeFS.existsSync(file)), stat: (file) => Effect.gen(function* () { yield* Queue.offer(started, file); From b387e3a179d7495321019363c5ba11e847834cd0 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 17 Nov 2026 12:37:41 -0800 Subject: [PATCH 089/133] fix(server): Claude turns receive MCP app model context (#38307) --- .../Adapters/ClaudeAdapterV2.test.ts | 72 ++++++++++++++++++ .../Adapters/ClaudeAdapterV2.ts | 76 +++++++++++++++++-- 2 files changed, 143 insertions(+), 5 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index d0dda62b1ff2..ef09d0022ac8 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -6840,6 +6840,78 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); + // regression: #38284 an MCP app's update-model-context note must reach Claude's next turn + it.effect("sends MCP app model context with the next Claude turn", () => + Effect.gen(function* () { + const harness = yield* makeWakeHarnessWithOptions({ + close: (sdkMessages) => Queue.shutdown(sdkMessages), + freshQueueOnReopen: true, + }); + const runTurn = Effect.fnUntraced(function* (ordinal: number, note: string) { + yield* harness.runtime.startTurn({ + ...makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make(`mcp-app-context-${ordinal}`), + providerTurnOrdinal: ordinal, + text: "What did the app report?", + attachments: [], + }), + appContext: [{ key: "mcp_app_item-1", text: note }], + }); + const content = harness.offeredMessages.at(-1)?.message.content; + return typeof content === "string" + ? content + : (content ?? []).map((block) => (block.type === "text" ? block.text : "")).join("\n"); + }); + const finishTurn = Effect.fnUntraced(function* (ordinal: number) { + yield* harness.offerAndWait( + makeResultFrame({ uuid: `mcp-app-context-result-${ordinal}`, result: "Done." }), + ); + yield* Queue.take(harness.terminalReceipts); + }); + + assert.include(yield* runTurn(0, "Created Jira issue PROJ-42"), "PROJ-42"); + // A turn that does not complete may not have put the note in Claude's history. + yield* harness.runtime.interruptTurn({ + providerThread: harness.providerThread, + providerTurnId: (yield* IdAllocator.IdAllocatorV2).derive.providerTurn({ + driver: ClaudeAdapterV2.CLAUDE_PROVIDER, + nativeTurnId: "turn:mcp-app-context-0", + }), + }); + assert.equal((yield* Queue.take(harness.terminalReceipts)).status, "interrupted"); + assert.include(yield* runTurn(1, "Created Jira issue PROJ-42"), "PROJ-42"); + yield* finishTurn(1); + // Already in Claude's history: resending it every turn would only grow the context. + assert.notInclude(yield* runTurn(2, "Created Jira issue PROJ-42"), "PROJ-42"); + yield* finishTurn(2); + assert.include(yield* runTurn(3, "Created Jira issue PROJ-43"), "PROJ-43"); + yield* harness.offerAndWait( + claudeSdkFrame({ + type: "system", + subtype: "compact_boundary", + compact_metadata: { trigger: "auto", pre_tokens: 1500, post_tokens: 400 }, + uuid: "00000000-0000-4000-8000-000000038284", + session_id: WAKE_NATIVE_SESSION, + }), + ); + yield* finishTurn(3); + // Compaction summarizes the note away, so the next turn carries it again. + assert.include(yield* runTurn(4, "Created Jira issue PROJ-43"), "PROJ-43"); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + it.effect("sends the model id Claude Code reported for the selected catalog model", () => Effect.scoped( Effect.gen(function* () { diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index edb8ef01301a..abf31497a9ad 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -3022,6 +3022,37 @@ const reserveClaudePdfBudget = ( }).pipe(Effect.andThen(persist)), ); +// MCP app notes are app-written, so they go as quoted user input like Codex's untrusted context. +// A slash command runs only when it opens a plain-text prompt; its note waits for the next turn. +// Returns `message` itself when it adds nothing. +const withClaudeAppContext = ( + message: SDKUserMessage, + appContext: NonNullable, + reservation: Effect.Success>, +): SDKUserMessage => { + const content = message.message.content; + if (appContext.length === 0 || (typeof content === "string" && content.startsWith("/"))) { + return message; + } + const contextBlocks = appContext.map((entry) => ({ + type: "text" as const, + text: `${entry.text}`, + })); + const bytes = Buffer.byteLength(encodeClaudeJson(contextBlocks)); + reservation.budget.pending.bytes += bytes; + reservation.bytes += bytes; + return { + ...message, + message: { + ...message.message, + content: [ + ...contextBlocks, + ...(typeof content === "string" ? [{ type: "text" as const, text: content }] : content), + ], + }, + }; +}; + const makeClaudeUserMessageWithAttachments = Effect.fnUntraced(function* (input: { readonly text: string; readonly attachments: ReadonlyArray; @@ -5045,6 +5076,8 @@ interface ActiveClaudeTurnContext { readonly subagentsByToolUseId: Map; readonly promptUuid: string | null; promptEcho: "pending" | "confirmed"; + // MCP app notes this turn's prompt carries, recorded as delivered only if the turn completes. + appContextOffered?: ReadonlyMap | undefined; promptStarted: boolean; nativeWakeStarted: boolean; gatedFramesBeforeEcho: number; @@ -5889,6 +5922,8 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( // Sessions Claude Code reported gone on resume; resumeThread fails them into a fresh session. const missingNativeThreads = new Set(); const pdfBudgets = new Map>(); + // MCP app notes already in each native session's history, by key. Cleared when it compacts. + const deliveredAppContext = new Map>(); const latestPlanByKind = yield* Ref.make(new Map()); // Claude 5 task tools edit one list per native session, across turns. const taskListsByNativeThread = yield* Ref.make( @@ -9216,6 +9251,9 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( } else { yield* cutOffStreamedText(input.context); } + if (input.status === "completed" && input.context.appContextOffered !== undefined) { + deliveredAppContext.set(input.context.nativeThreadId, input.context.appContextOffered); + } // A turn that completes has taken in every steer; one that stops drops them unread. const droppedSteers = [...input.context.pendingSteers]; input.context.pendingSteers.clear(); @@ -10924,6 +10962,8 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( // Every trigger discards the conversation, so reset whatever the trigger is. if (message.type === "conversation_reset") { + deliveredAppContext.delete(context.nativeThreadId); + context.appContextOffered = undefined; if (context.streamUsage !== null) context.streamUsage.usage = null; context.compactionTokens = 0; yield* emitContextUsage(context, 0); @@ -10993,6 +11033,8 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( budget.compacting = null; yield* persistAttachmentBudget(context.nativeThreadId); } + deliveredAppContext.delete(context.nativeThreadId); + context.appContextOffered = undefined; if (context.streamUsage !== null) context.streamUsage.usage = null; const postTokens = message.compact_metadata.post_tokens; const afterTokenCount = @@ -13157,6 +13199,9 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( turnInput.message.text, compileClaudeModelSelection(turnInput.modelSelection, modelCatalog).promptEffort, ); + const appContext = turnInput.appContext ?? []; + const delivered = deliveredAppContext.get(nativeThreadId); + let appContextSent = false; const userMessage = promptUuid === null ? null @@ -13185,6 +13230,15 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( ...(skills === undefined ? {} : { skills }), uuid: promptUuid, }).pipe( + Effect.map((message) => { + const withContext = withClaudeAppContext( + message, + appContext.filter((entry) => delivered?.get(entry.key) !== entry.text), + pdfReservation, + ); + appContextSent = withContext !== message; + return withContext; + }), Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), Effect.provideService(Path.Path, path), ); @@ -13332,17 +13386,27 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( }), }); }); + // `offer` may call this twice; a second call must not restore notes compaction cleared. + let offerCommitted = false; + const commitOffer = () => { + if (offerCommitted) return; + offerCommitted = true; + pdfReservation.commit(); + if (appContextSent) { + context.appContextOffered = new Map( + appContext.map((entry) => [entry.key, entry.text]), + ); + } + }; const offerUserMessage = userMessage === null ? Effect.void : startUserTurnForWakeReports(nativeThreadId).pipe( Effect.andThen( Effect.uninterruptibleMask((restore) => - restore( - querySession.query.offer(userMessage, () => { - pdfReservation.commit(); - }), - ).pipe(Effect.tap(() => Effect.sync(() => pdfReservation.commit()))), + restore(querySession.query.offer(userMessage, commitOffer)).pipe( + Effect.tap(() => Effect.sync(commitOffer)), + ), ), ), ); @@ -14390,6 +14454,8 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( const nativeThreadId = yield* getNativeThreadId(rollbackInput.providerThread); yield* closeLiveQueryForNativeThread(nativeThreadId); + // The rewound history may no longer hold the turns that carried app notes. + deliveredAppContext.delete(nativeThreadId); const now = yield* DateTime.now; const resumeSessionAt = yield* resolveClaudeRollbackResumeSessionAt(rollbackInput); From 51eb2d5437b217b5f9a8e9eff4f97a8e353ce201 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 17 Nov 2026 13:13:29 -0800 Subject: [PATCH 090/133] fix(web): usage chart's screen-reader caption stays hidden in Firefox (#38332) --- .../components/usage/UsageProviderChart.tsx | 69 ++++++++++--------- 1 file changed, 36 insertions(+), 33 deletions(-) diff --git a/apps/web/src/components/usage/UsageProviderChart.tsx b/apps/web/src/components/usage/UsageProviderChart.tsx index 520fe45404a6..90c17d28011a 100644 --- a/apps/web/src/components/usage/UsageProviderChart.tsx +++ b/apps/web/src/components/usage/UsageProviderChart.tsx @@ -522,39 +522,42 @@ export function UsageProviderChart({
- {/* The plot and its axes are hover-only; this carries the same figures for screen readers. */} - - - - - - {providers.map((provider) => ( - - ))} - {providers.length > 1 ? : null} - - - - {periods.map((period, index) => { - const column = columns[index]; - return ( - - - {providers.map((provider) => ( - - ))} - {providers.length > 1 ? : null} - - ); - })} - -
- {`${resolution === "hour" ? "Hourly" : "Daily"} ${metric === "tokens" ? "processed tokens" : "cost"} by provider`} -
{resolution === "hour" ? "Hour" : "Day"} - {PROVIDER_PRESENTATION[provider].label} - Total
{formatTooltipPeriod(period)} - {format(column?.bands.find((band) => band.provider === provider)?.value ?? 0)} - {format(column?.total ?? 0)}
+ {/* The plot and its axes are hover-only; this carries the same figures for screen readers. + sr-only sits on a wrapper: Firefox does not clip a table's caption by the table's own box. */} +
+ + + + + + {providers.map((provider) => ( + + ))} + {providers.length > 1 ? : null} + + + + {periods.map((period, index) => { + const column = columns[index]; + return ( + + + {providers.map((provider) => ( + + ))} + {providers.length > 1 ? : null} + + ); + })} + +
+ {`${resolution === "hour" ? "Hourly" : "Daily"} ${metric === "tokens" ? "processed tokens" : "cost"} by provider`} +
{resolution === "hour" ? "Hour" : "Day"} + {PROVIDER_PRESENTATION[provider].label} + Total
{formatTooltipPeriod(period)} + {format(column?.bands.find((band) => band.provider === provider)?.value ?? 0)} + {format(column?.total ?? 0)}
+
); } From 94dc06e7ac13a337f9cbebe5f1f89d0d47976399 Mon Sep 17 00:00:00 2001 From: Aritra Das <64171580+Ari-03@users.noreply.github.com> Date: Tue, 17 Nov 2026 13:29:28 -0800 Subject: [PATCH 091/133] fix(cli): keep the old database when project or thread records are missing (#38325) Co-authored-by: Julius Marminge --- apps/server/src/cli/doctor.test.ts | 2 + apps/server/src/cli/doctor.ts | 17 ++++- .../persistence/DatabaseMaintenance.test.ts | 24 +++++++ .../src/persistence/DatabaseMaintenance.ts | 72 ++++++++++++++++--- docs/user/background-service.md | 5 +- 5 files changed, 107 insertions(+), 13 deletions(-) diff --git a/apps/server/src/cli/doctor.test.ts b/apps/server/src/cli/doctor.test.ts index aec121749498..6315378d07cb 100644 --- a/apps/server/src/cli/doctor.test.ts +++ b/apps/server/src/cli/doctor.test.ts @@ -68,6 +68,7 @@ it.effect( reclaimableBytes: 1000, incrementalVacuumEnabled: false, legacyDatabaseBytes: 4000, + legacyOnlyRecords: { projects: 0, threads: 0 }, }), compact: () => startServer.pipe( @@ -151,6 +152,7 @@ it.effect("warns how long reclaiming can take and reports each step with its ela reclaimableBytes: 0, incrementalVacuumEnabled: false, legacyDatabaseBytes: null, + legacyOnlyRecords: null, }), compact: (_databasePath, onStep) => Effect.gen(function* () { diff --git a/apps/server/src/cli/doctor.ts b/apps/server/src/cli/doctor.ts index a0bda9935164..50cd852e5b4b 100644 --- a/apps/server/src/cli/doctor.ts +++ b/apps/server/src/cli/doctor.ts @@ -68,10 +68,20 @@ export const runDoctor = Effect.fn("runDoctor")(function* ( yield* Console.log( `Database: ${formatBytes(status.databaseBytes)}, ${formatBytes(status.reclaimableBytes)} reclaimable.`, ); + const legacyRecords = status.legacyOnlyRecords; if (status.legacyDatabaseBytes !== null) { yield* Console.log( `Database from before 0.1.0: ${formatBytes(status.legacyDatabaseBytes)}, kept for rolling back.`, ); + if (legacyRecords === null) { + yield* Console.log( + " Could not check for missing projects or threads. Keep the old database.", + ); + } else if (legacyRecords.projects > 0 || legacyRecords.threads > 0) { + yield* Console.log( + ` The current database is missing legacy records. Projects missing: ${legacyRecords.projects}. Threads missing: ${legacyRecords.threads}. Keep the old database for recovery.`, + ); + } } const repairs = [ ...(status.incrementalVacuumEnabled && status.reclaimableBytes === 0 @@ -90,13 +100,16 @@ export const runDoctor = Effect.fn("runDoctor")(function* ( status.reclaimableBytes >= DATABASE_COMPACTION_RECOMMENDED_BYTES, }, ]), - ...(status.legacyDatabaseBytes === null + ...(status.legacyDatabaseBytes === null || + legacyRecords === null || + legacyRecords.projects > 0 || + legacyRecords.threads > 0 ? [] : [ { id: "legacy" as const, title: "Delete the database from before 0.1.0", - description: `Frees ${formatBytes(status.legacyDatabaseBytes)}. Your threads and settings are already in the current database.\n Warning: after this, a T3 Code version before 0.1.0 starts with no threads or settings, so you can no longer roll back.`, + description: `Frees ${formatBytes(status.legacyDatabaseBytes)}.\n Warning: after this, a T3 Code version before 0.1.0 starts with no threads or settings, so you can no longer roll back.`, recommended: false, }, ]), diff --git a/apps/server/src/persistence/DatabaseMaintenance.test.ts b/apps/server/src/persistence/DatabaseMaintenance.test.ts index 2621d366c04a..e186beb025f0 100644 --- a/apps/server/src/persistence/DatabaseMaintenance.test.ts +++ b/apps/server/src/persistence/DatabaseMaintenance.test.ts @@ -41,6 +41,8 @@ it.layer(DatabaseMaintenance.layer.pipe(Layer.provideMerge(NodeServices.layer))) const legacy = path.join(userdata, "state.sqlite"); yield* Effect.gen(function* () { const sql = yield* SqlClient.SqlClient; + yield* sql`CREATE TABLE projection_projects (project_id TEXT PRIMARY KEY)`; + yield* sql`CREATE TABLE orchestration_v2_projection_threads (thread_id TEXT PRIMARY KEY)`; yield* sql`CREATE TABLE retained_data (value TEXT)`; yield* sql`INSERT INTO retained_data VALUES ('keep')`; }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: dbPath }))); @@ -52,9 +54,31 @@ it.layer(DatabaseMaintenance.layer.pipe(Layer.provideMerge(NodeServices.layer))) yield* sql`PRAGMA journal_mode = WAL`; yield* sql`CREATE TABLE v1_data (value TEXT)`; yield* sql`INSERT INTO v1_data VALUES ('rollback')`; + yield* sql`CREATE TABLE projection_projects (project_id TEXT PRIMARY KEY, deleted_at TEXT)`; + yield* sql`CREATE TABLE projection_threads (thread_id TEXT PRIMARY KEY, deleted_at TEXT)`; + yield* sql`INSERT INTO projection_projects VALUES ('legacy-project', NULL)`; + yield* sql`INSERT INTO projection_threads VALUES ('legacy-thread', NULL), ('deleted-thread', '2026-10-01')`; }).pipe(Effect.provide(openLegacy)); assert.isAbove((yield* maintenance.inspect(dbPath)).legacyDatabaseBytes ?? 0, 0); + assert.deepEqual((yield* maintenance.inspect(dbPath)).legacyOnlyRecords, { + projects: 1, + threads: 1, + }); + const missing = yield* Effect.flip(maintenance.removeLegacyDatabase(dbPath)); + assert.equal(missing._tag, "LegacyDatabaseHasUnmigratedRecordsError"); + assert.isTrue(yield* fs.exists(legacy)); + + yield* Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* sql`INSERT INTO projection_projects VALUES ('legacy-project')`; + yield* sql`INSERT INTO orchestration_v2_projection_threads VALUES ('legacy-thread')`; + }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: dbPath }))); + assert.deepEqual((yield* maintenance.inspect(dbPath)).legacyOnlyRecords, { + projects: 0, + threads: 0, + }); + const refused = yield* Effect.gen(function* () { const sql = yield* SqlClient.SqlClient; yield* sql`SELECT value FROM v1_data`; diff --git a/apps/server/src/persistence/DatabaseMaintenance.ts b/apps/server/src/persistence/DatabaseMaintenance.ts index 07f2bdeecec6..bdb1c459f6e9 100644 --- a/apps/server/src/persistence/DatabaseMaintenance.ts +++ b/apps/server/src/persistence/DatabaseMaintenance.ts @@ -11,6 +11,7 @@ import * as Schema from "effect/Schema"; // @effect-diagnostics-next-line nodeBuiltinImport:off -- Effect has no free-space query. import * as NodeFSP from "node:fs/promises"; import * as NodeOS from "node:os"; +import * as NodeURL from "node:url"; import * as SqlClient from "effect/sql/SqlClient"; import { isSqlError } from "effect/sql/SqlError"; @@ -66,7 +67,16 @@ export class LegacyDatabaseRemoveError extends Schema.TaggedError()( + "LegacyDatabaseHasUnmigratedRecordsError", + { projects: Schema.Int, threads: Schema.Int }, +) { + override get message() { + return `The current database is missing legacy records. Projects missing: ${this.projects}. Threads missing: ${this.threads}. Keep the old database for recovery.`; } } @@ -79,6 +89,8 @@ export class DiskSpaceCheckError extends Schema.TaggedError } } +type LegacyOnlyRecords = { readonly projects: number; readonly threads: number }; + export type DatabaseCompactStep = "prune-events" | "vacuum" | "rebuild-search" | "checkpoint"; export class DatabaseMaintenance extends Context.Service< @@ -91,6 +103,7 @@ export class DatabaseMaintenance extends Context.Service< readonly incrementalVacuumEnabled: boolean; /** Size of the database from before 0.1.0 still kept beside it, or null. */ readonly legacyDatabaseBytes: number | null; + readonly legacyOnlyRecords: LegacyOnlyRecords | null; }, DatabaseMissingError | DatabaseInspectError >; @@ -113,7 +126,10 @@ export class DatabaseMaintenance extends Context.Service< /** Deletes only the pre-0.1.0 database; earlier versions still use it. */ readonly removeLegacyDatabase: ( databasePath: string, - ) => Effect.Effect; + ) => Effect.Effect< + void, + DatabaseInUseError | LegacyDatabaseRemoveError | LegacyDatabaseHasUnmigratedRecordsError + >; } >()("t3/persistence/DatabaseMaintenance") {} @@ -143,7 +159,7 @@ const lockExclusively = Effect.fn("DatabaseMaintenance.lockExclusively")(functio ) { const sql = yield* SqlClient.SqlClient; yield* sql`PRAGMA busy_timeout = 0`; - yield* sql`PRAGMA locking_mode = EXCLUSIVE`; + yield* sql`PRAGMA main.locking_mode = EXCLUSIVE`; yield* sql`BEGIN EXCLUSIVE`.pipe( Effect.mapError((cause) => isSqlError(cause) && cause.reason._tag === "LockTimeoutError" @@ -166,6 +182,29 @@ const make = Effect.gen(function* () { } }); + const readLegacyOnlyRecords = Effect.fn("DatabaseMaintenance.readLegacyOnlyRecords")(function* ( + databasePath: string, + ) { + const sql = yield* SqlClient.SqlClient; + const currentUri = `${NodeURL.pathToFileURL(databasePath).href}?mode=ro`; + yield* sql`ATTACH DATABASE ${currentUri} AS current_v2`; + const [counts] = yield* sql` + SELECT + (SELECT COUNT(*) FROM main.projection_projects legacy + WHERE legacy.deleted_at IS NULL AND NOT EXISTS ( + SELECT 1 FROM current_v2.projection_projects current + WHERE current.project_id = legacy.project_id + )) AS projects, + (SELECT COUNT(*) FROM main.projection_threads legacy + WHERE legacy.deleted_at IS NULL AND NOT EXISTS ( + SELECT 1 FROM current_v2.orchestration_v2_projection_threads current + WHERE current.thread_id = legacy.thread_id + )) AS threads + `; + if (!counts) return yield* Effect.die(new Error("Missing result from legacy database counts")); + return counts; + }); + const inspect = Effect.fn("DatabaseMaintenance.inspect")( function* (databasePath: string) { yield* locate(databasePath); @@ -176,7 +215,14 @@ const make = Effect.gen(function* () { const legacyDatabaseBytes = (yield* fs.exists(legacy)) ? Number((yield* fs.stat(legacy)).size) : null; - return { ...storage, legacyDatabaseBytes }; + const legacyOnlyRecords = + legacyDatabaseBytes === null + ? null + : yield* readLegacyOnlyRecords(databasePath).pipe( + Effect.provide(NodeSqliteClient.layer({ filename: legacy, readonly: true })), + Effect.orElseSucceed(() => null), + ); + return { ...storage, legacyDatabaseBytes, legacyOnlyRecords }; }, (effect, databasePath) => effect.pipe( @@ -242,21 +288,27 @@ const make = Effect.gen(function* () { { discard: true }, ); const connection = NodeSqliteClient.layer({ filename: legacy }); + const check = lockExclusively(legacy).pipe( + Effect.andThen(readLegacyOnlyRecords(databasePath)), + Effect.flatMap((counts) => + counts.projects > 0 || counts.threads > 0 + ? new LegacyDatabaseHasUnmigratedRecordsError(counts) + : Effect.void, + ), + ); if ((yield* HostProcess.Platform) === "win32") { // Windows blocks unlink while any SQLite handle is open, including our own. - yield* lockExclusively(legacy).pipe(Effect.provide(connection)); + yield* check.pipe(Effect.provide(connection)); yield* removeFiles; } else { - yield* lockExclusively(legacy).pipe( - Effect.andThen(removeFiles), - Effect.provide(connection), - ); + yield* check.pipe(Effect.andThen(removeFiles), Effect.provide(connection)); } }, (effect, databasePath) => effect.pipe( Effect.mapError((cause) => - cause._tag === "DatabaseInUseError" + cause._tag === "DatabaseInUseError" || + cause._tag === "LegacyDatabaseHasUnmigratedRecordsError" ? cause : new LegacyDatabaseRemoveError({ path: legacyPath(databasePath), cause }), ), diff --git a/docs/user/background-service.md b/docs/user/background-service.md index 1bc41addf8c9..fb3d3cca9a1b 100644 --- a/docs/user/background-service.md +++ b/docs/user/background-service.md @@ -199,4 +199,7 @@ once next to the database for its write-ahead log. If you upgraded from a version before 0.1.0, its database (`state.sqlite`) is still kept next to the current one so you can roll back. `t3 doctor` offers to delete it, but never selects that repair for you and `--fix` skips it: once it -is gone, a version before 0.1.0 starts with no threads or settings. +is gone, a version before 0.1.0 starts with no threads or settings. It does +not offer to delete it while any project or thread you have not deleted is +missing from the current database, so the old file stays available for +recovery. From 54ad956ff229045bc6d9a844457426d009c10250 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 17 Nov 2026 13:37:25 -0800 Subject: [PATCH 092/133] fix(server): file search keeps Git-ignored files a .ignore re-includes (#38337) --- .../src/workspace/WorkspaceEntries.test.ts | 6 +- .../workspace/WorkspaceSearchIndex.test.ts | 24 ++++++ .../src/workspace/WorkspaceSearchIndex.ts | 82 ++++++++++++------- 3 files changed, 80 insertions(+), 32 deletions(-) diff --git a/apps/server/src/workspace/WorkspaceEntries.test.ts b/apps/server/src/workspace/WorkspaceEntries.test.ts index 92d8bc882c95..363764ff70e8 100644 --- a/apps/server/src/workspace/WorkspaceEntries.test.ts +++ b/apps/server/src/workspace/WorkspaceEntries.test.ts @@ -618,7 +618,7 @@ it.layer(layerTest, { excludeTestServices: true })("WorkspaceEntries", (it) => { } }), ); - it.effect("lets the nearest .ignore rule decide a symlink, and git's rules still hide it", () => + it.effect("lets the nearest .ignore rule decide a symlink, ahead of git's rules", () => Effect.gen(function* () { if ((yield* HostProcess.Platform) === "win32") return; const cwd = yield* makeTempDir({ prefix: "t3code-workspace-symlinks-", git: true }); @@ -639,12 +639,12 @@ it.layer(layerTest, { excludeTestServices: true })("WorkspaceEntries", (it) => { for (const entries of [searched.entries, listed.entries]) { const paths = entries.map((entry) => entry.path); expect(paths).toContain("sub/hide-link.ts"); - expect(paths).not.toContain("keep-link.ts"); + expect(paths).toContain("keep-link.ts"); } // The real files are shown or hidden by the same rules. const listedPaths = listed.entries.map((entry) => entry.path); expect(listedPaths).toContain("sub/hide-real.ts"); - expect(listedPaths).not.toContain("keep-real.ts"); + expect(listedPaths).toContain("keep-real.ts"); }), ); it.effect("matches .ignore rules against whole names and treats folder links as links", () => diff --git a/apps/server/src/workspace/WorkspaceSearchIndex.test.ts b/apps/server/src/workspace/WorkspaceSearchIndex.test.ts index 8c42fcf52aab..265a72a98a4a 100644 --- a/apps/server/src/workspace/WorkspaceSearchIndex.test.ts +++ b/apps/server/src/workspace/WorkspaceSearchIndex.test.ts @@ -748,3 +748,27 @@ it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")( }), ).pipe(Effect.provide(testLayer)), ); + +// ripgrep and fff let a matching `.ignore` decide ahead of `.gitignore`, so Git's list must not hide it. +it.live("finds Git-ignored files that a root .ignore re-includes", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const vcsProcess = yield* VcsProcess.VcsProcess; + const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-search-reinclude-" }); + yield* vcsProcess.run({ operation: "test.gitInit", command: "git", args: ["init"], cwd }); + yield* fileSystem.writeFileString(path.join(cwd, ".gitignore"), "notes/\n"); + yield* fileSystem.writeFileString( + path.join(cwd, ".ignore"), + "!notes/\nnotes/**/*\n!notes/**/\n!notes/**/*.md\n", + ); + yield* fileSystem.makeDirectory(path.join(cwd, "notes", "daily"), { recursive: true }); + yield* fileSystem.writeFileString(path.join(cwd, "notes", "daily", "standup.md"), ""); + yield* fileSystem.writeFileString(path.join(cwd, "notes", "daily", "standup.txt"), ""); + + const searchIndex = yield* WorkspaceSearchIndex.make(cwd); + const result = yield* searchIndex.search("standup", 50, "file"); + + expect(result.entries).toEqual([{ kind: "file", path: "notes/daily/standup.md" }]); + }).pipe(Effect.scoped, Effect.provide(testLayer)), +); diff --git a/apps/server/src/workspace/WorkspaceSearchIndex.ts b/apps/server/src/workspace/WorkspaceSearchIndex.ts index b33ceade77fa..e862a5d5325a 100644 --- a/apps/server/src/workspace/WorkspaceSearchIndex.ts +++ b/apps/server/src/workspace/WorkspaceSearchIndex.ts @@ -526,13 +526,12 @@ const listGitIgnoredPaths = Effect.fn("WorkspaceSearchIndex.listGitIgnoredPaths" maxOutputBytes: 16 * 1024 * 1024, }) .pipe(Effect.orElseSucceed(() => undefined)); - if (!result || result.exitCode !== 0 || result.stdoutTruncated) return new Set(); - return new Set( - result.stdout - .split("\0") - .filter((entry) => entry.length > 0) - .map((entry) => trimDirectorySeparator(toPosixPath(entry, hostIsWindows))), - ); + if (!result || result.exitCode !== 0 || result.stdoutTruncated) return []; + // Folders keep their trailing `/`. + return result.stdout + .split("\0") + .filter((entry) => entry.length > 0) + .map((entry) => toPosixPath(entry, hostIsWindows)); }); function mixedItemPath(item: MixedItem): string { @@ -624,7 +623,50 @@ export const make = Effect.fn("WorkspaceSearchIndex.make")(function* ( // so content searches do not wait for it; git grep answers until it is ready. let contentIndexPending = variant === "content"; const vcsProcess = yield* VcsProcess.VcsProcess; - let ignoredPaths = yield* listGitIgnoredPaths(vcsProcess, cwd, hostIsWindows); + + /** The nearest `.ignore` with a pattern matching `relativePath` itself decides. */ + const makeIgnoreFileDecider = () => { + const ignoreFiles = new Map(); + const readIgnoreFile = Effect.fn("WorkspaceSearchIndex.readIgnoreFile")(function* ( + directory: string, + ) { + if (ignoreFiles.has(directory)) return ignoreFiles.get(directory); + const contents = yield* fileSystem + .readFileString(path.join(cwd, directory, ".ignore")) + .pipe(Effect.option); + const file = Option.isSome(contents) ? parseIgnoreFile(contents.value) : undefined; + ignoreFiles.set(directory, file); + return file; + }); + return Effect.fn("WorkspaceSearchIndex.decideByIgnoreFile")(function* ( + relativePath: string, + isFolder: boolean, + ) { + const segments = relativePath.split("/"); + for (let ancestor = segments.length - 1; ancestor >= 0; ancestor -= 1) { + const directory = segments.slice(0, ancestor).join("/"); + const file = yield* readIgnoreFile(directory); + const relative = directory ? relativePath.slice(directory.length + 1) : relativePath; + const decision = file?.decide(relative, isFolder); + if (decision) return decision; + } + return undefined; + }); + }; + + // Like ripgrep and fff, a `.ignore` that re-includes a path overrules Git's ignore rules for it. + const loadIgnoredPaths = Effect.fn("WorkspaceSearchIndex.loadIgnoredPaths")(function* () { + const decide = makeIgnoreFileDecider(); + const ignored = new Set(); + for (const entry of yield* listGitIgnoredPaths(vcsProcess, cwd, hostIsWindows)) { + const relativePath = trimDirectorySeparator(entry); + if ((yield* decide(relativePath, entry.endsWith("/"))) !== "included") { + ignored.add(relativePath); + } + } + return ignored; + }); + let ignoredPaths = yield* loadIgnoredPaths(); if (variant === "paths") { yield* waitForIndexReady( cwd, @@ -713,32 +755,14 @@ export const make = Effect.fn("WorkspaceSearchIndex.make")(function* ( // fff leaves out what `.ignore` files exclude, which git cannot evaluate; the nearest // `.ignore` that matches a path or one of its folders decides, as in decideByIgnoreFiles. const makeIgnoreFileFilter = () => { - const ignoreFiles = new Map(); - const readIgnoreFile = Effect.fn("WorkspaceSearchIndex.readIgnoreFile")(function* ( - directory: string, - ) { - if (ignoreFiles.has(directory)) return ignoreFiles.get(directory); - const contents = yield* fileSystem - .readFileString(path.join(cwd, directory, ".ignore")) - .pipe(Effect.option); - const file = Option.isSome(contents) ? parseIgnoreFile(contents.value) : undefined; - ignoreFiles.set(directory, file); - return file; - }); + const decide = makeIgnoreFileDecider(); return Effect.fn("WorkspaceSearchIndex.isExcludedByIgnoreFiles")(function* ( relativePath: string, ) { const segments = relativePath.split("/"); for (let depth = 1; depth <= segments.length; depth += 1) { const candidate = segments.slice(0, depth).join("/"); - for (let ancestor = depth - 1; ancestor >= 0; ancestor -= 1) { - const directory = segments.slice(0, ancestor).join("/"); - const file = yield* readIgnoreFile(directory); - const relative = directory ? candidate.slice(directory.length + 1) : candidate; - const decision = file?.decide(relative, depth < segments.length); - if (decision === "ignored") return true; - if (decision === "included") break; - } + if ((yield* decide(candidate, depth < segments.length)) === "ignored") return true; } return false; }); @@ -1159,7 +1183,7 @@ export const make = Effect.fn("WorkspaceSearchIndex.make")(function* ( cause, }), ).pipe(Effect.catchTags({ WorkspaceSearchIndexScanTimedOut: () => Effect.void })); - ignoredPaths = yield* listGitIgnoredPaths(vcsProcess, cwd, hostIsWindows); + ignoredPaths = yield* loadIgnoredPaths(); invalidateSymlinkScan(); }); From 4ecbe55087ade20daea476d67b479aab4ce5039a Mon Sep 17 00:00:00 2001 From: Mike Olson Date: Tue, 17 Nov 2026 16:48:17 -0500 Subject: [PATCH 093/133] fix(pi): Reasoning that Pi starts again no longer repeats the abandoned attempt (#38334) Co-authored-by: Julius Marminge --- .../provider-pi/src/server/adapter.test.ts | 54 +++++++++++++++++++ packages/provider-pi/src/server/adapter.ts | 19 ++++++- 2 files changed, 71 insertions(+), 2 deletions(-) diff --git a/packages/provider-pi/src/server/adapter.test.ts b/packages/provider-pi/src/server/adapter.test.ts index a1dd152e662e..601969d5ffe3 100644 --- a/packages/provider-pi/src/server/adapter.test.ts +++ b/packages/provider-pi/src/server/adapter.test.ts @@ -6117,6 +6117,60 @@ describe("PiAdapterV2", () => { }).pipe(Effect.scoped, Effect.provide(layerTest)), ); + // Streamed text is published on a real timer, so this runs on the live clock. + it.live("shows only the new reasoning when Pi starts a streaming block again", () => + Effect.gen(function* () { + const fake = yield* makeFakePi; + const { runtime, takeEvent } = yield* openRuntime(fake); + const providerThread = yield* runtime.ensureThread({ + threadId: THREAD_ID, + modelSelection: modelSelection("default"), + runtimePolicy, + }); + yield* startTurn(runtime, providerThread); + yield* fake.takeRequest("prompt"); + yield* fake.emit({ type: "agent_start" }); + yield* fake.emit({ type: "message_start", message: { role: "assistant" } }); + // A provider that reconnects mid-reasoning streams the same block from its start. + const thinking = (event: Record) => + fake.emit({ + type: "message_update", + assistantMessageEvent: { contentIndex: 0, ...event }, + }); + const reasoningUpdate = Effect.fnUntraced(function* ( + wanted: (item: { readonly status: string; readonly text: string }) => boolean, + ) { + const update = yield* takeEvent( + (event) => + event.type === "turn_item.updated" && + event.turnItem.type === "reasoning" && + wanted(event.turnItem), + ); + return update.type === "turn_item.updated" && update.turnItem.type === "reasoning" + ? { status: update.turnItem.status, text: update.turnItem.text } + : null; + }); + yield* thinking({ type: "thinking_start" }); + yield* thinking({ type: "thinking_delta", delta: "Abandoned attempt" }); + yield* thinking({ type: "thinking_start" }); + yield* thinking({ type: "thinking_delta", delta: "Replacement attempt" }); + assert.deepEqual( + yield* reasoningUpdate((item) => item.text.endsWith("Replacement attempt")), + { + status: "running", + text: "Replacement attempt", + }, + ); + // A third attempt that ends with no reasoning leaves nothing of the second on screen. + yield* thinking({ type: "thinking_start" }); + yield* thinking({ type: "thinking_end" }); + assert.deepEqual(yield* reasoningUpdate((item) => item.status === "completed"), { + status: "completed", + text: "", + }); + }).pipe(Effect.scoped, Effect.provide(layerTest)), + ); + it.effect.each([ { pi: "clears its native queue", diff --git a/packages/provider-pi/src/server/adapter.ts b/packages/provider-pi/src/server/adapter.ts index 1e80b48d7fb9..ab49fe6a4531 100644 --- a/packages/provider-pi/src/server/adapter.ts +++ b/packages/provider-pi/src/server/adapter.ts @@ -327,6 +327,7 @@ interface PiStreamItemState { text: string; completed: boolean; flushScheduled: boolean; + published: boolean; readonly startedAt: DateTime.Utc; } @@ -1196,6 +1197,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( item: PiStreamItemState, streaming: boolean, ) { + item.published = true; const emittedAt = yield* DateTime.now; const base = baseItemFields(turn, item.nativeItemId, item.startedAt, emittedAt); yield* emitItemNode( @@ -1279,12 +1281,15 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( ); }); + const streamItemId = (turn: ActivePiTurn, contentIndex: number) => + `${turn.providerTurn.id}:m${turn.messageOrdinal}:c${contentIndex}`; + const streamItemFor = Effect.fnUntraced(function* ( turn: ActivePiTurn, kind: PiStreamItemState["kind"], contentIndex: number, ) { - const nativeItemId = `${turn.providerTurn.id}:m${turn.messageOrdinal}:c${contentIndex}`; + const nativeItemId = streamItemId(turn, contentIndex); const existing = turn.streamItems.get(nativeItemId); if (existing !== undefined) return existing; const startedAt = yield* DateTime.now; @@ -1294,6 +1299,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( text: "", completed: false, flushScheduled: false, + published: false, startedAt, }; turn.streamItems.set(nativeItemId, item); @@ -1306,7 +1312,10 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( if (item.completed) return Effect.void; item.completed = true; if (text !== undefined && text.length > 0) item.text = text; - return item.text.length === 0 ? Effect.void : emitStreamItem(turn, item, false); + // A block that was shown and then started again empty still replaces what it showed. + return item.text.length === 0 && !item.published + ? Effect.void + : emitStreamItem(turn, item, false); }); const completeOpenStreamItems = (turn: ActivePiTurn) => @@ -2309,6 +2318,12 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( const delta = event["assistantMessageEvent"]; const deltaType = recordString(delta, "type"); const contentIndex = recordNumber(delta, "contentIndex") ?? 0; + if (deltaType === "text_start" || deltaType === "thinking_start") { + // A provider that reconnects mid-block starts it again; its earlier text is abandoned. + const restarted = turn.streamItems.get(streamItemId(turn, contentIndex)); + if (restarted !== undefined && !restarted.completed) restarted.text = ""; + return; + } if (deltaType === "text_delta" || deltaType === "thinking_delta") { const item = yield* streamItemFor( turn, From 2ebe7f8e22617d0eb8deb93ce4f458aba3e9a434 Mon Sep 17 00:00:00 2001 From: Benjamin Nasse <72772737+Bean0-0@users.noreply.github.com> Date: Tue, 17 Nov 2026 15:48:51 -0600 Subject: [PATCH 094/133] fix(pi): fork historical turns from their original session (#38315) Co-authored-by: Julius Marminge --- packages/contracts/src/orchestrationV2.ts | 2 + .../provider-pi/src/server/adapter.test.ts | 109 +++++++++++- packages/provider-pi/src/server/adapter.ts | 165 ++++++++++++++++-- 3 files changed, 252 insertions(+), 24 deletions(-) diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index 39543e9a5f26..a297d92a444d 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -1232,6 +1232,8 @@ export const OrchestrationV2ProviderTurn = Schema.Struct({ nodeId: NodeId, runAttemptId: Schema.NullOr(RunAttemptId), nativeTurnRef: Schema.NullOr(OrchestrationV2ProviderRef), + /** The native session that held this turn, when a provider can move a thread between sessions. */ + nativeThreadRef: Schema.optional(OrchestrationV2ProviderRef), ordinal: PositiveInt, status: Schema.Literals([ "pending", diff --git a/packages/provider-pi/src/server/adapter.test.ts b/packages/provider-pi/src/server/adapter.test.ts index 601969d5ffe3..d4a5f5ff206c 100644 --- a/packages/provider-pi/src/server/adapter.test.ts +++ b/packages/provider-pi/src/server/adapter.test.ts @@ -164,6 +164,7 @@ interface FakePi { readonly queueEntries: (data: unknown) => void; readonly queueMessages: (data: unknown) => void; readonly vetoNextSwitch: () => void; + readonly failNextFork: () => void; readonly queueState: (data: Record) => void; readonly setStreaming: (streaming: boolean) => void; readonly setCompacting: (compacting: boolean) => void; @@ -237,6 +238,7 @@ const makeFakePi: Effect.Effect = Effect.gen(function* () { let failStateAfter: number | null = null; let failThinking = false; let vetoSwitch = false; + let failFork = false; let vetoNewSession = false; let deferredLifecycle: string | undefined; let sessionFile = FAKE_SESSION_FILE; @@ -354,6 +356,10 @@ const makeFakePi: Effect.Effect = Effect.gen(function* () { case "get_session_stats": return { ...base, data: statsQueue.shift() ?? {} }; case "fork": + if (failFork) { + failFork = false; + return { ...base, success: false, error: "Invalid entry ID for forking" }; + } serviceTier = null; return { ...base, data: { text: "Hello pi", cancelled: false } }; case "clear_queue": @@ -498,6 +504,9 @@ const makeFakePi: Effect.Effect = Effect.gen(function* () { vetoNextSwitch: () => { vetoSwitch = true; }, + failNextFork: () => { + failFork = true; + }, queueState: (data) => stateQueue.push(data), setStreaming: (streaming) => { isStreaming = streaming; @@ -2806,6 +2815,16 @@ describe("PiAdapterV2", () => { yield* fake.emit({ type: "agent_start" }); yield* fake.emit({ type: "agent_end", messages: [], willRetry: false }); yield* fake.emit({ type: "agent_settled" }); + const completed = yield* takeEvent( + (event) => + event.type === "provider_turn.updated" && event.providerTurn.status === "completed", + ); + assert.equal( + completed.type === "provider_turn.updated" + ? completed.providerTurn.nativeThreadRef?.nativeId + : undefined, + childFile, + ); const idle = yield* takeEvent( (event) => event.type === "provider_thread.updated" && event.providerThread.status === "idle", @@ -2965,9 +2984,21 @@ describe("PiAdapterV2", () => { ); it.effect.each([ - { historical: false, label: "the latest turn" }, - { historical: true, label: "a historical turn" }, - ])("natively forks $label into an independent session", ({ historical }) => + { historical: false, moved: false, split: false, label: "the latest turn" }, + { historical: true, moved: false, split: false, label: "a historical turn" }, + { + historical: true, + moved: true, + split: false, + label: "a historical turn after a session switch", + }, + { + historical: true, + moved: true, + split: true, + label: "the last turn before a switch to a fresh session", + }, + ])("natively forks $label into an independent session", ({ historical, moved, split }) => Effect.gen(function* () { const fake = yield* makeFakePi; const forkFake = yield* makeFakePi; @@ -2984,12 +3015,22 @@ describe("PiAdapterV2", () => { modelSelection: modelSelection("default"), runtimePolicy, }); + const freshSession = { + driver: PI_PROVIDER, + nativeId: "/fake/new-session.jsonl", + strength: "strong", + } as const; const turn = (ordinal: number): OrchestrationV2ProviderTurn => ({ id: ProviderTurnId.make(`turn-${ordinal}`), providerThreadId: source.id, nodeId: NodeId.make(`node-${ordinal}`), runAttemptId: null, nativeTurnRef: { driver: PI_PROVIDER, nativeId: `u${ordinal}`, strength: "strong" }, + ...(split && ordinal === 2 + ? { nativeThreadRef: freshSession } + : moved && source.nativeThreadRef !== null + ? { nativeThreadRef: source.nativeThreadRef } + : {}), ordinal, status: "completed", startedAt: null, @@ -3005,7 +3046,7 @@ describe("PiAdapterV2", () => { fake.queueState({ sessionFile: forkFile }); const target = ThreadId.make("fork-target"); const forked = yield* runtime.forkThread({ - sourceProviderThread: source, + sourceProviderThread: moved ? { ...source, nativeThreadRef: freshSession } : source, sourceProviderTurns: historical ? [turn(1), turn(2)] : [turn(1)], providerTurnId: turn(1).id, targetThreadId: target, @@ -3025,7 +3066,7 @@ describe("PiAdapterV2", () => { .allRequests() .filter((request) => request.type === "fork") .map((request) => request.entryId), - historical ? ["u2"] : [], + historical && !split ? ["u2"] : [], ); assert.isFalse( fake.allRequests().some((request) => request.type === "fork" || request.type === "clone"), @@ -3061,6 +3102,64 @@ describe("PiAdapterV2", () => { }).pipe(Effect.scoped, Effect.provide(layerTest)), ); + it.effect("recovers a historical Pi fork recorded before turns stored the session file", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const dir = yield* fs.makeTempDirectoryScoped(); + const oldFile = `${dir}/original.jsonl`; + const unrelatedFile = `${dir}/unrelated.jsonl`; + const currentFile = `${dir}/current.jsonl`; + const header = { type: "session", version: 3 }; + const writeSession = (file: string, entries: ReadonlyArray) => + fs.writeFileString( + file, + [header, ...entries].map((entry) => encodeJsonLine(entry)).join("\n") + "\n", + ); + yield* writeSession(oldFile, UNCAPTURED_TURN_TREE.entries); + yield* writeSession(unrelatedFile, [ + sessionMessage("u1", null, "user", 10), + sessionMessage("u2", null, "user", 110), + ]); + yield* writeSession(currentFile, [sessionMessage("new", null, "user", 120)]); + + const fake = yield* makeFakePi; + const forkFake = yield* makeFakePi; + const { runtime } = yield* openRuntime(fake, "default", THREAD_ID, SESSION_ID, forkFake); + const source = yield* runtime.ensureThread({ + threadId: THREAD_ID, + modelSelection: modelSelection("default"), + runtimePolicy, + }); + const forkFile = `${dir}/forked.jsonl`; + forkFake.failNextFork(); + forkFake.queueState({ sessionFile: forkFile }); + fake.queueState({ sessionFile: forkFile }); + const [target, boundary] = uncapturedTurns(source.id, { + startedAt: 100, + completedAt: 145, + }); + if (target === undefined || boundary === undefined) throw new Error("missing fork turns"); + const forked = yield* runtime.forkThread({ + sourceProviderThread: { + ...source, + nativeThreadRef: { driver: PI_PROVIDER, nativeId: currentFile, strength: "strong" }, + }, + sourceProviderTurns: [ + target, + { + ...boundary, + nativeTurnRef: { driver: PI_PROVIDER, nativeId: "u2", strength: "strong" }, + }, + ], + providerTurnId: target.id, + targetThreadId: ThreadId.make("fork-target"), + }); + const args = forkFake.lastSpawn().args; + assert.equal(args[args.indexOf("--fork") + 1], oldFile); + assert.equal(forked.nativeThreadRef?.nativeId, forkFile); + }).pipe(Effect.scoped, Effect.provide(layerTest)), + ); + it.effect("natively forks before a turn whose start entry was never captured", () => Effect.gen(function* () { const fake = yield* makeFakePi; diff --git a/packages/provider-pi/src/server/adapter.ts b/packages/provider-pi/src/server/adapter.ts index ab49fe6a4531..d4dac26c9a4e 100644 --- a/packages/provider-pi/src/server/adapter.ts +++ b/packages/provider-pi/src/server/adapter.ts @@ -521,7 +521,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( Effect.orElseSucceed(() => undefined), ); if (header === undefined) return true; - const sessionCwd = recordString(Option.getOrUndefined(decodeSessionHeader(header)), "cwd"); + const sessionCwd = recordString(Option.getOrUndefined(decodeSessionLine(header)), "cwd"); if (sessionCwd === undefined || sessionCwd === cwd) return true; const realCwd = yield* fileSystem.realPath(cwd).pipe(Effect.orElseSucceed(() => cwd)); return sessionCwd === realCwd; @@ -2076,6 +2076,9 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( ...(treeRefs === null || treeRefs.nativeTurnRef === undefined ? {} : { nativeTurnRef: treeRefs.nativeTurnRef }), + ...(state.providerThread.nativeThreadRef === null + ? {} + : { nativeThreadRef: state.providerThread.nativeThreadRef }), status: interrupted ? "interrupted" : failure !== null ? "failed" : "completed", completedAt, ...(tokenUsage === undefined ? {} : { tokenUsage }), @@ -2951,6 +2954,68 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( ).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner)); }); + // Old records hold entry IDs without a session file. Recover only when both + // timestamped user entries are on the same branch in a sibling session. + const findHistoricalForkSession = Effect.fnUntraced(function* ( + currentFile: string, + boundary: Extract, + ) { + const targetId = piTurnEntryId(boundary.target); + const startedAt = boundary.target?.startedAt; + const completedAt = boundary.target?.completedAt; + const boundaryEnd = boundary.turn.completedAt; + if ( + targetId === undefined || + startedAt == null || + completedAt == null || + boundaryEnd === null + ) { + return undefined; + } + const from = DateTime.toEpochMillis(startedAt); + const between = DateTime.toEpochMillis(completedAt); + const to = DateTime.toEpochMillis(boundaryEnd); + const dir = path.dirname(currentFile); + const siblings = yield* fileSystem + .readDirectoryEntries(dir) + .pipe(Effect.orElseSucceed(() => [])); + const files = siblings + .filter((entry) => entry.type === "File" && entry.name.endsWith(".jsonl")) + .map((entry) => path.join(dir, entry.name)) + .sort() + .reverse(); + for (const file of files) { + if (file === currentFile) continue; + const entries = new Map(); + let leafId: string | null = null; + const readable = yield* fileSystem.stream(file).pipe( + Stream.decodeText(), + Stream.splitLines, + Stream.runForEach((line) => + Effect.sync(() => { + const entry = readPiSessionEntry(Option.getOrUndefined(decodeSessionLine(line))); + if (entry === null) return; + const [id, value] = entry; + entries.set(id, value); + leafId = id; + }), + ), + Effect.as(true), + Effect.orElseSucceed(() => false), + ); + if ( + readable && + piUserEntryInWindow(entries.get(targetId), from, between) && + piUserEntryInWindow(entries.get(boundary.entryId), between, to) && + walkPiBranch(entries, leafId, boundary.entryId)?.reachedStop === true && + walkPiBranch(entries, boundary.entryId, targetId)?.reachedStop === true + ) { + return file; + } + } + return undefined; + }); + const sessionFileInCwd = Effect.fnUntraced(function* ( sessionFile: string, providerThreadCreatedAt: DateTime.Utc, @@ -3369,6 +3434,9 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( nodeId: turnInput.rootNodeId, runAttemptId: turnInput.attemptId, nativeTurnRef: providerRef(syntheticNativeTurnId, "weak"), + ...(state.providerThread.nativeThreadRef === null + ? {} + : { nativeThreadRef: state.providerThread.nativeThreadRef }), ordinal: turnInput.providerTurnOrdinal, status: "running", startedAt, @@ -3927,8 +3995,8 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( return yield* protocolError("Cannot fork while a Pi turn is active"); } const source = forkInput.sourceProviderThread; - const sourceFile = source.nativeThreadRef?.nativeId; - if (sourceFile == null) + const currentFile = source.nativeThreadRef?.nativeId; + if (currentFile == null) return yield* protocolError("Pi fork source has no session file"); const sourceTurns = (forkInput.sourceProviderTurns ?? []).filter( (turn) => turn.providerThreadId === source.id, @@ -3937,14 +4005,39 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( if (forkInput.providerTurnId !== undefined && target === undefined) { return yield* protocolError("Pi fork target turn is missing"); } + const targetFile = target?.nativeThreadRef?.nativeId ?? undefined; const boundary: PiForkBoundary = target === undefined ? { type: "nothing" } : piForkBoundary({ target: { type: "provider_turn", providerTurn: target }, providerThreadTurns: sourceTurns, + sessionFile: targetFile, }); - const nativeId = yield* forkSessionIntoCwd(sourceFile, boundary, source.createdAt); + const boundaryFile = + boundary.type === "nothing" ? undefined : boundary.turn.nativeThreadRef?.nativeId; + const sourceFile = targetFile ?? boundaryFile ?? currentFile; + const nativeId = yield* forkSessionIntoCwd(sourceFile, boundary, source.createdAt).pipe( + Effect.catchTags({ + PiRpcError: (error) => { + if ( + boundary.type !== "entry" || + boundaryFile != null || + error.operation !== "fork" || + error.detail !== "Invalid entry ID for forking" + ) { + return Effect.fail(error); + } + return findHistoricalForkSession(currentFile, boundary).pipe( + Effect.flatMap((file) => + file === undefined + ? Effect.fail(error) + : forkSessionIntoCwd(file, boundary, source.createdAt), + ), + ); + }, + }), + ); const now = yield* DateTime.now; return yield* registerThread( { @@ -3998,7 +4091,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( }); }); -const decodeSessionHeader = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Unknown)); +const decodeSessionLine = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Unknown)); interface PiSessionEntry { readonly parentId: string | null; @@ -4021,15 +4114,24 @@ function piSessionListing(data: unknown): PiSessionListing | null { } function piSessionEntries(entries: unknown): ReadonlyMap | null { - const byId = new Map(); if (!Array.isArray(entries)) return null; - for (const entry of entries) { - const id = recordString(entry, "id"); - const parentId = recordField(entry, "parentId"); - if (id === undefined || byId.has(id) || (parentId !== null && typeof parentId !== "string")) - return null; - const timestamp = recordString(entry, "timestamp"); - byId.set(id, { + const byId = new Map(); + for (const raw of entries) { + const entry = readPiSessionEntry(raw); + if (entry === null || byId.has(entry[0])) return null; + byId.set(...entry); + } + return byId; +} + +function readPiSessionEntry(entry: unknown): [string, PiSessionEntry] | null { + const id = recordString(entry, "id"); + const parentId = recordField(entry, "parentId"); + if (id === undefined || (parentId !== null && typeof parentId !== "string")) return null; + const timestamp = recordString(entry, "timestamp"); + return [ + id, + { parentId, isUserMessage: recordField(entry, "type") === "message" && @@ -4038,9 +4140,22 @@ function piSessionEntries(entries: unknown): ReadonlyMap timestamp === undefined ? null : Option.getOrNull(Option.map(DateTime.make(timestamp), DateTime.toEpochMillis)), - }); - } - return byId; + }, + ]; +} + +function piUserEntryInWindow(entry: PiSessionEntry | undefined, from: number, to: number): boolean { + return ( + entry?.isUserMessage === true && + entry.timestamp !== null && + entry.timestamp >= from && + entry.timestamp <= to + ); +} + +function piTurnEntryId(turn: OrchestrationV2ProviderTurn | null | undefined): string | undefined { + const ref = turn?.nativeTurnRef; + return ref?.strength === "strong" ? (ref.nativeId ?? undefined) : undefined; } function walkPiBranch( @@ -4067,7 +4182,12 @@ function walkPiBranch( } type PiForkBoundary = - | { readonly type: "entry"; readonly entryId: string } + | { + readonly type: "entry"; + readonly entryId: string; + readonly turn: OrchestrationV2ProviderTurn; + readonly target: OrchestrationV2ProviderTurn | null; + } | { readonly type: "nothing" } | { readonly type: "uncaptured"; @@ -4085,15 +4205,22 @@ function piForkBoundary(input: { | { readonly type: "thread_start" } | { readonly type: "provider_turn"; readonly providerTurn: OrchestrationV2ProviderTurn }; readonly providerThreadTurns: ReadonlyArray; + /** Only turns recorded in this session can bound a fork from it. */ + readonly sessionFile?: string | undefined; }): PiForkBoundary { const target = input.target.type === "thread_start" ? null : input.target.providerTurn; const boundary = input.providerThreadTurns - .filter((turn) => turn.ordinal > (target?.ordinal ?? 0) && turn.nativeTurnRef !== null) + .filter( + (turn) => + turn.ordinal > (target?.ordinal ?? 0) && + turn.nativeTurnRef !== null && + (input.sessionFile === undefined || turn.nativeThreadRef?.nativeId === input.sessionFile), + ) .sort((a, b) => a.ordinal - b.ordinal)[0]; const ref = boundary?.nativeTurnRef; if (boundary === undefined || ref == null) return { type: "nothing" }; return ref.strength === "strong" && ref.nativeId !== null - ? { type: "entry", entryId: ref.nativeId } + ? { type: "entry", entryId: ref.nativeId, turn: boundary, target } : { type: "uncaptured", turn: boundary, target }; } From 009966d073aa093832ed39278f524e9870adffd6 Mon Sep 17 00:00:00 2001 From: shivam <91240327+shivamhwp@users.noreply.github.com> Date: Wed, 18 Nov 2026 03:25:06 +0530 Subject: [PATCH 095/133] fix(web): find in thread paints only matches near the viewport (#38329) Co-authored-by: Julius Marminge --- .../threadFindHighlights.browser.test.tsx | 135 ++++++++++- .../components/chat/threadFindHighlights.ts | 229 +++++++++++++++--- .../scenarios/thread-find-paint-bound.e2e.ts | 75 ++++++ 3 files changed, 400 insertions(+), 39 deletions(-) create mode 100644 scripts/scenarios/thread-find-paint-bound.e2e.ts diff --git a/apps/web/src/components/chat/threadFindHighlights.browser.test.tsx b/apps/web/src/components/chat/threadFindHighlights.browser.test.tsx index a04507ef9c2c..d7a3647d9c2c 100644 --- a/apps/web/src/components/chat/threadFindHighlights.browser.test.tsx +++ b/apps/web/src/components/chat/threadFindHighlights.browser.test.tsx @@ -29,19 +29,148 @@ function Highlights(props: Parameters[0]) { return null; } -it("paints every match when one row has more matches than a call can take as arguments", async () => { +function mountTimeline(html: string) { + const container = document.createElement("div"); + container.style.cssText = "height: 200px; width: 300px; overflow: auto"; + container.innerHTML = html; + document.body.append(container); + return { container, [Symbol.dispose]: () => container.remove() }; +} + +const painted = () => [...(CSS.highlights.get("t3-thread-find") ?? [])] as Range[]; +const paintedIn = (element: Element) => + painted().filter((range) => element.contains(range.startContainer)).length; + +it("paints only matches near the viewport plus the active one, in a row with more matches than a call can take as arguments", async () => { const count = 200_000; const onActiveRange = vi.fn<(range: Range | null) => void>(); + using timeline = mountTimeline( + `
${"e x".repeat(count)}
`, + ); await using _screen = await render( , ); - expect(CSS.highlights.get("t3-thread-find")?.size).toBe(count - 1); + const visible = painted(); + expect(visible.length).toBeGreaterThan(0); + expect(visible.length).toBeLessThan(5_000); + expect(Math.max(...visible.map((range) => range.startOffset))).toBeLessThan(count); expect(CSS.highlights.get("t3-thread-find-active")?.size).toBe(1); expect(onActiveRange.mock.lastCall?.[0]?.startOffset).toBe((count - 1) * 3); + + timeline.container.scrollTop = timeline.container.scrollHeight; + await vi.waitFor(() => + expect(Math.max(...painted().map((range) => range.startOffset))).toBe((count - 2) * 3), + ); + expect(painted().length).toBeLessThan(5_000); +}); + +it("paints every match near the viewport when cells lay text out in a different order than the DOM", async () => { + using timeline = mountTimeline( + `
+ + +
${"e x ".repeat(5_000)}${"e x ".repeat(5_000)}
`, + ); + const cells = [...timeline.container.querySelectorAll("td")]; + const ranges = collectThreadFindRanges(timeline.container, "e"); + const key = (range: Range) => + `${cells.indexOf(range.startContainer.parentElement as HTMLTableCellElement)}:${range.startOffset}`; + const missing = () => { + const viewport = timeline.container.getBoundingClientRect(); + const [top, bottom] = [viewport.top - viewport.height, viewport.bottom + viewport.height]; + const shown = new Set(painted().map(key)); + return ranges.filter(({ range }) => { + const rect = range.getBoundingClientRect(); + return rect.bottom >= top && rect.top <= bottom && !shown.has(key(range)); + }).length; + }; + await using _screen = await render( + {}} + />, + ); + expect(missing()).toBe(0); + + timeline.container.scrollTop = 1_000; + await vi.waitFor(() => expect(missing()).toBe(0)); + expect(painted().length).toBeLessThan(ranges.length / 2); +}); + +it("skips a hidden block's matches without measuring each one", async () => { + using timeline = mountTimeline( + `
+
${"e x ".repeat(10_000)}

e

+
`, + ); + const visible = timeline.container.querySelector("p")!; + using measure = vi.spyOn(Range.prototype, "getBoundingClientRect"); + await using _screen = await render( + {}} + />, + ); + expect([painted().length, paintedIn(visible)]).toEqual([1, 1]); + expect(measure.mock.calls.length).toBeLessThan(100); +}); + +it("registers a row's matches only while it is near the viewport, and again after its text changes", async () => { + using timeline = mountTimeline( + `
e e e
+
+
e e
`, + ); + const [near, far] = [...timeline.container.querySelectorAll("[data-thread-find-text]")]; + const onActiveRange = vi.fn<(range: Range | null) => void>(); + await using _screen = await render( + , + ); + expect([paintedIn(near!), paintedIn(far!)]).toEqual([3, 0]); + expect(CSS.highlights.get("t3-thread-find-active")?.size).toBe(1); + expect(far!.contains(onActiveRange.mock.lastCall?.[0]?.startContainer ?? null)).toBe(true); + + near!.append(" e"); + await vi.waitFor(() => expect(paintedIn(near!)).toBe(4)); + + timeline.container.scrollTop = timeline.container.scrollHeight; + await vi.waitFor(() => expect([paintedIn(near!), paintedIn(far!)]).toEqual([0, 1])); +}); + +it("paints a row's matches once the hidden wrapper around it is revealed", async () => { + using timeline = mountTimeline( + ``, + ); + const text = timeline.container.querySelector("[data-thread-find-text]")!; + await using _screen = await render( + {}} + />, + ); + expect(paintedIn(text)).toBe(0); + + timeline.container.querySelector("#wrap")!.removeAttribute("hidden"); + await vi.waitFor(() => expect(paintedIn(text)).toBe(2)); }); diff --git a/apps/web/src/components/chat/threadFindHighlights.ts b/apps/web/src/components/chat/threadFindHighlights.ts index 54ee159e1b28..c8ce0b31b9c9 100644 --- a/apps/web/src/components/chat/threadFindHighlights.ts +++ b/apps/web/src/components/chat/threadFindHighlights.ts @@ -2,6 +2,8 @@ import { findThreadSearchOccurrences } from "@t3tools/shared/threadSearch"; import { useEffect, useEffectEvent, useRef } from "react"; import { THREAD_FIND_BLOCK_TAGS } from "@t3tools/shared/threadFindText"; +import { observeResize } from "~/lib/observeResize"; + const THREAD_FIND_HIGHLIGHT_NAME = "t3-thread-find"; const THREAD_FIND_ACTIVE_HIGHLIGHT_NAME = "t3-thread-find-active"; @@ -160,9 +162,19 @@ export function useThreadFindHighlights(input: { } for (const row of cache.keys()) if (!rows.has(row)) cache.delete(row); rangesRef.current = ranges; - paint(ranges, readSelection()); + paint.update(cache, ranges, readSelection()); }; let frame: number | null = null; + let dirty = false; + const schedule = () => { + if (frame !== null) return; + frame = requestAnimationFrame(() => { + frame = null; + if (dirty) repaint(); + else paint.place(cache); + dirty = false; + }); + }; const observer = new MutationObserver((mutations) => { // Ignore timer and status mutations outside searchable text and folds. const relevant = mutations.filter(affectsSearchableText); @@ -174,12 +186,12 @@ export function useThreadFindHighlights(input: { : mutation.target.parentElement; const row = target?.closest("[data-timeline-row-id]"); if (row) cache.delete(row); + // A hidden wrapper around rows changes their runs, which are cached with their matches. + if (mutation.attributeName === "hidden" && target) + for (const cached of cache.keys()) if (target.contains(cached)) cache.delete(cached); } - if (frame !== null) return; - frame = requestAnimationFrame(() => { - frame = null; - repaint(); - }); + dirty = true; + schedule(); }); observer.observe(container, { subtree: true, @@ -195,10 +207,14 @@ export function useThreadFindHighlights(input: { "data-thread-find-ignore", ], }); + container.addEventListener("scroll", schedule, { passive: true }); + const stopResize = observeResize(container, schedule); // Revealing the first match can synchronously mount or recycle list rows. repaint(); return () => { observer.disconnect(); + stopResize(); + container.removeEventListener("scroll", schedule); if (frame !== null) cancelAnimationFrame(frame); cache.clear(); paintRef.current = null; @@ -211,7 +227,7 @@ export function useThreadFindHighlights(input: { // layout inputs, and repainting the active highlight for those is wasted work. // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- repaints the active CSS Highlight range when the selected match changes useEffect(() => { - paintRef.current?.(rangesRef.current, { + paintRef.current?.select({ activeRowId, activeOccurrence, onActiveRange: readSelection().onActiveRange, @@ -219,47 +235,188 @@ export function useThreadFindHighlights(input: { }, [activeOccurrence, activeRowId]); } +type ThreadFindSelection = Pick< + Parameters[0], + "activeRowId" | "activeOccurrence" | "onActiveRange" +>; + +interface TextRun { + readonly start: number; + end: number; + readonly box: Element; + readonly item: Node | null; + readonly ordered: boolean; + readonly hidden: boolean; +} + +const INLINE_DISPLAYS = new Set(["inline", "contents"]); +const textRunsByMatches = new WeakMap(); + +// Splits a row's matches into runs that each lie in one inline formatting context, +// where a later match is never higher on screen. Cells, flex and grid items, and +// inline blocks each start a run, since their text can sit beside earlier text. +function textRuns(row: Element, matches: readonly ThreadFindRange[]): readonly TextRun[] { + const cached = textRunsByMatches.get(matches); + if (cached) return cached; + const displays = new Map(); + const displayOf = (element: Element) => { + let display = displays.get(element); + if (display === undefined) { + display = getComputedStyle(element).display; + displays.set(element, display); + } + return display; + }; + const columns = new Map(); + const inColumns = (element: Element): boolean => { + let multicol = columns.get(element); + if (multicol === undefined) { + const style = getComputedStyle(element); + multicol = + style.columnCount !== "auto" || + style.columnWidth !== "auto" || + (element !== row && element.parentElement !== null && inColumns(element.parentElement)); + columns.set(element, multicol); + } + return multicol; + }; + const runs: TextRun[] = []; + let text: Node | null = null; + for (const [index, { range }] of matches.entries()) { + const last = runs.at(-1); + if (last && range.startContainer === text) { + last.end = index + 1; + continue; + } + const parent = range.startContainer.parentElement; + if (!parent) continue; + text = range.startContainer; + let box = parent; + while (box !== row && box.parentElement && INLINE_DISPLAYS.has(displayOf(box))) + box = box.parentElement; + // Text directly inside a flex or grid container is an anonymous item of its own. + const item = /flex|grid/.test(displayOf(box)) ? text : null; + const hidden = parent.closest("[hidden]") !== null; + if (last?.end === index && last.box === box && last.item === item && last.hidden === hidden) { + last.end = index + 1; + continue; + } + runs.push({ start: index, end: index + 1, box, item, hidden, ordered: !inColumns(box) }); + } + textRunsByMatches.set(matches, runs); + return runs; +} + +// Blink rebuilds every registered highlight Range on any DOM or style change, so +// only matches within a screen of the viewport are painted; the active one always is. +function matchesInZone( + row: Element, + matches: readonly ThreadFindRange[], + zone: { top: number; bottom: number }, + shown: Set, +): void { + const rowBox = row.getBoundingClientRect(); + if (matches.length === 0 || rowBox.bottom < zone.top || rowBox.top > zone.bottom) return; + const intersects = (rect: DOMRect) => rect.bottom >= zone.top && rect.top <= zone.bottom; + for (const run of textRuns(row, matches)) { + if (run.hidden) continue; + const boxes = run.box.getClientRects(); + if (boxes.length === 0 || ![...boxes].some(intersects)) continue; + if (!run.ordered) { + for (let index = run.start; index < run.end; index++) + if (intersects(matches[index]!.range.getBoundingClientRect())) + shown.add(matches[index]!.range); + continue; + } + const firstShown = (index: number, high: number): [number, DOMRect | null] => { + for (; index < high; index++) { + const rect = matches[index]!.range.getBoundingClientRect(); + if (rect.height > 0) return [index, rect]; + } + return [high, null]; + }; + const firstWhere = (isPast: (rect: DOMRect) => boolean) => { + let low = run.start; + let high = run.end; + while (low < high) { + const mid = (low + high) >>> 1; + const [probe, rect] = firstShown(mid, high); + if (!rect || isPast(rect)) high = mid; + else low = probe + 1; + } + return low; + }; + const end = firstWhere((rect) => rect.top > zone.bottom); + for (let index = firstWhere((rect) => rect.bottom >= zone.top); index < end; index++) + shown.add(matches[index]!.range); + } +} + function makeThreadFindHighlightPainter(container: HTMLElement) { - let previousRanges: readonly ThreadFindRange[] | null = null; - const rangesByRow = new Map(); const inactive = new Highlight(); const active = new Highlight(); - let previousActive: Range | null = null; + const zoned = new Set(); + const windows = new Map>(); + const rangesByRow = new Map(); + let selected: Range | null = null; CSS.highlights.set(THREAD_FIND_HIGHLIGHT_NAME, inactive); CSS.highlights.set(THREAD_FIND_ACTIVE_HIGHLIGHT_NAME, active); - return ( - ranges: readonly ThreadFindRange[], - selection: Pick< - Parameters[0], - "activeRowId" | "activeOccurrence" | "onActiveRange" - >, - ) => { - if (previousRanges !== ranges) { - previousRanges = ranges; - previousActive = null; - rangesByRow.clear(); - inactive.clear(); - for (const match of ranges) { - const row = rangesByRow.get(match.rowId) ?? []; - row[match.occurrence] = match.range; - rangesByRow.set(match.rowId, row); - if (foldsHiding(match.range, container).length === 0) inactive.add(match.range); - } + const show = (range: Range) => { + zoned.add(range); + if (range !== selected && foldsHiding(range, container).length === 0) inactive.add(range); + }; + const hide = (range: Range) => { + zoned.delete(range); + inactive.delete(range); + }; + const place = (rows: ReadonlyMap) => { + const viewport = container.getBoundingClientRect(); + const zone = { top: viewport.top - viewport.height, bottom: viewport.bottom + viewport.height }; + for (const [row, previous] of windows) { + if (rows.has(row)) continue; + for (const range of previous) hide(range); + windows.delete(row); + } + for (const [row, matches] of rows) { + const shown = new Set(); + matchesInZone(row, matches, zone, shown); + const previous = windows.get(row); + if (previous) for (const range of previous) if (!shown.has(range)) hide(range); + for (const range of shown) if (!previous?.has(range)) show(range); + windows.set(row, shown); } - if (previousActive && foldsHiding(previousActive, container).length === 0) - inactive.add(previousActive); - const selected = + }; + const select = (selection: ThreadFindSelection) => { + const next = selection.activeRowId === null ? null : (rangesByRow.get(selection.activeRowId)?.[selection.activeOccurrence] ?? null); + if (selected && selected !== next && zoned.has(selected)) { + if (foldsHiding(selected, container).length === 0) inactive.add(selected); + } + selected = next; active.clear(); - if (selected) inactive.delete(selected); - previousActive = selected; - if (selected && revealFolded(selected, container)) { + if (next) inactive.delete(next); + if (next && revealFolded(next, container)) { selection.onActiveRange(null); } else { - if (selected) active.add(selected); - selection.onActiveRange(selected); + if (next) active.add(next); + selection.onActiveRange(next); + } + }; + const update = ( + rows: ReadonlyMap, + ranges: readonly ThreadFindRange[], + selection: ThreadFindSelection, + ) => { + rangesByRow.clear(); + for (const match of ranges) { + const row = rangesByRow.get(match.rowId) ?? []; + row[match.occurrence] = match.range; + rangesByRow.set(match.rowId, row); } + place(rows); + select(selection); }; + return { update, place, select }; } diff --git a/scripts/scenarios/thread-find-paint-bound.e2e.ts b/scripts/scenarios/thread-find-paint-bound.e2e.ts new file mode 100644 index 000000000000..9c0be796fcdc --- /dev/null +++ b/scripts/scenarios/thread-find-paint-bound.e2e.ts @@ -0,0 +1,75 @@ +import { expect } from "e2e"; + +import { test, WEB } from "./t3.ts"; + +// The thread CLI takes at most 120,000 characters per message: 3,000 lines of ten "the". +const SEEDED_MATCHES = 30_000; +const LONG_MESSAGE = Array.from({ length: SEEDED_MATCHES / 10 }, () => + "the ".repeat(10).trim(), +).join("\n"); + +const findTotal = `(() => { + const label = document.querySelector("[data-thread-find-bar] span[aria-hidden]")?.textContent ?? ""; + const match = /^\\d+\\/(\\d+)$/.exec(label.trim()); + return match ? Number(match[1]) : 0; +})()`; + +const paint = `(() => { + const inactive = CSS.highlights.get("t3-thread-find"); + const active = CSS.highlights.get("t3-thread-find-active"); + let onScreen = 0; + for (const highlight of [inactive, active]) + for (const range of highlight ?? []) { + const rect = range.getBoundingClientRect(); + if (rect.height > 0 && rect.bottom >= 0 && rect.top <= innerHeight) onScreen++; + } + return { + registered: (inactive?.size ?? 0) + (active?.size ?? 0), + active: active?.size ?? 0, + onScreen, + }; +})()`; + +test( + "Find paints only matches near the viewport of a message with 30,000 matches", + WEB, + async ({ t3, app, screen, browser }) => { + const project = await t3.project("find-paint"); + const thread = await t3.thread({ + project, + title: "Paint bound proof", + messages: [LONG_MESSAGE], + }); + await t3.open(thread); + await expect(screen.getByText("first fixture turn complete", { exact: false })).toBeVisible({ + timeout: 120_000, + }); + + // The CLI's message folds to one line; find unfolds it to reach the first match. + await browser.keyboard.press("Control+f"); + const find = screen.getByRole("searchbox", "Find in thread"); + await expect(find).toBeVisible(); + await find.fill("the"); + // The count is the server's: every match in the thread, whatever is painted. + await expect + .poll(() => browser.evaluate(findTotal), { timeout: 60_000 }) + .toBeGreaterThanOrEqual(SEEDED_MATCHES); + await expect + .poll(async () => (await browser.evaluate<{ active: number }>(paint)).active, { + timeout: 30_000, + }) + .toBe(1); + + try { + const painted = await browser.evaluate<{ + registered: number; + active: number; + onScreen: number; + }>(paint); + expect(painted.onScreen).toBeGreaterThan(0); + expect(painted.registered).toBeLessThan(5_000); + } finally { + await app.screenshot("find-open-paint"); + } + }, +); From 73e62fcecc5e07de840e2b03a8efd9c45cbe52cf Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 17 Nov 2026 14:23:35 -0800 Subject: [PATCH 096/133] fix(server): Copilot MCP calls and glob searches keep their identity (#38349) --- .../Adapters/AcpRegistryAdapterV2.test.ts | 103 ++++++++++++++++++ .../src/server/copilotAcp.ts | 53 ++++++++- 2 files changed, 153 insertions(+), 3 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts index ee82cc06de83..495f16646a61 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts @@ -1997,6 +1997,109 @@ describe("AcpRegistryAdapterV2", () => { }).pipe(Effect.provide(layerTest)), ); + // Copilot flattens MCP titles and reports kind "read" for MCP calls and glob; its native + // tool.execution_start event carries the real identity. + it.effect("keeps Copilot's MCP and search tool identity instead of calling them file reads", () => + Effect.gen(function* () { + const sessionId = "copilot-session"; + const executionStart = (data: Record) => ({ + type: "emit_inbound", + frame: { + kind: "notification", + method: "github.com/copilot/sessionEvent", + params: { sessionId, type: "tool.execution_start", data }, + }, + }); + const update = (sessionUpdate: Record) => + claudeFrames.update(sessionId, sessionUpdate); + const session = yield* openClaudeReplaySession( + [ + { + type: "expect_outbound", + frame: { kind: "request", method: "initialize", params: "" }, + }, + { + type: "emit_inbound", + frame: { + kind: "response", + method: "initialize", + result: { + protocolVersion: 1, + agentInfo: { name: "Copilot", version: "1.0.112" }, + agentCapabilities: { loadSession: true }, + authMethods: [], + }, + }, + }, + { + type: "expect_outbound", + frame: { kind: "request", method: "session/new", params: "" }, + }, + { + type: "emit_inbound", + frame: { kind: "response", method: "session/new", result: { sessionId } }, + }, + { + type: "expect_outbound", + frame: { kind: "request", method: "session/prompt", params: "" }, + }, + executionStart({ + toolCallId: "mcp-call", + mcpServerName: "demo-library", + mcpToolName: "search_books", + }), + update({ + sessionUpdate: "tool_call", + toolCallId: "mcp-call", + title: "demo-library-search_books", + kind: "read", + status: "completed", + rawInput: { arguments: { query: "paper airplanes" }, limit: 2 }, + }), + executionStart({ + toolCallId: "native-search", + toolName: "glob", + toolTitle: "Finding files", + arguments: { pattern: "*.ts", paths: ["/workspace"] }, + }), + update({ + sessionUpdate: "tool_call", + toolCallId: "native-search", + title: "Finding files matching *.ts", + kind: "read", + status: "completed", + rawInput: { pattern: "*.ts", paths: ["/workspace"] }, + locations: [{ path: "/workspace" }], + }), + update({ sessionUpdate: "session_info_update", title: "after tools" }), + ], + undefined, + false, + "github-copilot-cli", + ); + yield* session.runtime.startTurn(session.turnInput(1)); + const events = yield* session.throughMarker("after tools"); + const lastItem = (nativeId: string) => + events + .flatMap((event) => + event.type === "turn_item.updated" && + event.turnItem.nativeItemRef?.nativeId === nativeId + ? [event.turnItem] + : [], + ) + .at(-1); + const mcp = lastItem("mcp-call"); + const search = lastItem("native-search"); + assert.deepEqual( + { + mcp: mcp?.type === "dynamic_tool" ? mcp.toolName : mcp?.type, + search: search?.type === "dynamic_tool" ? search.toolName : search?.type, + }, + { mcp: "demo-library.search_books", search: "file_search" }, + ); + }).pipe(Effect.provide(layerTest)), + ); + it.effect.each([ { kind: "approval", stopReason: "end_turn", status: "completed" }, { kind: "question", stopReason: "error", status: "failed" }, diff --git a/packages/provider-acp-registry/src/server/copilotAcp.ts b/packages/provider-acp-registry/src/server/copilotAcp.ts index 848288689298..7b5027147c07 100644 --- a/packages/provider-acp-registry/src/server/copilotAcp.ts +++ b/packages/provider-acp-registry/src/server/copilotAcp.ts @@ -24,6 +24,7 @@ export const copilotClientCapabilitiesMeta = { "session.compaction_complete", "assistant.turn_start", "assistant.idle", + "tool.execution_start", ], }, }; @@ -63,9 +64,26 @@ function record(value: unknown): Record | undefined { const childSessionId = (taskToolCallId: string) => `copilot-task:${taskToolCallId}`; +// Copilot's tool_call reports MCP calls and glob/grep as kind "read" under a flattened title. +type CopilotToolIdentity = + | { readonly kind: "mcp"; readonly server: string; readonly tool: string } + | { readonly kind: "search" }; + +const COPILOT_SEARCH_TOOLS = new Set(["glob", "grep"]); + interface CopilotSessionAttribution { delta: { readonly kind: string; readonly text: string; readonly task?: string } | undefined; readonly taskByAgentId: Map; + readonly toolIdentityByCallId: Map; +} + +function copilotToolIdentity(data: Record): CopilotToolIdentity | undefined { + const server = typeof data.mcpServerName === "string" ? data.mcpServerName.trim() : ""; + const tool = typeof data.mcpToolName === "string" ? data.mcpToolName.trim() : ""; + if (server.length > 0 && tool.length > 0) return { kind: "mcp", server, tool }; + return typeof data.toolName === "string" && COPILOT_SEARCH_TOOLS.has(data.toolName) + ? { kind: "search" } + : undefined; } export function makeCopilotSubagentRouting() { @@ -73,13 +91,17 @@ export function makeCopilotSubagentRouting() { const session = (sessionId: string) => { let current = sessions.get(sessionId); if (current === undefined) { - current = { delta: undefined, taskByAgentId: new Map() }; + current = { delta: undefined, taskByAgentId: new Map(), toolIdentityByCallId: new Map() }; sessions.set(sessionId, current); } return current; }; const release = (sessionId: string, current: CopilotSessionAttribution) => { - if (current.delta === undefined && current.taskByAgentId.size === 0) { + if ( + current.delta === undefined && + current.taskByAgentId.size === 0 && + current.toolIdentityByCallId.size === 0 + ) { sessions.delete(sessionId); } }; @@ -105,6 +127,13 @@ export function makeCopilotSubagentRouting() { } return Effect.void; } + case "tool.execution_start": { + const identity = copilotToolIdentity(data); + if (identity !== undefined && typeof data.toolCallId === "string") { + session(event.sessionId).toolIdentityByCallId.set(data.toolCallId, identity); + } + return Effect.void; + } case "subagent.completed": case "subagent.failed": { const current = sessions.get(event.sessionId); @@ -154,6 +183,7 @@ export function makeCopilotSubagentRouting() { const current = sessions.get(notification.sessionId); if (current === undefined) return notification; let task: string | undefined; + let normalized = notification; if ( update.sessionUpdate === "agent_message_chunk" || update.sessionUpdate === "agent_thought_chunk" @@ -178,8 +208,25 @@ export function makeCopilotSubagentRouting() { ) { const agentId = record(record(update._meta)?.[COPILOT_META_KEY])?.agentId; task = typeof agentId === "string" ? current.taskByAgentId.get(agentId) : undefined; + const identity = current.toolIdentityByCallId.get(update.toolCallId); + if (identity !== undefined) { + if (update.status === "completed" || update.status === "failed") { + current.toolIdentityByCallId.delete(update.toolCallId); + release(notification.sessionId, current); + } + normalized = { + ...notification, + update: + identity.kind === "search" + ? { ...update, kind: "search" } + : { + ...update, + _meta: { ...update._meta, serverId: identity.server, toolName: identity.tool }, + }, + }; + } } - return task === undefined ? notification : { ...notification, sessionId: childSessionId(task) }; + return task === undefined ? normalized : { ...normalized, sessionId: childSessionId(task) }; }; return { registerExtensions, normalizeSessionUpdate }; From 7b4478895daf4f71da216131dbb629ba04271dcf Mon Sep 17 00:00:00 2001 From: Simone Date: Tue, 17 Nov 2026 23:25:09 +0100 Subject: [PATCH 097/133] fix(server): omit page-specific headers and footers from RTF text (#38347) Co-authored-by: Simone <185146821+Lucenx9@users.noreply.github.com> Co-authored-by: Julius Marminge --- apps/server/src/provider/documentTextWorker.ts | 6 ++++++ apps/server/src/provider/userInputAttachments.test.ts | 11 ++++++++++- 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/apps/server/src/provider/documentTextWorker.ts b/apps/server/src/provider/documentTextWorker.ts index ed67cba63f47..57f154204a56 100644 --- a/apps/server/src/provider/documentTextWorker.ts +++ b/apps/server/src/provider/documentTextWorker.ts @@ -454,7 +454,13 @@ function* rtf(source: string): Generator { "object", "fldinst", "header", + "headerf", + "headerl", + "headerr", "footer", + "footerf", + "footerl", + "footerr", ].includes(control) ) state.skip = true; diff --git a/apps/server/src/provider/userInputAttachments.test.ts b/apps/server/src/provider/userInputAttachments.test.ts index 79a9f0539534..f54b748a5701 100644 --- a/apps/server/src/provider/userInputAttachments.test.ts +++ b/apps/server/src/provider/userInputAttachments.test.ts @@ -277,6 +277,15 @@ describe("question answer paths", () => { ); it.effect.each([ + [ + "page-specific headers and footers", + String.raw`{\rtf1\ansi\facingp\sectd\titlepg +{\headerf First-page header}{\headerl Left-page header}{\headerr Right-page header} +{\footerf First-page footer}{\footerl Left-page footer}{\footerr Right-page footer} +\pard Approved delivery date: 24 November.\par +}`, + "Approved delivery date: 24 November.", + ], [ "text symbols", String.raw`{\rtf1\ansi Pages 1\endash 5\emdash\lquote left\rquote\ldblquote right\rdblquote\bullet\b End\b0\unknown{\*\secret\bullet hidden}}`, @@ -310,7 +319,7 @@ describe("question answer paths", () => { ["large fallback", String.raw`{\rtf1\ansi\uc20\u945????????????????????Z}`, "αZ"], ["no fallback", String.raw`{\rtf1\ansi\uc0\u945Z}`, "αZ"], ["scoped count", String.raw`{\rtf1\ansi{\uc2\u945??}\u946?Z}`, "αβZ"], - ] as const)("extracts RTF symbols and Unicode fallbacks: %s", ([name, source, expected]) => + ] as const)("extracts RTF text: %s", ([name, source, expected]) => Effect.gen(function* () { const config = yield* ServerConfig.ServerConfig; const path = NodePath.join(config.attachmentsDir, `${name}.rtf`); From 856c84e4b14653facaa3ee320cd165e4e1b103c1 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 17 Nov 2026 15:37:35 -0800 Subject: [PATCH 098/133] fix(desktop): picked element keeps its screenshot when the page re-renders before Attach (#38357) --- apps/desktop/src/preview/PickPreload.test.ts | 45 +++++++++++++++++++- apps/desktop/src/preview/PickPreload.ts | 19 +++++++-- 2 files changed, 59 insertions(+), 5 deletions(-) diff --git a/apps/desktop/src/preview/PickPreload.test.ts b/apps/desktop/src/preview/PickPreload.test.ts index 61d3941ba41a..abf9421985f2 100644 --- a/apps/desktop/src/preview/PickPreload.test.ts +++ b/apps/desktop/src/preview/PickPreload.test.ts @@ -1,9 +1,10 @@ import { expect, it, vi } from "vite-plus/test"; -import { START_PICK_CHANNEL } from "./GuestProtocol.ts"; +import { ELEMENT_PICKED_CHANNEL, START_PICK_CHANNEL } from "./GuestProtocol.ts"; import "./PickPreload.ts"; const ipcListeners = vi.hoisted(() => new Map void>>()); +const ipcSend = vi.hoisted(() => ({ calls: [] as unknown[][] })); vi.mock("electron", () => ({ ipcRenderer: { @@ -11,7 +12,9 @@ vi.mock("electron", () => ({ ipcListeners.set(channel, [...(ipcListeners.get(channel) ?? []), listener]); }, off: () => {}, - send: () => {}, + send: (...args: unknown[]) => { + ipcSend.calls.push(args); + }, invoke: async () => undefined, }, })); @@ -105,3 +108,41 @@ it("keeps the annotation when Escape dismisses an IME candidate in the comment", expect(shadowRoot.host.isConnected).toBe(true); expect(comment.value).toBe("draft"); }); + +it.each([ + { scrolled: false, rect: { x: 40, y: 60, width: 200, height: 120 } }, + // The last rect would point at whatever now sits there, so no crop beats a wrong one. + { scrolled: true, rect: { x: 0, y: 0, width: 0, height: 0 } }, +])( + "submits a replaced element's last rect unless the page scrolled ($scrolled)", + async ({ scrolled, rect }) => { + ipcSend.calls.length = 0; + const card = document.body.appendChild(document.createElement("div")); + const pickedRect = new DOMRect(40, 60, 200, 120); + // Browsers report a detached element at 0x0 in the corner. + using _rect = vi + .spyOn(card, "getBoundingClientRect") + .mockImplementation(() => (card.isConnected ? pickedRect : new DOMRect())); + document.elementsFromPoint = () => [card]; + const shadowRoot = startAnnotation(); + + card.dispatchEvent( + new PointerEvent("pointerdown", { button: 0, clientX: 100, clientY: 100, bubbles: true }), + ); + // A polling page re-renders while the comment is written and replaces the picked node. + card.replaceWith(document.createElement("div")); + if (scrolled) window.dispatchEvent(new Event("scroll")); + const attach = Array.from(shadowRoot.querySelectorAll("button")).find( + (button) => button.textContent === "Attach", + ); + if (!attach) throw new Error("Attach button not found"); + attach.click(); + + await vi.waitFor(() => + expect(ipcSend.calls.some(([channel]) => channel === ELEMENT_PICKED_CHANNEL)).toBe(true), + ); + const [, annotation] = + ipcSend.calls.find(([channel]) => channel === ELEMENT_PICKED_CHANNEL) ?? []; + expect((annotation as { elements: Array<{ rect: unknown }> }).elements[0]?.rect).toEqual(rect); + }, +); diff --git a/apps/desktop/src/preview/PickPreload.ts b/apps/desktop/src/preview/PickPreload.ts index 42867b9d9cb4..14ae5b16f33d 100644 --- a/apps/desktop/src/preview/PickPreload.ts +++ b/apps/desktop/src/preview/PickPreload.ts @@ -151,6 +151,8 @@ interface SelectedElement { outline: HTMLDivElement; label: HTMLDivElement; baselineStyles: Map; + // Last rect measured while connected; a detached node reports 0x0. + rect: PreviewAnnotationRect; } interface AnnotationSession { @@ -417,6 +419,7 @@ function updateSelectedVisual(target: SelectedElement): void { target.label.style.display = "none"; return; } + target.rect = rectFromDomRect(target.element.getBoundingClientRect()); const rect = visibleElementRect(target.element); positionBox(target.outline, rect); if (rect.width === 0 || rect.height === 0) { @@ -966,6 +969,7 @@ function startAnnotation( outline: createBox(PRIMARY, PRIMARY_FILL), label: createLabel(), baselineStyles: new Map(), + rect: rectFromDomRect(element.getBoundingClientRect()), }; selected.set(element, target); root.append(target.outline, target.label); @@ -1392,6 +1396,13 @@ function startAnnotation( for (const target of selected.values()) updateSelectedVisual(target); queueEditorLayout(); }; + const onScroll = (): void => { + // A detached element's last rect no longer matches what is on screen once the page scrolls. + for (const target of selected.values()) { + if (!target.element.isConnected) target.rect = { x: 0, y: 0, width: 0, height: 0 }; + } + repaint(); + }; // A scrollbar appearing narrows the viewport without a window resize. const rootResizeObserver = new ResizeObserver(repaint); @@ -1626,7 +1637,7 @@ function startAnnotation( window.removeEventListener("focus", onWindowFocus); window.removeEventListener("keydown", onKeyDown, true); window.removeEventListener("keyup", onVoiceKeyUp, true); - window.removeEventListener("scroll", repaint, true); + window.removeEventListener("scroll", onScroll, true); window.removeEventListener("resize", repaint); dragHandle.removeEventListener("pointerdown", onEditorPointerDown); dragHandle.removeEventListener("pointermove", onEditorPointerMove); @@ -1723,7 +1734,9 @@ function startAnnotation( return { id: target.id, element, - rect: rectFromDomRect(target.element.getBoundingClientRect()), + rect: target.element.isConnected + ? rectFromDomRect(target.element.getBoundingClientRect()) + : target.rect, }; }), ) @@ -1785,7 +1798,7 @@ function startAnnotation( window.addEventListener("focus", onWindowFocus); window.addEventListener("keydown", onKeyDown, { capture: true }); window.addEventListener("keyup", onVoiceKeyUp, { capture: true }); - window.addEventListener("scroll", repaint, { capture: true, passive: true }); + window.addEventListener("scroll", onScroll, { capture: true, passive: true }); window.addEventListener("resize", repaint, { passive: true }); // Bubble phase, so the overlay's own handlers still see these events. for (const type of PAGE_ISOLATED_EVENTS) From 24467d671d182bdac5915088bed23a4d34a46dfe Mon Sep 17 00:00:00 2001 From: Martin Bergo Date: Wed, 18 Nov 2026 01:28:02 +0100 Subject: [PATCH 099/133] fix(client): a subagent prompt that opens with comment dividers no longer freezes the thread (#38368) Co-authored-by: Julius Marminge --- .../client-runtime/src/state/subagentRuntime.test.ts | 12 ++++++++++++ packages/client-runtime/src/state/subagentRuntime.ts | 4 +++- 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/packages/client-runtime/src/state/subagentRuntime.test.ts b/packages/client-runtime/src/state/subagentRuntime.test.ts index 7be9639bafed..3512956af25f 100644 --- a/packages/client-runtime/src/state/subagentRuntime.test.ts +++ b/packages/client-runtime/src/state/subagentRuntime.test.ts @@ -316,5 +316,17 @@ describe("resolveWorkflowOpening", () => { false, ); expect(isWorkflowScriptMessage({ role: "assistant", text: SCRIPT })).toBe(false); + expect( + isWorkflowScriptMessage({ role: "user", text: `// a\r// b\u2028/* c\n * d */\r\n${SCRIPT}` }), + ).toBe(true); + expect(isWorkflowScriptMessage({ role: "user", text: "// export const meta = {}" })).toBe( + false, + ); + // Divider comments ahead of ordinary code must reject without catastrophic backtracking. + const dividers = `${"/".repeat(40)}\n`.repeat(40); + expect(isWorkflowScriptMessage({ role: "user", text: `${dividers}const x = 1;` })).toBe(false); + expect( + isWorkflowScriptMessage({ role: "user", text: `${"/**/".repeat(200)}const x = 1;` }), + ).toBe(false); }); }); diff --git a/packages/client-runtime/src/state/subagentRuntime.ts b/packages/client-runtime/src/state/subagentRuntime.ts index a971eef5efc7..ceee780057d5 100644 --- a/packages/client-runtime/src/state/subagentRuntime.ts +++ b/packages/client-runtime/src/state/subagentRuntime.ts @@ -325,7 +325,9 @@ export function deriveWorkflowGroups( } // Workflow scripts open with their `meta` export, after any leading comments. -const WORKFLOW_SCRIPT_START = /^\s*(?:(?:\/\/[^\n]*|\/\*[\s\S]*?\*\/)\s*)*export\s+const\s+meta\b/; +// Each comment has one way to match, so a prompt of `////` divider lines cannot backtrack. +const WORKFLOW_SCRIPT_START = + /^\s*(?:(?:\/\/[^\r\n\u2028\u2029]*(?:[\r\n\u2028\u2029]|$)|\/\*(?:[^*]|\*(?!\/))*\*\/)\s*)*export\s+const\s+meta\b/; /** * Whether a user message is the script a provider-native workflow runs. Servers mark every From ef5772805916a97e9522feaaefcf9e0b5c3b92ff Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 17 Nov 2026 16:28:46 -0800 Subject: [PATCH 100/133] fix(gitlab): GitLab issues open again; issue reactions come from REST (#38383) --- .../src/server/GitLabIssueTracker.test.ts | 14 +++++++++++-- .../src/server/GitLabIssueTracker.ts | 12 ++++++++++- .../src/server/gitLabIssueJson.ts | 6 +++--- .../src/server/gitLabMergeRequestJson.ts | 21 +++++++++++++++++++ 4 files changed, 47 insertions(+), 6 deletions(-) diff --git a/packages/source-control-gitlab/src/server/GitLabIssueTracker.test.ts b/packages/source-control-gitlab/src/server/GitLabIssueTracker.test.ts index 9b6e23b16d0e..18c3c7709f52 100644 --- a/packages/source-control-gitlab/src/server/GitLabIssueTracker.test.ts +++ b/packages/source-control-gitlab/src/server/GitLabIssueTracker.test.ts @@ -92,13 +92,15 @@ function answer(path: string): string { }, ]); } + if (path.startsWith("projects/acme%2Fweb/issues/42/award_emoji")) { + return encode([{ id: 11, name: "eyes", user: { username: "theo" } }]); + } if (path === "graphql") { return encode({ data: { currentUser: { username: "julius" }, project: { mergeRequest: { - awardEmoji: { nodes: [{ name: "eyes", user: { username: "theo" } }] }, notes: { pageInfo: { hasNextPage: false }, nodes: [ @@ -144,7 +146,15 @@ describe("GitLabIssueTracker", () => { const awardCursors: unknown[] = []; const api = yield* tracker((args, input) => { hosts.add(input.host); - if (args[1] === "graphql") awardCursors.push(JSON.parse(input.stdin!).variables.cursor); + if (args[1] === "graphql") { + const request = JSON.parse(input.stdin!); + // gitlab.com's schema has no `Issue.awardEmoji`; glab exits 1 on such a query. + const issueFields = /issue\(iid: \$iid\) \{([\s\S]*?)notes\(/.exec(request.query)?.[1]; + if (issueFields?.includes("awardEmoji")) { + throw new Error("Field 'awardEmoji' doesn't exist on type 'Issue'"); + } + awardCursors.push(request.variables.cursor); + } return answer(args[1]!); }); const target = { cwd: "/w", host: "gitlab.example.com", scope: "acme/web", key: "42" }; diff --git a/packages/source-control-gitlab/src/server/GitLabIssueTracker.ts b/packages/source-control-gitlab/src/server/GitLabIssueTracker.ts index e30dcc18b256..8206b572ece5 100644 --- a/packages/source-control-gitlab/src/server/GitLabIssueTracker.ts +++ b/packages/source-control-gitlab/src/server/GitLabIssueTracker.ts @@ -37,7 +37,9 @@ import { type GitLabTemplateEntry, } from "./gitLabIssueJson.ts"; import { + awardReactions, decodeAwardEmojiJson, + decodeAwardListJson, decodeOwnAwardIdJson, decodeViewerJson, gitLabAwardName, @@ -523,6 +525,13 @@ export const make: Effect.Effect = number, operation: "getIssue", }), + read({ + cwd: input.cwd, + host: input.host, + operation: "getIssue", + path: paged(`${path}/award_emoji`, 1), + decode: decodeAwardListJson, + }), ], { concurrency: 4 }, ), @@ -537,6 +546,7 @@ export const make: Effect.Effect = closing, related, awardPage, + issueAwards, ]) => { const closingKeys = new Set( closing.map((link) => `${link.repository}!${link.number}`), @@ -546,7 +556,7 @@ export const make: Effect.Effect = viewer: viewerLogin, viewerPermissions: VIEWER_PERMISSIONS, states: ISSUE_STATES, - reactions: awardPage.reactions, + reactions: awardReactions(issueAwards, viewerLogin), comments: notes.comments.map((comment) => ({ ...comment, reactions: awardPage.reactionsByNoteId.get(comment.id) ?? [], diff --git a/packages/source-control-gitlab/src/server/gitLabIssueJson.ts b/packages/source-control-gitlab/src/server/gitLabIssueJson.ts index 7f649eeeb9f1..91495e43ed00 100644 --- a/packages/source-control-gitlab/src/server/gitLabIssueJson.ts +++ b/packages/source-control-gitlab/src/server/gitLabIssueJson.ts @@ -409,14 +409,14 @@ export function decodeTemplateJson( } /** - * Awards on the issue and on every note of it, in one read, shaped exactly like the merge request - * query so its decoder answers for both: `mergeRequest` is an alias for the issue field. + * Awards on every note of the issue, shaped like the merge request query so its decoder answers + * for both: `mergeRequest` is an alias for the issue field. GitLab's `Issue` type has no + * `awardEmoji`, so the issue's own awards are read from REST `award_emoji` instead. */ export const ISSUE_AWARD_EMOJI_GRAPHQL_QUERY = `query($fullPath: ID!, $iid: String!, $cursor: String) { currentUser { username } project(fullPath: $fullPath) { mergeRequest: issue(iid: $iid) { - awardEmoji { nodes { name user { username } } } notes(first: ${PAGE_SIZE}, after: $cursor) { pageInfo { hasNextPage endCursor } nodes { id awardEmoji { nodes { name user { username } } } } diff --git a/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.ts b/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.ts index 995ae7493926..00daa58f026d 100644 --- a/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.ts +++ b/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.ts @@ -1304,6 +1304,27 @@ const RawAwardSchema = Schema.Struct({ const decodeAward = Schema.decodeUnknownExit(RawAwardSchema); +type GitLabAward = typeof RawAwardSchema.Type; + +/** A page of REST `award_emoji`; a row that cannot be read is skipped. */ +export function decodeAwardListJson( + raw: string, +): Result.Result, DecodeFailure> { + return Result.map(decodeUnknownList(raw), (rows) => + rows.flatMap((entry) => { + const award = decodeAward(entry); + return Exit.isSuccess(award) ? [award.value] : []; + }), + ); +} + +export function awardReactions( + awards: ReadonlyArray, + viewer: string | null, +): ReadonlyArray { + return toReactions({ nodes: awards }, viewer); +} + export function decodeOwnAwardIdJson( raw: string, input: { readonly content: PullRequestReactionContent; readonly viewer: string }, From 959c4c1ecf0dac0e6a1ebc83336113ecf91a585d Mon Sep 17 00:00:00 2001 From: Simone Date: Wed, 18 Nov 2026 01:31:17 +0100 Subject: [PATCH 101/133] fix(server): count only actual slides in PowerPoint attachment text (#38377) Co-authored-by: Simone <185146821+Lucenx9@users.noreply.github.com> --- .../server/src/provider/documentTextWorker.ts | 8 ++++--- .../src/provider/userInputAttachments.test.ts | 22 ++++++++++++++----- 2 files changed, 21 insertions(+), 9 deletions(-) diff --git a/apps/server/src/provider/documentTextWorker.ts b/apps/server/src/provider/documentTextWorker.ts index 57f154204a56..fd723a7c2585 100644 --- a/apps/server/src/provider/documentTextWorker.ts +++ b/apps/server/src/provider/documentTextWorker.ts @@ -133,8 +133,8 @@ function xml(source: string, extension: string): XmlNode { return root; } -const children = (node: XmlNode) => - node.children.filter((child): child is XmlNode => typeof child !== "string"); +const children = (node: XmlNode | undefined) => + node?.children.filter((child): child is XmlNode => typeof child !== "string") ?? []; function* all(node: XmlNode, name: string | readonly string[]): Generator { for (const child of children(node)) { if (typeof name === "string" ? child.name === name : name.includes(child.name)) yield child; @@ -630,8 +630,10 @@ async function* document(path: string, extension: string): AsyncGenerator node.name === "sldIdLst"); let index = 0; - for (const slide of all(read("ppt/presentation.xml"), "sldId")) { + for (const slide of children(slideList).filter((node) => node.name === "sldId")) { yield `\n\n## Slide ${++index}\n`; const target = rels.get(slide.attrs["r:id"] ?? slide.attrs.id); if (!target) { diff --git a/apps/server/src/provider/userInputAttachments.test.ts b/apps/server/src/provider/userInputAttachments.test.ts index f54b748a5701..b2ea247900b9 100644 --- a/apps/server/src/provider/userInputAttachments.test.ts +++ b/apps/server/src/provider/userInputAttachments.test.ts @@ -685,7 +685,7 @@ describe("question answer paths", () => { ext === "pptx" ? { "ppt/presentation.xml": - '', + '', "ppt/_rels/presentation.xml.rels": '', "ppt/bad.xml": "

Discard", @@ -912,8 +912,16 @@ describe("question answer paths", () => { ext: "pptx", bounded: true, parts: { - "ppt/presentation.xml": - '', + "ppt/presentation.xml": ` + + + + + + + `, "ppt/_rels/presentation.xml.rels": '', "ppt/slides/slide1.xml": "Departure", @@ -934,13 +942,15 @@ describe("question answer paths", () => { "## Slide 2", "Departure\nNotes:\nBoard at gate 4", ], + occurrences: { text: "## Slide ", count: 2 }, absent: ["Unrelated notes", "[Skipped document part", "[Extracted text truncated"], }, ...[false, true].map((missing) => ({ ext: "pptx", bounded: true, parts: { - "ppt/presentation.xml": '', + "ppt/presentation.xml": + '', "ppt/_rels/presentation.xml.rels": '', "ppt/slides/a.xml": "

Slide text

", @@ -958,7 +968,7 @@ describe("question answer paths", () => { bounded: true, parts: { "ppt/presentation.xml": - '', + '', "ppt/_rels/presentation.xml.rels": '', "ppt/slides/a.xml": `

${"A".repeat(600_000)}

`, @@ -1092,7 +1102,7 @@ describe("question answer paths", () => { bounded: true, parts: { "ppt/presentation.xml": - '', + '', "ppt/_rels/presentation.xml.rels": '', "ppt/slides/slide.xml": `${"A".repeat(1_000_100)}`, From 1c818a80830f6b031c5ffd6d96d78b64d958b0dd Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 17 Nov 2026 16:40:43 -0800 Subject: [PATCH 102/133] fix(server): settling a thread closes its waiting link cards (#38380) --- .../src/orchestration-v2/Orchestrator.ts | 6 ++++-- apps/server/src/peer/PeerLinkRequests.test.ts | 18 ++++++++++++++++++ 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 9ca65a32f3cf..819aa90c03b9 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -5446,6 +5446,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio now, cancelQueuedDelivery: false, }); + } + if (command.type === "thread.archive" || command.type === "thread.settle") { yield* closePendingLinkRequests({ command, events, threadId: command.threadId, now }); } @@ -10828,8 +10830,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio /** * Closes the link cards still waiting for the user. Their agent stopped - * waiting long ago, so nobody is woken: stopping or archiving the thread - * means the user is done with it. + * waiting long ago, so nobody is woken: stopping, settling or archiving the + * thread means the user is done with it. */ const closePendingLinkRequests = Effect.fn("orchestrationV2.closePendingLinkRequests")( function* (input: { diff --git a/apps/server/src/peer/PeerLinkRequests.test.ts b/apps/server/src/peer/PeerLinkRequests.test.ts index 2190e9a50e6a..2eec22a90bfa 100644 --- a/apps/server/src/peer/PeerLinkRequests.test.ts +++ b/apps/server/src/peer/PeerLinkRequests.test.ts @@ -888,6 +888,24 @@ it.live("archiving the thread closes its open card", () => ), ); +it.live("settling the thread closes its open card, so it no longer reads as asking", () => + withBoth((a, b) => + Effect.gen(function* () { + yield* seedThread(a); + yield* a.call({ url: b.url }); + yield* pendingCard(a); + yield* endRun(a); + yield* a.orchestrator.dispatch({ + type: "thread.settle", + commandId: CommandId.make("command:settle:laptop"), + threadId, + }); + expect(yield* cardOf(a)).toMatchObject({ status: "cancelled", linkStatus: "cancelled" }); + expect((yield* a.orchestrator.getThreadShell(threadId))?.pendingRuntimeRequest).toBeNull(); + }), + ), +); + it.live("a code the box refuses fails the request with its reason, and links nothing", () => withBoth((a, b) => Effect.gen(function* () { From 25875c11b226b20d4612e719d35c1dd9797c0026 Mon Sep 17 00:00:00 2001 From: Alex Vallone <39172404+amv146@users.noreply.github.com> Date: Tue, 17 Nov 2026 17:06:13 -0800 Subject: [PATCH 103/133] fix(azure-devops): list issues when work item metadata is large (#38387) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Co-authored-by: Julius Marminge --- .../src/server/AzureDevOpsIssueTracker.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/packages/source-control-azure-devops/src/server/AzureDevOpsIssueTracker.ts b/packages/source-control-azure-devops/src/server/AzureDevOpsIssueTracker.ts index 40dfd6df986e..5a6f4c7c38ef 100644 --- a/packages/source-control-azure-devops/src/server/AzureDevOpsIssueTracker.ts +++ b/packages/source-control-azure-devops/src/server/AzureDevOpsIssueTracker.ts @@ -347,7 +347,12 @@ export const make: Effect.Effect< read({ cwd: input.cwd, operation: input.operation, - args: invokeArgs({ ...input, resource: "workitemtypes" }), + // Form layouts can exceed the CLI output cap; only workflow metadata is needed. + args: [ + ...invokeArgs({ ...input, resource: "workitemtypes" }), + "--query", + "{value: value[].{name: name, isDisabled: isDisabled || `false`, states: (states || `[]`)[].{name: name, category: category}}}", + ], decode: decodeAs(decodeTypes), }).pipe(Effect.map((types) => types.value)); From 65accaf23cc51563e385f4d3ad84a97eecd95ca0 Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Tue, 17 Nov 2026 17:18:46 -0800 Subject: [PATCH 104/133] chore: vouch maschwenk (#38394) Co-authored-by: Claude Opus 5.5 --- .github/VOUCHED.td | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/VOUCHED.td b/.github/VOUCHED.td index 315ff5742fd5..2cfd35f32074 100644 --- a/.github/VOUCHED.td +++ b/.github/VOUCHED.td @@ -52,6 +52,7 @@ github:lnieuwenhuis github:Lucenx9 github:mackinleysmith github:maria-rcks +github:maschwenk github:MatthewFeroz github:maxwellyoung github:mweinbach From 42763ff8b12bfb534363df4dd5f8f5f759f54990 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 17 Nov 2026 17:59:16 -0800 Subject: [PATCH 105/133] fix(web): screen readers read a pull request's number once in thread details (#38400) --- .../components/chat/ThreadDetailsPrRow.browser.test.tsx | 7 +++++++ apps/web/src/components/chat/ThreadDetailsPrRow.tsx | 4 +++- 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/apps/web/src/components/chat/ThreadDetailsPrRow.browser.test.tsx b/apps/web/src/components/chat/ThreadDetailsPrRow.browser.test.tsx index 1c3fa1a3899f..0c33baf1a2e4 100644 --- a/apps/web/src/components/chat/ThreadDetailsPrRow.browser.test.tsx +++ b/apps/web/src/components/chat/ThreadDetailsPrRow.browser.test.tsx @@ -361,6 +361,13 @@ it("names a linked pull request row by its kind, number and title, not its URL", expect(name).toMatch(/pull request/i); expect(name).toContain("#1"); expect(name).toContain("Test PR"); + const exposedNumbers = [...screen.container.querySelectorAll("span")].filter( + (span) => + span.textContent?.trim() === "#1" && + span.closest("button") === null && + span.closest('[aria-hidden="true"]') === null, + ); + expect(exposedNumbers).toHaveLength(0); }); it("names a linked issue row by its kind, number and title, not its URL", async () => { diff --git a/apps/web/src/components/chat/ThreadDetailsPrRow.tsx b/apps/web/src/components/chat/ThreadDetailsPrRow.tsx index c06763298015..3fc70104882c 100644 --- a/apps/web/src/components/chat/ThreadDetailsPrRow.tsx +++ b/apps/web/src/components/chat/ThreadDetailsPrRow.tsx @@ -483,7 +483,9 @@ export function ThreadDetailsPrRow({
{openRow(detail.title, "row", true)}
- #{number} + + #{number} + {showChecks && checksRollup !== null ? ( Date: Wed, 18 Nov 2026 03:03:18 +0100 Subject: [PATCH 106/133] fix(server): preserve positional tabs in DOCX attachment text (#38393) Co-authored-by: Simone <185146821+Lucenx9@users.noreply.github.com> Co-authored-by: Julius Marminge --- .../server/src/provider/documentTextWorker.ts | 32 +++++++++++++++---- .../src/provider/userInputAttachments.test.ts | 14 ++++++-- 2 files changed, 36 insertions(+), 10 deletions(-) diff --git a/apps/server/src/provider/documentTextWorker.ts b/apps/server/src/provider/documentTextWorker.ts index fd723a7c2585..237df2a07ab1 100644 --- a/apps/server/src/provider/documentTextWorker.ts +++ b/apps/server/src/provider/documentTextWorker.ts @@ -112,12 +112,7 @@ function xml(source: string, extension: string): XmlNode { parent.children.pop(); return; } - // Markup-compatibility fallbacks repeat their mc:Choice content, e.g. Word text boxes. - // Keep one when no Choice carries text, such as a chart with a VML caption. - if (node.name === "Fallback" && parent.hasTextChoice) { - parent.children.pop(); - return; - } + if (node.name === "Fallback" && !retainCompatibilityFallback(parent, node)) return; if (HIDDEN.has(node.name) || (!node.hasText && node.name !== "noBreakHyphen")) return; parent.hasText = true; if (node.name === "Choice") parent.hasTextChoice = true; @@ -135,6 +130,29 @@ function xml(source: string, extension: string): XmlNode { const children = (node: XmlNode | undefined) => node?.children.filter((child): child is XmlNode => typeof child !== "string") ?? []; + +function retainCompatibilityFallback(parent: XmlNode, fallback: XmlNode): boolean { + // Markup-compatibility fallbacks repeat their mc:Choice content, e.g. Word text boxes. + // Keep one when no Choice carries text, such as a chart with a VML caption. + if (parent.hasTextChoice) { + parent.children.pop(); + return false; + } + if (fallback.hasText || hasInlineTab(fallback, ["tab", "ptab"])) { + parent.children = parent.children.filter( + (child) => + typeof child === "string" || child.name !== "Choice" || !hasInlineTab(child, ["ptab"]), + ); + } + return true; +} + +function hasInlineTab(node: XmlNode, names: readonly string[]): boolean { + return ( + !HIDDEN.has(node.name) && + (names.includes(node.name) || children(node).some((child) => hasInlineTab(child, names))) + ); +} function* all(node: XmlNode, name: string | readonly string[]): Generator { for (const child of children(node)) { if (typeof name === "string" ? child.name === name : name.includes(child.name)) yield child; @@ -143,7 +161,7 @@ function* all(node: XmlNode, name: string | readonly string[]): Generator { if (HIDDEN.has(node.name)) return; - if (["tab", "cell"].includes(node.name)) yield "\t"; + if (["tab", "ptab", "cell"].includes(node.name)) yield "\t"; else if (["br", "line-break", "cr"].includes(node.name)) yield "\n"; else if (node.name === "noBreakHyphen") yield "\u2011"; else if (node.spaceCount !== undefined) { diff --git a/apps/server/src/provider/userInputAttachments.test.ts b/apps/server/src/provider/userInputAttachments.test.ts index b2ea247900b9..e0212783f6f6 100644 --- a/apps/server/src/provider/userInputAttachments.test.ts +++ b/apps/server/src/provider/userInputAttachments.test.ts @@ -749,10 +749,18 @@ describe("question answer paths", () => { ext: "docx", bounded: true, parts: { - "word/document.xml": - 'FirstSecondThirdparty‑End', + "word/document.xml": [ + '', + 'FirstSecondThirdparty‑End', + 'Invoice 104$700.00', + 'Invoice 105$800.00', + 'Invoice 106 total $900.00', + "", + ].join(""), }, - expected: ["First\nSecond\nThird\u2011party\u2011End"], + expected: [ + "First\nSecond\nThird\u2011party\u2011End\nInvoice 104\t$700.00\nInvoice 105\t$800.00\nInvoice 106 total $900.00", + ], }, { ext: "docx", From 724f5c6bec1781c6d7d6ad09033030f198e4607d Mon Sep 17 00:00:00 2001 From: Johannes Mitschunas <51748815+Krarilotus@users.noreply.github.com> Date: Wed, 18 Nov 2026 03:21:45 +0100 Subject: [PATCH 107/133] fix(server): a refused hub read keeps the account's last good usage reading (#38397) Co-authored-by: Julius Marminge --- .../src/usage/UsageLimitSources.test.ts | 101 ++++++++++++++++++ apps/server/src/usage/UsageLimitSources.ts | 38 ++++++- 2 files changed, 138 insertions(+), 1 deletion(-) diff --git a/apps/server/src/usage/UsageLimitSources.test.ts b/apps/server/src/usage/UsageLimitSources.test.ts index fc8a93f9e1bc..4a71640aa262 100644 --- a/apps/server/src/usage/UsageLimitSources.test.ts +++ b/apps/server/src/usage/UsageLimitSources.test.ts @@ -175,6 +175,107 @@ it.effect("reads a management key from its secret provider", () => { ); }); +it.effect("keeps an account's last good reading when the hub's next read of it is refused", () => { + let refused = true; + let workspace = "account-a"; + let listsIdentity = true; + const readAccount = Effect.gen(function* () { + const sources = yield* UsageLimitSources.make; + return Effect.gen(function* () { + yield* sources.refresh; + const [source] = yield* sources.current; + return source?.accounts[0]?.usageLimits; + }); + }); + return Effect.gen(function* () { + const read = yield* readAccount; + // Nothing to keep yet: the account stays listed as unreadable. + expect(yield* read).toMatchObject({ windows: [], unavailable: { reason: "probeFailed" } }); + refused = false; + const good = yield* read; + expect(good?.windows.map((window) => window.usedPercent)).toEqual([78]); + expect(good?.unavailable).toBeUndefined(); + refused = true; + expect(yield* read).toEqual(good); + // The same auth file now holds another login, whose reading is unknown. + workspace = "account-b"; + expect(yield* read).toMatchObject({ windows: [], unavailable: { reason: "probeFailed" } }); + // A file that lists no login cannot show whether the next one is the same. + listsIdentity = false; + refused = false; + yield* read; + refused = true; + expect(yield* read).toMatchObject({ windows: [], unavailable: { reason: "probeFailed" } }); + }).pipe( + Effect.provide([ + ServerSettings.layerTest({ + usageLimitSources: { + [UsageLimitSourceId.make("hub")]: { + kind: "cliproxy", + url: "http://hub.test:8317", + managementKey: "management-secret", + enabled: true, + }, + }, + }), + Layer.mock(BackgroundPolicy.BackgroundPolicy)({ + shouldRunScopeWork: () => Effect.succeed(false), + }), + Layer.succeed(SecretResolver.SecretResolver, { + label: (provider) => Effect.succeed(provider), + read: (references) => Effect.succeed(references.map(() => undefined)), + invalidate: () => Effect.void, + }), + Layer.succeed( + HttpClient.HttpClient, + HttpClient.make((request) => + Effect.sync(() => { + if (new URL(request.url).pathname.endsWith("/auth-files")) { + return HttpClientResponse.fromWeb( + request, + Response.json({ + files: [ + { + id: "first.json", + auth_index: "a", + provider: "codex", + ...(listsIdentity + ? { + email: "first@example.com", + id_token: { chatgpt_account_id: workspace }, + } + : {}), + }, + ], + }), + ); + } + const usage = { + plan_type: "pro", + rate_limit: { + secondary_window: { + used_percent: 78, + reset_at: 4070908800, + limit_window_seconds: 604800, + }, + }, + }; + return HttpClientResponse.fromWeb( + request, + Response.json( + refused + ? { status_code: 429, body: "{}" } + : { status_code: 200, body: JSON.stringify(usage) }, + ), + ); + }), + ), + ), + NodeCrypto.layer, + ]), + ); +}); + const NOW = Date.parse("2026-11-13T12:00:00.000Z"); const at = (hours: number) => DateTime.formatIso(DateTime.makeUnsafe(NOW + hours * 3_600_000)); const spent = (id: string, hours: number): ServerProviderUsageWindow => ({ diff --git a/apps/server/src/usage/UsageLimitSources.ts b/apps/server/src/usage/UsageLimitSources.ts index d6f867d621d2..ff54bb02781a 100644 --- a/apps/server/src/usage/UsageLimitSources.ts +++ b/apps/server/src/usage/UsageLimitSources.ts @@ -52,6 +52,41 @@ function sourceLabel(id: string, config: UsageLimitSourceConfig): string { } } +/** + * A refused read of one account keeps its last good reading, as provider probes keep their bars + * (see ServerProviderUsageLimits); a reading with none to keep stays listed as unreadable. + */ +function keepLastGoodReadings( + previous: ReadonlyArray, + next: ReadonlyArray, +): ReadonlyArray { + return next.map((source) => { + // Auth file names can be reused, so only the same hub and login may lend a reading. + const before = previous.find( + (candidate) => candidate.id === source.id && candidate.endpoint === source.endpoint, + ); + if (!before) return source; + return { + ...source, + accounts: source.accounts.map((account) => { + if (account.usageLimits.unavailable?.reason !== "probeFailed") return account; + // Without a listed login, a reused auth file name cannot be told apart from the old one. + if (account.email === undefined && account.workspaceId === undefined) return account; + const last = before.accounts.find( + (candidate) => + candidate.id === account.id && + candidate.driver === account.driver && + // Fingerprinted Antigravity readings omit the listed identity, so they are never lent. + candidate.usageLimits.credentialFingerprint === undefined && + candidate.email === account.email && + candidate.workspaceId === account.workspaceId, + ); + return last && !last.usageLimits.unavailable ? last : account; + }), + }; + }); +} + function missingManagementKey(config: UsageLimitSourceConfig): string { return typeof config.managementKey === "string" ? "No management key configured." @@ -131,7 +166,7 @@ export const make = Effect.gen(function* () { ([id, config]) => readSource(id as UsageLimitSourceId, config), { concurrency: 4 }, ); - yield* publish(snapshots); + yield* publish(keepLastGoodReadings(yield* Ref.get(stateRef), snapshots)); }).pipe(refreshLock.withPermits(1), Effect.ignoreCause({ log: true })); // Shares the refresh lock so a stale in-flight read cannot overwrite a redemption. @@ -156,6 +191,7 @@ export const make = Effect.gen(function* () { input.accountId, input.creditId, ); + // A redemption changes the reading, so a refused re-read must not bring back the one before it. const snapshot = yield* readSource(input.sourceId, config); const previous = yield* Ref.get(stateRef); yield* publish(previous.map((source) => (source.id === input.sourceId ? snapshot : source))); From 055b44919eeb5d6a59b934fea1cdd34de10c91fe Mon Sep 17 00:00:00 2001 From: maria Date: Tue, 17 Nov 2026 23:25:50 -0300 Subject: [PATCH 108/133] feat(web,mobile,desktop): translate the whole app into every supported language (#37893) --- apps/desktop/gt.config.json | 10 + apps/desktop/package.json | 5 +- apps/desktop/scripts/i18n-generate.mjs | 15 + apps/desktop/src/app/DesktopApp.ts | 6 +- .../desktop/src/app/DesktopStartupRecovery.ts | 62 +- .../desktop/src/backend/DesktopBackendPool.ts | 12 +- apps/desktop/src/backend/DesktopHomeOwner.ts | 49 +- apps/desktop/src/i18n/messages.ts | 83 + apps/desktop/src/i18n/translations/de.json | 103 + apps/desktop/src/i18n/translations/en.json | 103 + apps/desktop/src/i18n/translations/es.json | 103 + apps/desktop/src/i18n/translations/fr.json | 103 + apps/desktop/src/i18n/translations/ja.json | 103 + apps/desktop/src/i18n/translations/ko.json | 103 + apps/desktop/src/i18n/translations/pt-BR.json | 103 + apps/desktop/src/i18n/translations/ru.json | 103 + apps/desktop/src/i18n/translations/sv.json | 103 + apps/desktop/src/i18n/translations/zh.json | 103 + .../desktop/src/ipc/methods/clientSettings.ts | 2 + apps/desktop/src/ipc/methods/snapShot.ts | 4 +- apps/desktop/src/ipc/methods/window.ts | 4 +- apps/desktop/src/permissions/MacPermission.ts | 10 +- .../src/permissions/MacPermissionHelper.ts | 17 +- apps/desktop/src/preview/BrowserSession.ts | 63 +- apps/desktop/src/preview/Manager.ts | 7 +- apps/desktop/src/preview/Passkeys.ts | 8 +- .../src/window/DesktopApplicationMenu.ts | 148 +- apps/desktop/src/window/DesktopWindow.ts | 10 +- apps/mobile/gt.config.json | 8 +- apps/mobile/package.json | 1 + apps/mobile/src/App.tsx | 22 +- apps/mobile/src/Stack.tsx | 205 +- apps/mobile/src/components/BrandMark.tsx | 12 +- .../src/components/CompactBrandTitle.tsx | 7 +- .../components/ComposerAttachmentStrip.tsx | 20 +- .../components/ComposerContextAttachment.tsx | 21 +- .../src/components/ComposerContextSheet.tsx | 173 +- apps/mobile/src/components/ComposerEditor.tsx | 39 +- .../src/components/ComposerModelControl.tsx | 24 +- .../components/EnvironmentMachineSymbol.tsx | 19 +- .../src/components/MediaActionsMenu.tsx | 4 +- .../src/components/MediaVideoPlayer.tsx | 27 +- .../components/NewThreadButton.android.tsx | 4 +- .../src/components/NewThreadButton.shared.tsx | 8 +- .../src/components/PdfPreview.android.tsx | 20 +- apps/mobile/src/components/PdfPreview.tsx | 18 +- apps/mobile/src/components/ProjectFavicon.tsx | 4 +- apps/mobile/src/components/RelativeTime.tsx | 4 +- .../src/components/RenderErrorBoundary.tsx | 16 +- .../ScrollComposeButton.android.tsx | 6 +- .../src/components/VideoAttachmentTile.tsx | 8 +- .../ui/AndroidScreenHeader.android.tsx | 6 +- .../src/components/ui/AppBar.android.tsx | 14 +- apps/mobile/src/components/ui/AppBar.tsx | 46 +- .../src/components/ui/Dialog.android.tsx | 12 +- apps/mobile/src/components/ui/Dialog.tsx | 7 +- .../ui/FilePreviewModal.android.tsx | 25 +- .../src/components/ui/FilePreviewModal.tsx | 15 +- .../src/components/ui/FilePreviewSession.tsx | 27 +- .../src/components/ui/ListToggleRow.tsx | 10 +- apps/mobile/src/components/ui/Notice.tsx | 4 +- .../src/components/ui/NumberField.android.tsx | 11 +- apps/mobile/src/components/ui/NumberField.tsx | 6 +- .../src/components/ui/SecretRevealButton.tsx | 4 +- apps/mobile/src/components/ui/Sheet.tsx | 4 +- .../src/components/ui/SheetHeader.android.tsx | 4 +- apps/mobile/src/components/ui/SheetHeader.tsx | 7 +- apps/mobile/src/components/ui/Toast.tsx | 11 +- .../ui/VideoPreviewModal.android.tsx | 23 +- .../src/components/ui/VideoPreviewModal.tsx | 21 +- .../components/ui/WorkspaceAppBar.android.tsx | 4 +- apps/mobile/src/connection/catalog-store.ts | 15 +- apps/mobile/src/connection/platform.ts | 26 +- .../notificationPermissions.ts | 9 +- .../agent-awareness/remoteRegistration.ts | 17 +- .../archive/ArchivedThreadsScreen.tsx | 45 +- .../browser/BrowserPreviewRouteScreen.tsx | 40 +- .../src/features/browser/BrowserTabMenu.tsx | 63 +- .../features/browser/PreviewStreamWebView.tsx | 95 +- .../features/browser/ThreadBrowserFloat.tsx | 11 +- .../browser/browser-preview-button.tsx | 23 +- .../src/features/browser/browserTabs.ts | 7 +- .../browser/preview-stream-document.ts | 17 +- .../browser/preview-stream.browser.ts | 8 +- .../cloud/ConnectOnboardingRouteScreen.tsx | 10 +- .../features/cloud/T3ConnectProfilePage.tsx | 88 +- .../mobile/src/features/cloud/cloud-drafts.ts | 9 +- .../cloud/cloudEnvironmentPresentation.ts | 34 +- apps/mobile/src/features/cloud/dpop.ts | 27 +- .../src/features/cloud/linkEnvironment.ts | 46 +- .../connection/CloudEnvironmentRows.tsx | 77 +- .../ConnectDeviceApprovalCoordinator.tsx | 22 +- .../connection/ConnectionDiagnosisDetails.tsx | 35 +- .../connection/ConnectionEnvironmentRow.tsx | 85 +- .../features/connection/ConnectionTraceId.tsx | 13 +- .../connection/ConnectionsNewRouteScreen.tsx | 54 +- .../connection/ConnectionsRouteScreen.tsx | 8 +- .../EnvironmentConnectionNotice.tsx | 71 +- .../connection/LinkedEnvironmentsSection.tsx | 17 +- .../connection/LocalEnvironmentList.tsx | 8 +- .../connection/PullRequestRoutingSettings.tsx | 39 +- .../connection/connectDeviceApproval.ts | 21 +- .../src/features/connection/connectionTone.ts | 20 +- .../connection/environmentStatusText.ts | 30 +- .../mobile/src/features/connection/pairing.ts | 5 +- .../connection/permissionUpdateNotice.ts | 12 +- .../connection/useConnectionController.ts | 9 +- .../devices/DevicePreviewRouteScreen.tsx | 61 +- .../features/devices/DeviceStreamWebView.tsx | 55 +- .../devices/device-preview-button.tsx | 20 +- .../devices/device-stream-document.ts | 14 +- .../devices/device-stream.browser.test.ts | 4 + .../features/devices/device-stream.browser.ts | 51 +- .../SettingsDiagnosticsRouteScreen.tsx | 43 +- .../features/diagnostics/crash-log-model.ts | 1 + .../features/diffs/nativeReviewDiffSurface.ts | 8 +- .../features/files/AttachmentDocumentBody.tsx | 20 +- .../features/files/AttachmentFileScreen.tsx | 33 +- .../src/features/files/AudioFilePreview.tsx | 16 +- .../features/files/DelimitedFilePreview.tsx | 4 +- .../features/files/FileMarkdownPreview.tsx | 6 +- .../src/features/files/FileTreeBrowser.tsx | 24 +- .../src/features/files/SourceFileSurface.tsx | 8 +- .../features/files/ThreadFilesRouteScreen.tsx | 123 +- .../files/WorkspaceFileImagePreview.tsx | 15 +- .../files/WorkspaceFilePreviewError.tsx | 15 +- .../files/WorkspaceFileWebPreview.tsx | 13 +- .../src/features/files/ZipArchiveView.tsx | 186 +- .../files/thread-file-navigator-pane.tsx | 26 +- .../src/features/files/useFileTreeEntries.ts | 7 +- apps/mobile/src/features/files/zipTree.ts | 30 +- .../src/features/home/HomeRouteScreen.tsx | 43 +- apps/mobile/src/features/home/HomeScreen.tsx | 51 +- .../src/features/home/ThreadListFilters.tsx | 16 +- .../src/features/home/ThreadUndoNotice.tsx | 12 +- .../home/WorkspaceConnectionTitle.tsx | 7 +- .../src/features/home/home-empty-state.ts | 41 +- .../features/home/home-list-filter-menu.ts | 34 +- .../src/features/home/homeThreadList.ts | 31 +- .../features/home/thread-swipe-actions.tsx | 10 +- .../home/usePendingTaskListActions.ts | 60 +- .../src/features/home/useThreadListActions.ts | 222 +- .../home/workspace-connection-status.ts | 37 +- .../features/issues/IssueAssigneesScreen.tsx | 9 +- .../features/issues/IssueCandidatesSheet.tsx | 35 +- .../features/issues/IssueCommentComposer.tsx | 8 +- .../src/features/issues/IssueEditScreen.tsx | 14 +- .../issues/IssueFilterSearchScreen.tsx | 4 +- .../src/features/issues/IssueLabelsScreen.tsx | 9 +- .../src/features/issues/IssueListRow.tsx | 17 +- .../src/features/issues/IssueRouteScreen.tsx | 138 +- .../src/features/issues/IssuesScreen.tsx | 129 +- .../src/features/issues/issuePresentation.tsx | 18 +- .../src/features/keyboard/CommandPalette.tsx | 68 +- .../HardwareKeyboardCommandProvider.tsx | 24 +- .../layout/AdaptiveWorkspaceLayout.tsx | 8 +- .../features/layout/WorkspaceEmptyDetail.tsx | 30 +- .../createWorkspaceStackNavigator.ios.tsx | 4 +- .../layout/inspector-host.android.tsx | 4 +- .../src/features/layout/inspector-host.tsx | 4 +- .../layout/native-mail-search-toolbar.ts | 6 +- .../src/features/layout/useSidebarToggle.ts | 9 +- .../layout/workspace-inspector-pane.tsx | 4 +- .../layout/workspace-pane-divider.tsx | 8 +- .../workspace/ListSearchToolbar.android.tsx | 12 +- .../layout/workspace/SavedViewsMenu.tsx | 58 +- .../layout/workspace/SharedSlotTitle.tsx | 14 +- .../workspace/WorkspaceListEmptyDetail.tsx | 6 +- .../workspace/WorkspaceListHeader.android.tsx | 4 +- .../layout/workspace/WorkspaceListHeader.tsx | 9 +- .../workspace/WorkspaceNativeTabs.ios.tsx | 7 +- .../layout/workspace/WorkspaceNoTabs.tsx | 8 +- .../workspace/WorkspaceRootScreen.android.tsx | 11 +- .../layout/workspace/WorkspaceRootScreen.tsx | 24 +- .../workspace/WorkspaceSectionToolbar.tsx | 10 +- .../workspace/WorkspaceSidebarColumn.tsx | 13 +- .../layout/workspace/WorkspaceToolbar.tsx | 15 +- .../layout/workspace/brand-header-options.tsx | 8 +- .../layout/workspace/navigation-tab-order.ts | 10 +- .../layout/workspace/navigation-tabs.ts | 8 +- .../layout/workspace/useWorkspaceCompose.ts | 5 +- .../workspace/workspace-list-header-items.ts | 8 +- .../features/projects/AddProjectScreen.tsx | 256 +- .../src/features/projects/suggestAppAccess.ts | 15 +- .../prompt-links/newTaskPromptLink.ts | 63 +- .../prompt-links/prompt-link-actions.ts | 21 +- .../prompt-links/prompt-link-model.ts | 33 +- .../features/prompt-links/threadPromptLink.ts | 9 +- .../PullRequestActivityFilters.tsx | 37 +- .../PullRequestCompletionSuggestions.tsx | 34 +- .../pull-requests/PullRequestControls.tsx | 39 +- .../pull-requests/PullRequestDescription.tsx | 31 +- .../PullRequestDiscussionScreen.tsx | 43 +- .../pull-requests/PullRequestEditScreen.tsx | 55 +- .../pull-requests/PullRequestFiles.tsx | 108 +- .../PullRequestFilterSearchScreen.tsx | 26 +- .../PullRequestInlineCommentScreen.tsx | 25 +- .../pull-requests/PullRequestLabelsScreen.tsx | 48 +- .../pull-requests/PullRequestListFilters.tsx | 173 +- .../pull-requests/PullRequestListRow.tsx | 64 +- .../pull-requests/PullRequestMedia.tsx | 7 +- .../PullRequestMergeControls.tsx | 157 +- .../PullRequestOverviewLoading.tsx | 36 +- .../pull-requests/PullRequestPresentation.tsx | 10 +- .../pull-requests/PullRequestReactions.tsx | 19 +- .../pull-requests/PullRequestReviewSheet.tsx | 78 +- .../PullRequestReviewersScreen.tsx | 118 +- .../pull-requests/PullRequestRouteScreen.tsx | 170 +- .../pull-requests/PullRequestStackCard.tsx | 42 +- .../pull-requests/PullRequestStatusRows.tsx | 109 +- .../pull-requests/PullRequestTimeline.tsx | 87 +- .../pull-requests/PullRequestsScreen.tsx | 35 +- .../SourceControlAppAccessNotice.tsx | 13 +- .../pull-requests/guide/GuideNotice.tsx | 25 +- .../pull-requests/guide/GuideOutline.tsx | 34 +- .../guide/PullRequestGuideScreen.tsx | 65 +- .../guide/ReviewGuideExcerpt.tsx | 16 +- .../pull-requests/guide/reviewGuideState.ts | 63 +- .../pull-requests/guide/useReviewGuide.ts | 9 +- .../pull-requests/pullRequestActions.ts | 111 +- .../pull-requests/pullRequestAgentTasks.ts | 46 +- .../pullRequestDescriptionContent.ts | 7 +- .../pull-requests/pullRequestDiffComments.ts | 31 +- .../pull-requests/pullRequestDiffPages.ts | 65 +- .../features/pull-requests/pullRequestList.ts | 19 +- .../pull-requests/pullRequestStack.ts | 26 +- .../pull-requests/pullRequestStatus.ts | 187 +- .../pull-requests/usePullRequestAction.ts | 28 +- .../usePullRequestAgentActions.ts | 10 +- .../usePullRequestDescription.ts | 10 +- .../pull-requests/usePullRequestDiff.ts | 16 +- .../usePullRequestFilesViewed.ts | 8 +- .../pull-requests/usePullRequestList.ts | 17 +- .../usePullRequestListActions.ts | 57 +- .../usePullRequestMaintainerEdits.ts | 16 +- .../usePullRequestReviewDraft.ts | 6 +- .../pull-requests/usePullRequestThreads.ts | 26 +- .../src/features/review/ReviewCommentCard.tsx | 6 +- .../review/ReviewCommentComposerSheet.tsx | 34 +- .../src/features/review/ReviewSheet.tsx | 67 +- .../review/nativeReviewDiffAdapter.ts | 26 +- .../features/review/reviewCommentSelection.ts | 14 +- .../mobile/src/features/review/reviewModel.ts | 80 +- .../mobile/src/features/review/reviewState.ts | 12 +- .../useReviewCommentSelectionController.ts | 8 +- .../src/features/review/useReviewDiffData.ts | 44 +- .../review/useReviewDiffPrewarming.ts | 10 +- .../useReviewHeaderPresentation.android.ts | 10 +- .../src/features/review/useReviewSections.ts | 20 +- .../src/features/settings/ClaudeAccounts.tsx | 71 +- .../features/settings/CloudVoiceSection.tsx | 143 +- .../settings/EnvironmentRoutesSection.tsx | 74 +- .../settings/OutdatedServerUpdateSection.tsx | 43 +- .../settings/ScheduledTaskPickerScreens.tsx | 35 +- .../settings/SettingsAboutRouteScreen.tsx | 37 +- .../SettingsAppearanceRouteScreen.tsx | 4 +- .../SettingsClientStorageRouteScreen.tsx | 55 +- .../SettingsEnvironmentDetailRouteScreen.tsx | 129 +- .../SettingsEnvironmentsRouteScreen.tsx | 8 +- .../settings/SettingsFollowUpRouteScreen.tsx | 25 +- .../settings/SettingsKeyboardRouteScreen.tsx | 27 +- .../settings/SettingsLanguageRouteScreen.tsx | 18 +- .../settings/SettingsLegalRouteScreen.tsx | 9 +- .../SettingsNavigationRouteScreen.tsx | 35 +- .../SettingsNotificationsRouteScreen.tsx | 134 +- .../SettingsOpenSourceLicensesRouteScreen.tsx | 32 +- .../SettingsProjectGroupingRouteScreen.tsx | 23 +- .../SettingsProjectOverviewRouteScreen.tsx | 135 +- .../SettingsProviderAccountsRouteScreen.tsx | 113 +- .../settings/SettingsRouteScreen.logic.ts | 11 +- .../features/settings/SettingsRouteScreen.tsx | 23 +- .../SettingsScheduledTasksRouteScreen.tsx | 444 +- .../SettingsServerControlsRouteScreen.tsx | 163 +- ...ettingsSourceControlDetailRouteScreens.tsx | 41 +- .../SettingsVoiceModelsRouteScreen.tsx | 22 +- .../settings/SettingsVoiceRouteScreen.tsx | 121 +- .../SettingsWorkspaceLayout.android.tsx | 8 +- .../settings/ThreadSettingsSections.tsx | 82 +- .../features/settings/VoiceModelSection.tsx | 86 +- .../components/AppearancePreviews.tsx | 15 +- .../AndroidNavigationAppearanceSection.tsx | 8 +- .../sections/CodeAppearanceSection.tsx | 12 +- .../sections/TerminalAppearanceSection.tsx | 10 +- .../sections/TextAppearanceSection.tsx | 10 +- .../sections/ThemeAppearanceSection.tsx | 53 +- .../sections/ToolCallsAppearanceSection.tsx | 21 +- .../src/features/settings/claude-accounts.ts | 17 +- .../components/AutoSettleDaysField.tsx | 8 +- .../components/BranchNamingSettings.tsx | 50 +- .../components/DatabaseStorageNotice.tsx | 12 +- .../components/IssueTrackerSection.tsx | 40 +- .../components/ScheduledTaskPromptField.tsx | 13 +- .../components/SettingsDragHandle.tsx | 8 +- .../SettingsEnvironmentFilterHeader.tsx | 23 +- .../SettingsLegalDocumentRouteScreen.tsx | 18 +- .../SettingsProjectOverridesSection.tsx | 8 +- .../components/SettingsProviderRow.tsx | 4 +- .../SourceControlProvidersSection.tsx | 104 +- .../components/SourceControlSignInSection.tsx | 41 +- .../settings/environment-maintenance.ts | 12 +- .../settings/environmentUpdateCheck.ts | 10 +- .../settings/mobileThirdPartyLicenses.ts | 4 +- .../settings/scheduled-task-editor.tsx | 8 +- .../settings/scheduledTaskPresentation.ts | 92 +- .../settings/settings-environment-filter.tsx | 30 +- .../settings/settings-scoped-server.test.ts | 8 +- .../settings/settings-scoped-server.ts | 10 +- .../src/features/settings/settings-search.ts | 254 +- .../features/settings/useSettingsWriter.ts | 9 +- .../sharing/IncomingShareProvider.tsx | 34 +- .../features/sharing/incoming-share-inbox.ts | 15 +- .../features/sharing/incoming-share-model.ts | 71 +- .../src/features/shortcuts/appShortcuts.ts | 8 +- .../features/shortcuts/appShortcutsRuntime.ts | 18 +- .../showcase/showcaseAgentActivity.ts | 5 +- .../showcase/showcaseEnvironmentRows.ts | 2 + .../features/showcase/showcasePendingTasks.ts | 2 + .../showcase/stageShowcaseAgentActivity.ts | 1 + .../terminal/NativeTerminalSurface.tsx | 10 +- .../terminal/TerminalContextSheet.tsx | 20 +- .../terminal/ThreadTerminalRouteScreen.tsx | 146 +- .../src/features/terminal/terminalMenu.ts | 50 +- .../features/threads/ChatGptSharingStatus.tsx | 22 +- .../features/threads/ChildThreadApprovals.tsx | 10 +- .../threads/ComposerAttachmentButton.tsx | 13 +- .../threads/ComposerCommandPopover.tsx | 36 +- .../features/threads/ComposerErrorNotice.tsx | 4 +- .../src/features/threads/ComposerFeedback.tsx | 9 +- .../features/threads/ComposerQueuedEdit.tsx | 11 +- .../features/threads/ComposerUsageLimits.tsx | 8 +- .../src/features/threads/CopyTextButton.tsx | 8 +- .../threads/CustomSnoozeSheet.android.tsx | 29 +- .../features/threads/CustomSnoozeSheet.tsx | 39 +- .../threads/DraftEnvironmentControl.tsx | 12 +- .../features/threads/DraftThreadHeader.tsx | 14 +- .../features/threads/FreshSessionNotice.tsx | 8 +- .../threads/GitActionProgressOverlay.tsx | 13 +- .../features/threads/HtmlRenderWebView.tsx | 10 +- .../src/features/threads/LinkRequestCard.tsx | 146 +- .../threads/LinkedPullRequestList.tsx | 80 +- .../threads/ManagedRuntimeModeNotice.tsx | 11 +- .../threads/McpAppFullscreenScreen.tsx | 19 +- .../src/features/threads/McpAppWebView.tsx | 62 +- .../features/threads/NativeChildWorkSheet.tsx | 23 +- .../threads/NewTaskContextPickerScreens.tsx | 47 +- .../threads/NewTaskDraftRouteScreen.tsx | 14 +- .../features/threads/NewTaskDraftScreen.tsx | 195 +- .../features/threads/NewTaskRouteScreen.tsx | 117 +- .../features/threads/PendingApprovalCard.tsx | 33 +- .../features/threads/PendingUserInputCard.tsx | 47 +- .../features/threads/ProjectCloneBanner.tsx | 26 +- .../src/features/threads/ProposedPlanCard.tsx | 23 +- .../features/threads/ProviderSubagentBar.tsx | 22 +- .../features/threads/QuestionAttachments.tsx | 18 +- .../features/threads/SecretRequestCard.tsx | 28 +- .../src/features/threads/SubagentRow.tsx | 37 +- .../features/threads/SubagentStopButton.tsx | 26 +- .../features/threads/ThreadAgentsSheet.tsx | 26 +- .../threads/ThreadArrangementSheet.tsx | 53 +- .../threads/ThreadBackgroundWorkSheet.tsx | 23 +- .../src/features/threads/ThreadComposer.tsx | 95 +- .../threads/ThreadCreationFailedCard.tsx | 8 +- .../features/threads/ThreadDetailScreen.tsx | 122 +- .../src/features/threads/ThreadFeed.tsx | 237 +- .../features/threads/ThreadGitControls.tsx | 133 +- .../features/threads/ThreadGuestShareBar.tsx | 35 +- .../src/features/threads/ThreadHeader.tsx | 10 +- .../threads/ThreadInlineFilePreview.tsx | 21 +- .../features/threads/ThreadMarkdownImage.tsx | 24 +- .../features/threads/ThreadMarkdownVideo.tsx | 5 +- .../threads/ThreadNavigationSidebar.tsx | 59 +- .../threads/ThreadPullRequestsSheet.tsx | 22 +- .../features/threads/ThreadQueueControl.tsx | 78 +- .../features/threads/ThreadRouteScreen.tsx | 77 +- .../threads/ThreadSettingsRows.shared.tsx | 44 +- .../features/threads/ThreadSettingsSheet.tsx | 106 +- .../features/threads/ThreadSideChatsRow.tsx | 14 +- .../features/threads/ThreadWorkflowGroup.tsx | 64 +- .../threads/UsageLimitRecoveryCard.tsx | 61 +- .../threads/checkout-new-task-branch.ts | 19 +- .../threads/composerSendPresentation.ts | 34 +- .../features/threads/draft-thread-shell.ts | 30 +- .../src/features/threads/fileChipMenu.ts | 18 +- .../threads/floating-working-control.tsx | 23 +- .../threads/floating-working-status.ts | 54 +- .../features/threads/git/GitBranchesSheet.tsx | 43 +- .../features/threads/git/GitCommitSheet.tsx | 45 +- .../features/threads/git/GitConfirmSheet.tsx | 32 +- .../features/threads/git/GitOverviewSheet.tsx | 111 +- .../threads/git/gitSheetComponents.tsx | 49 +- .../features/threads/guestMessageStyle.tsx | 4 +- .../features/threads/incomingShareImport.ts | 13 +- .../threads/new-task-context-presentation.ts | 51 +- .../threads/new-task-flow-provider.tsx | 47 +- .../features/threads/pending-thread-feed.ts | 9 +- .../threads/provider-catalog-refresh.ts | 6 +- .../threads/subagent-card-presentation.ts | 7 +- .../threads/thread-command-output.tsx | 12 +- .../features/threads/thread-handoff-row.tsx | 7 +- .../threads/thread-inspector-preview.tsx | 6 +- .../features/threads/thread-list-v2-items.tsx | 469 +- .../thread-list-v2-row-appearance.android.ts | 7 +- .../threads/thread-list-v2-row-appearance.ts | 7 +- .../features/threads/thread-search-match.tsx | 7 +- .../threads/thread-settings-options.ts | 29 +- .../threads/thread-subagent-group.tsx | 23 +- .../threads/thread-title-regeneration-menu.ts | 18 +- .../src/features/threads/thread-work-log.tsx | 76 +- .../threads/thread-workflow-opening.tsx | 30 +- .../threads/threadAgentsPresentation.ts | 47 +- .../threads/threadContentPresentation.ts | 20 +- .../src/features/threads/threadListV2.ts | 79 +- .../src/features/threads/threadOrder.ts | 24 +- .../threads/threadQueueControlPresentation.ts | 3 +- .../features/threads/turnThreadIntoProject.ts | 9 +- .../threads/use-composer-command-menu.ts | 125 +- .../threads/use-new-task-project-defaults.ts | 16 +- .../threads/use-open-thread-pull-requests.ts | 15 +- .../src/features/threads/useFileChipShare.ts | 13 +- .../threads/useLinkedPullRequestActions.ts | 104 +- .../src/features/threads/useStartSideChat.ts | 22 +- .../src/features/threads/useThreadListV2.ts | 2 + .../threads/useThreadStatusAnnouncements.ts | 3 +- .../threads/userMessageIntentBadge.ts | 21 +- .../features/threads/worktree-setup-card.tsx | 97 +- .../src/features/triage/useStartTriage.ts | 37 +- .../src/features/updates/app-updates.ts | 34 +- .../features/usage/ChatGptUsageSummary.tsx | 21 +- .../src/features/usage/UsageLimitsPooled.tsx | 181 +- .../src/features/usage/UsageLimitsSection.tsx | 107 +- .../src/features/usage/UsageRouteScreen.tsx | 281 +- .../src/features/usage/usageAxisLabels.ts | 42 + .../voice-input/ComposerDictationControl.tsx | 15 +- .../voice-input/GlobalVoiceInputControl.tsx | 37 +- .../voice-input/environmentTranscriber.ts | 7 +- .../features/voice-input/lazyVoiceRecorder.ts | 5 +- .../features/voice-input/voiceDestination.ts | 14 +- .../voice-input/voiceInputPresentation.ts | 14 +- .../features/voice-input/voiceInputSession.ts | 2 + apps/mobile/src/i18n/I18nProvider.tsx | 49 +- apps/mobile/src/i18n/intl-polyfills.ts | 14 +- apps/mobile/src/i18n/messages.ts | 39 + apps/mobile/src/i18n/translations/de.json | 5220 ++++++- apps/mobile/src/i18n/translations/en.json | 5221 ++++++- apps/mobile/src/i18n/translations/es.json | 5214 ++++++- apps/mobile/src/i18n/translations/fr.json | 5220 ++++++- apps/mobile/src/i18n/translations/ja.json | 5196 ++++++- apps/mobile/src/i18n/translations/ko.json | 5200 ++++++- apps/mobile/src/i18n/translations/pt-BR.json | 5214 ++++++- apps/mobile/src/i18n/translations/ru.json | 5296 ++++++- apps/mobile/src/i18n/translations/sv.json | 5210 +++++++ apps/mobile/src/i18n/translations/zh.json | 5209 ++++++- apps/mobile/src/lib/attachmentDocument.ts | 21 +- apps/mobile/src/lib/attachmentDownload.ts | 21 +- apps/mobile/src/lib/attachmentUpload.ts | 25 +- apps/mobile/src/lib/authClientMetadata.ts | 1 + apps/mobile/src/lib/changeRequestTerm.ts | 12 + .../src/lib/composerAttachmentUploadQueue.ts | 22 +- apps/mobile/src/lib/composerContext.ts | 11 +- .../src/lib/composerContextClipboard.ts | 12 +- apps/mobile/src/lib/composerImages.ts | 72 +- apps/mobile/src/lib/localAttachmentPreview.ts | 9 +- apps/mobile/src/lib/markdownDetails.ts | 10 +- apps/mobile/src/lib/mediaActions.test.ts | 4 + apps/mobile/src/lib/modelOptions.ts | 34 +- apps/mobile/src/lib/pdfPreview.ts | 6 +- apps/mobile/src/lib/projectThreadStartTurn.ts | 12 +- apps/mobile/src/lib/threadActivity.ts | 342 +- apps/mobile/src/lib/time.ts | 30 +- .../src/native/EnrichedMarkdownText.tsx | 42 +- .../src/native/HighlightedCodeBlock.tsx | 17 +- apps/mobile/src/native/MermaidCodeBlock.tsx | 30 +- .../src/native/T3ComposerEditor.ios.tsx | 6 +- apps/mobile/src/native/V5StackHeader.ios.tsx | 12 +- .../src/native/useMarkdownImageSource.ts | 16 +- .../src/native/voiceTranscription.android.ts | 36 +- .../src/native/voiceTranscription.ios.ts | 14 +- apps/mobile/src/state/assets.test.ts | 4 + apps/mobile/src/state/assets.ts | 23 +- apps/mobile/src/state/attachments.ts | 4 +- .../src/state/edit-pending-thread-message.ts | 4 +- apps/mobile/src/state/entities.ts | 27 +- apps/mobile/src/state/mediaActions.ts | 28 +- .../src/state/pending-new-tasks-model.ts | 27 +- .../src/state/queries.filesystem.test.ts | 4 + apps/mobile/src/state/queries.ts | 22 +- apps/mobile/src/state/query.ts | 17 +- apps/mobile/src/state/queued-run-edit.ts | 6 +- .../state/remote-environment-projections.ts | 4 + apps/mobile/src/state/remote-runtime-types.ts | 3 + .../src/state/thread-model-selection.ts | 11 +- apps/mobile/src/state/thread-outbox-model.ts | 4 +- .../src/state/thread-pr-presentation.ts | 70 +- .../src/state/thread-task-permissions.test.ts | 9 + apps/mobile/src/state/threadOutboxDelivery.ts | 63 +- apps/mobile/src/state/usage.ts | 31 +- .../state/use-composer-attachment-actions.ts | 32 +- apps/mobile/src/state/use-composer-drafts.ts | 8 +- .../mobile/src/state/use-pending-new-tasks.ts | 15 +- .../state/use-remote-environment-registry.ts | 49 +- .../state/use-selected-thread-git-actions.ts | 39 +- .../state/use-selected-thread-git-state.ts | 5 +- .../src/state/use-selected-thread-requests.ts | 6 +- .../src/state/use-thread-composer-state.ts | 143 +- apps/mobile/src/state/use-thread-pr.ts | 25 +- apps/mobile/src/state/use-vcs-action-state.ts | 25 +- apps/mobile/src/state/workspaceModel.ts | 12 +- apps/mobile/src/widgets/AgentActivity.tsx | 51 +- .../src/widgets/AgentActivityWidget.tsx | 15 +- .../src/widgets/SubscriptionUsage.android.tsx | 29 +- apps/mobile/src/widgets/SubscriptionUsage.tsx | 78 +- .../widgets/SubscriptionUsageCoordinator.tsx | 51 +- .../widgets/agentActivityWidgetTimeline.ts | 72 +- .../widgets/publishAgentActivityWidget.ios.ts | 26 +- .../src/widgets/publishAgentActivityWidget.ts | 8 +- .../src/widgets/subscriptionUsageSnapshot.ts | 148 +- apps/mobile/vite.config.ts | 34 + apps/web/gt.config.json | 8 +- apps/web/src/appInit.tsx | 12 +- apps/web/src/assets/assetUrls.ts | 6 +- apps/web/src/assets/longLivedAssetUrls.ts | 6 +- apps/web/src/branding.logic.ts | 5 +- apps/web/src/browser/BrowserDeviceToolbar.tsx | 38 +- .../browser/BrowserViewportResizeHandles.tsx | 15 +- apps/web/src/browser/ServerBrowserSurface.tsx | 59 +- .../web/src/browser/browserViewportActions.ts | 7 +- apps/web/src/browser/openFileInPreview.ts | 6 +- apps/web/src/browser/useOpenLink.ts | 4 +- apps/web/src/cloud/cloudLinkState.ts | 8 +- apps/web/src/cloud/dpop.ts | 43 +- apps/web/src/cloud/linkEnvironment.ts | 109 +- apps/web/src/cloud/relayFailureReason.ts | 13 +- apps/web/src/cloud/useCloudLinkController.ts | 28 +- .../components/AddProjectToMachineDialog.tsx | 96 +- apps/web/src/components/AppRouteModal.tsx | 8 +- apps/web/src/components/AppSidebarLayout.tsx | 13 +- apps/web/src/components/BranchPicker.tsx | 31 +- .../web/src/components/BranchToolbar.logic.ts | 78 +- apps/web/src/components/BranchToolbar.tsx | 97 +- .../BranchToolbarBranchSelector.tsx | 88 +- .../BranchToolbarEnvModeSelector.tsx | 29 +- .../BranchToolbarEnvironmentSelector.tsx | 22 +- apps/web/src/components/ChatMarkdown.tsx | 103 +- apps/web/src/components/ChatView.logic.ts | 143 +- apps/web/src/components/ChatView.tsx | 245 +- apps/web/src/components/CommandBlock.tsx | 10 +- .../src/components/CommandPalette.logic.ts | 212 +- apps/web/src/components/CommandPalette.tsx | 494 +- .../components/CommandPaletteAddProject.tsx | 24 +- .../src/components/CommandPaletteContent.tsx | 13 +- .../src/components/CommandPaletteLookups.ts | 8 +- .../components/CommandPaletteProjectItems.tsx | 43 +- .../src/components/CommandPaletteResults.tsx | 9 +- .../components/CommandPaletteThemeItems.tsx | 43 +- .../components/CommandPaletteThreadItems.tsx | 166 +- .../components/ComposerContextPermissions.tsx | 15 +- .../components/ComposerPromptEditorTiptap.tsx | 4 +- apps/web/src/components/ConfirmDialogHost.tsx | 28 +- .../ConnectDeviceApprovalCoordinator.tsx | 24 +- .../web/src/components/CustomSnoozeDialog.tsx | 64 +- apps/web/src/components/DevReplayHost.tsx | 24 +- .../src/components/DiffFilePathCopyButton.tsx | 6 +- apps/web/src/components/DiffPanel.tsx | 232 +- .../src/components/DiffWorkerPoolProvider.tsx | 3 +- .../src/components/EnvironmentContextChip.tsx | 7 +- .../src/components/EnvironmentMachineIcon.tsx | 15 +- .../src/components/GitActionsControl.logic.ts | 324 +- apps/web/src/components/GitActionsControl.tsx | 325 +- apps/web/src/components/GitHubStarPrompt.tsx | 20 +- .../components/HostFreezeToastCoordinator.ts | 3 +- apps/web/src/components/HostedEmptyState.tsx | 37 +- apps/web/src/components/InstallT3Commands.tsx | 13 +- .../components/KeybindingsConfigWarning.tsx | 12 +- .../src/components/KeybindingsUpdateToast.tsx | 5 +- .../components/LegacyThreadMigrationToast.ts | 17 +- apps/web/src/components/ManagedPolicy.tsx | 7 +- .../src/components/NoActiveThreadState.tsx | 13 +- apps/web/src/components/NoProjectsHero.tsx | 16 +- .../src/components/PermissionUpdateNotice.ts | 15 +- .../components/PersistentThreadTerminals.tsx | 9 +- .../PreviousWorktreeItemContent.tsx | 5 +- .../ProjectCloneToastCoordinator.tsx | 33 +- .../components/ProjectEnvironmentBadge.tsx | 9 +- apps/web/src/components/ProjectPinButton.tsx | 12 +- .../src/components/ProjectScriptsControl.tsx | 74 +- .../ProviderUpdateLaunchNotification.logic.ts | 165 +- .../src/components/ProviderUpdatesAction.tsx | 10 +- .../components/PullRequestContextDetails.tsx | 25 +- .../PullRequestThreadDialog.test.ts | 10 + .../components/PullRequestThreadDialog.tsx | 90 +- apps/web/src/components/QuitHoldOverlay.tsx | 6 +- apps/web/src/components/RelativeTime.tsx | 2 +- .../components/ReopenClosedViewShortcut.tsx | 8 +- apps/web/src/components/RightPanelSheet.tsx | 5 +- apps/web/src/components/RightPanelTabs.tsx | 247 +- apps/web/src/components/SavedViewsMenu.tsx | 71 +- .../web/src/components/ServerUpdateAction.tsx | 132 +- apps/web/src/components/Sidebar.logic.ts | 51 +- apps/web/src/components/Sidebar.snooze.ts | 11 +- apps/web/src/components/Sidebar.tsx | 243 +- .../src/components/SidebarStageBackdrop.tsx | 2 + .../SlowRpcRequestToastCoordinator.tsx | 18 +- .../SourceControlAppAccessNotice.tsx | 14 +- .../src/components/ThreadCommandSubtitle.tsx | 5 +- apps/web/src/components/ThreadContextChip.tsx | 10 +- .../ThreadNotificationCoordinator.tsx | 16 +- apps/web/src/components/ThreadSearchMatch.tsx | 10 +- .../src/components/ThreadStatusIndicators.tsx | 284 +- .../src/components/ThreadTerminalDrawer.tsx | 142 +- .../components/WorktreeBaseBranchPicker.tsx | 45 +- .../components/auth/ApproveAgentSurface.tsx | 39 +- .../components/auth/ConnectAgentSurface.tsx | 157 +- .../components/auth/PairingRouteSurface.tsx | 110 +- .../backgroundThreadAnnouncement.ts | 19 +- apps/web/src/components/chat/AgentElapsed.tsx | 43 +- .../components/chat/AssistantCitationChip.tsx | 16 +- .../chat/AssistantCitationCommentEditor.tsx | 22 +- .../chat/AssistantCitationSource.tsx | 10 +- .../chat/AssistantSelectionToolbar.tsx | 8 +- .../components/chat/BackgroundWorkDetails.tsx | 34 +- .../src/components/chat/ChangedFilesTree.tsx | 27 +- apps/web/src/components/chat/ChatComposer.tsx | 158 +- .../components/chat/ChatGptSharingControl.tsx | 10 +- apps/web/src/components/chat/ChatHeader.tsx | 39 +- .../src/components/chat/ChatMarkdownMedia.tsx | 30 +- .../src/components/chat/ChatOverlayHosts.tsx | 41 +- .../components/chat/ChildThreadApprovals.tsx | 19 +- .../components/chat/CommandOutputPanel.tsx | 31 +- .../chat/CompactComposerControlsMenu.tsx | 4 +- .../chat/ComposerAttachmentStrip.tsx | 82 +- .../src/components/chat/ComposerBanner.tsx | 6 +- .../components/chat/ComposerBannerStack.tsx | 15 +- .../chat/ComposerCodeBlockLanguagePicker.tsx | 27 +- .../components/chat/ComposerCommandMenu.tsx | 70 +- .../components/chat/ComposerControlsBar.tsx | 7 +- .../src/components/chat/ComposerFeedback.tsx | 31 +- .../chat/ComposerFooterControls.tsx | 28 +- .../components/chat/ComposerFreshSession.tsx | 14 +- .../components/chat/ComposerModelEffort.tsx | 93 +- .../chat/ComposerPendingApprovalActions.tsx | 38 +- .../chat/ComposerPendingUserInputPanel.tsx | 10 +- ...omposerPermissionsSection.browser.test.tsx | 4 +- .../chat/ComposerPrimaryActions.tsx | 112 +- .../components/chat/ComposerSpeechButton.tsx | 40 +- .../components/chat/ComposerStashBadge.tsx | 8 +- .../src/components/chat/ComposerStashMenu.tsx | 70 +- .../components/chat/ComposerUsageLimits.tsx | 85 +- .../web/src/components/chat/DiffStatLabel.tsx | 4 +- .../src/components/chat/DraftHeroHeadline.tsx | 30 +- .../chat/DraftHeroProjectHeading.tsx | 27 +- .../components/chat/ExpandedImageDialog.tsx | 28 +- .../components/chat/ExpandedImagePreview.tsx | 8 +- .../chat/GlobalVoiceInputIndicator.tsx | 4 +- .../chat/GuestMessageAttachments.tsx | 9 +- .../components/chat/GuestShareControls.tsx | 69 +- .../src/components/chat/HtmlRenderDialog.tsx | 12 +- .../src/components/chat/HtmlRenderFrame.tsx | 16 +- .../src/components/chat/LinkRequestCard.tsx | 127 +- .../src/components/chat/MarkdownCodeBlock.tsx | 24 +- .../src/components/chat/MarkdownDetails.tsx | 4 +- .../components/chat/MarkdownFileLink.logic.ts | 14 +- .../src/components/chat/MarkdownFileLink.tsx | 44 +- apps/web/src/components/chat/MarkdownMath.tsx | 10 +- .../chat/MarkdownMermaidCodeBlock.tsx | 4 +- .../web/src/components/chat/MarkdownTable.tsx | 12 +- .../components/chat/MarkdownThreadLink.tsx | 9 +- apps/web/src/components/chat/McpAppFrame.tsx | 33 +- .../src/components/chat/MermaidDiagram.tsx | 16 +- .../src/components/chat/MessageCopyButton.tsx | 5 +- .../components/chat/MessagesTimeline.logic.ts | 204 +- .../src/components/chat/MessagesTimeline.tsx | 66 +- apps/web/src/components/chat/ModelListRow.tsx | 12 +- .../src/components/chat/ModelMentionChip.tsx | 4 +- .../components/chat/ModelPickerContent.tsx | 39 +- .../components/chat/ModelPickerSidebar.tsx | 39 +- .../components/chat/NativeChildWorkDialog.tsx | 35 +- apps/web/src/components/chat/OpenInPicker.tsx | 63 +- .../components/chat/OpenInPickerShortcut.ts | 6 +- .../components/chat/PanelLayoutControls.tsx | 30 +- .../src/components/chat/ProposedPlanCard.tsx | 72 +- .../components/chat/ProviderModelPicker.tsx | 38 +- .../components/chat/ProviderStatusBanner.tsx | 60 +- .../components/chat/ProviderSubagentBar.tsx | 17 +- .../src/components/chat/QueuedRunsControl.tsx | 99 +- .../chat/RightPanelSurfaceContent.tsx | 10 +- .../src/components/chat/SecretRequestCard.tsx | 26 +- apps/web/src/components/chat/SideChatPane.tsx | 39 +- .../src/components/chat/SkillInlineText.tsx | 8 +- .../chat/SnapShotAttachmentDetails.tsx | 30 +- .../chat/SubagentTooltipContent.tsx | 54 +- .../chat/TerminalContextInlineChip.tsx | 21 +- .../chat/ThreadActivityAnnouncer.tsx | 12 +- .../components/chat/ThreadActivityBanners.tsx | 174 +- .../chat/ThreadAutomationsPanel.tsx | 65 +- .../src/components/chat/ThreadDetailsCard.tsx | 4 +- .../chat/ThreadDetailsIssueRows.tsx | 4 +- .../chat/ThreadDetailsItemsMenu.tsx | 10 +- .../components/chat/ThreadDetailsPanel.tsx | 8 +- .../components/chat/ThreadDetailsPrRow.tsx | 139 +- .../components/chat/ThreadDetailsPrRows.tsx | 12 +- .../components/chat/ThreadDetailsUsage.tsx | 62 +- .../src/components/chat/ThreadErrorBanner.tsx | 34 +- .../web/src/components/chat/ThreadFindBar.tsx | 25 +- .../chat/ThreadLineageWorkflowRow.tsx | 50 +- apps/web/src/components/chat/ThreadNow.tsx | 4 +- .../chat/ThreadRelationshipIcon.tsx | 35 +- .../chat/ThreadRelationshipsControl.tsx | 138 +- .../components/chat/ThreadServersPanel.tsx | 42 +- .../components/chat/TimelineAssistantRows.tsx | 29 +- .../src/components/chat/TimelineMinimap.tsx | 11 +- .../src/components/chat/TimelineOverlays.tsx | 5 +- .../chat/TimelinePendingApprovalRow.tsx | 40 +- .../src/components/chat/TimelineRowParts.tsx | 6 +- .../chat/TimelineUserMessageRow.logic.ts | 9 +- .../chat/TimelineUserMessageRow.tsx | 125 +- .../components/chat/TimelineV2EventRow.tsx | 14 +- .../chat/TimelineWorkEntryRow.logic.ts | 14 +- .../components/chat/TimelineWorkEntryRow.tsx | 148 +- .../chat/TimelineWorkGroupRows.logic.ts | 10 +- .../components/chat/TimelineWorkGroupRows.tsx | 81 +- apps/web/src/components/chat/TraitsPicker.tsx | 75 +- apps/web/src/components/chat/TraitsSpeed.tsx | 14 +- .../src/components/chat/TriageDraftHero.tsx | 36 +- .../chat/UsageLimitRecoveryBanner.tsx | 60 +- .../chat/UserMessageContextChips.tsx | 75 +- .../src/components/chat/V2ItemInspector.tsx | 32 +- .../src/components/chat/V2LifecycleRow.tsx | 97 +- .../components/chat/VoiceInputErrorPill.tsx | 69 +- .../src/components/chat/VoiceInputSetup.tsx | 83 +- .../components/chat/WorkflowOpeningBlock.tsx | 19 +- .../components/chat/WorkspaceEntryIcon.tsx | 4 +- .../src/components/chat/WorktreeSetupCard.tsx | 68 +- .../web/src/components/chat/ZoomableImage.tsx | 10 +- apps/web/src/components/chat/chatViewSend.ts | 42 +- .../src/components/chat/citationProcedure.ts | 25 +- .../src/components/chat/compaction.logic.ts | 17 +- .../chat/composerAttachmentFiles.ts | 11 +- .../src/components/chat/composerSend.logic.ts | 58 +- .../src/components/chat/composerSubmission.ts | 24 +- apps/web/src/components/chat/copySnapshot.ts | 5 +- .../chat/externalLinkContextMenu.ts | 21 +- .../src/components/chat/guestMessageStyle.tsx | 8 +- .../components/chat/guestShareAvailability.ts | 3 +- .../src/components/chat/queuedMessageEdit.ts | 4 +- .../src/components/chat/runtimeModeConfig.ts | 67 +- .../src/components/chat/threadDetailsItems.ts | 37 +- .../components/chat/turnDetailAnnouncement.ts | 30 +- .../chat/useApplyThreadModelPick.ts | 11 +- .../chat/useAutoBalanceUpdateBanner.tsx | 48 +- .../components/chat/useChatTerminalActions.ts | 21 +- .../chat/useComposerAttachmentIntake.ts | 63 +- .../chat/useComposerContextImport.ts | 20 +- .../components/chat/useComposerMenuItems.ts | 76 +- .../src/components/chat/useComposerResume.ts | 5 +- .../components/chat/useComposerSelection.ts | 3 + .../src/components/chat/useComposerSend.ts | 197 +- .../src/components/chat/useComposerStash.ts | 117 +- .../chat/useDraftEnvironmentRouting.ts | 27 +- .../src/components/chat/useForceStopThread.ts | 18 +- .../components/chat/useMultipleModelSend.ts | 42 +- .../chat/usePendingThreadRequests.ts | 19 +- .../components/chat/useProjectCloneBanner.tsx | 42 +- .../chat/useProjectScriptEditing.ts | 30 +- .../chat/usePullRequestDraftThread.ts | 4 +- .../src/components/chat/useQueuedRunEdit.ts | 32 +- .../components/chat/useRightPanelActions.ts | 15 +- apps/web/src/components/chat/useSideChat.ts | 18 +- .../chat/useSystemComposerBanners.tsx | 60 +- .../components/chat/useThreadLifecycle.tsx | 124 +- .../src/components/chat/useTimelineRewind.ts | 28 +- .../src/components/chat/useTimelineRows.ts | 15 +- .../components/chat/useUsageLimitsPanel.ts | 16 +- .../components/clerk/ClerkUserProfilePage.tsx | 3 +- .../MobileClientsUserProfilePage.logic.ts | 34 +- .../clerk/MobileClientsUserProfilePage.tsx | 41 +- .../RemoveT3ConnectEnvironmentDialog.tsx | 34 +- .../clerk/T3ChatUserProfilePage.tsx | 67 +- .../clerk/T3ConnectAccountPages.tsx | 6 +- .../clerk/T3ConnectSidebarSignIn.tsx | 12 +- .../clerk/T3ConnectUserProfilePage.tsx | 86 +- .../web/src/components/clerk/useT3ChatLink.ts | 12 +- .../cloud/CloudEnvironmentConnectList.tsx | 101 +- .../cloud/ConnectCliAuthSurface.tsx | 28 +- .../cloud/ConnectOnboardingDialog.tsx | 56 +- .../cloud/RelayClientInstallDialog.tsx | 50 +- apps/web/src/components/cloud/TunnelUsage.tsx | 46 +- .../cloudEnvironmentConnectionPresentation.ts | 35 +- .../composerContextPresentation.tsx | 187 +- apps/web/src/components/contextChipParts.tsx | 17 +- .../desktop/DesktopWebLinkCoordinator.tsx | 21 +- .../desktop/SnapShotCoordinator.tsx | 33 +- .../desktop/SshPasswordPromptDialog.tsx | 40 +- .../web/src/components/desktopUpdate.logic.ts | 98 +- .../src/components/desktopUpdate.toast.tsx | 10 +- .../device/DeviceAndroidFoldControls.tsx | 24 +- .../components/device/DeviceControlsRail.tsx | 69 +- .../components/device/DeviceDuoControls.tsx | 23 +- .../components/device/DeviceDuoViewport.tsx | 6 +- .../device/DeviceHostAvailability.tsx | 15 +- .../components/device/DeviceHostUpdates.tsx | 16 +- .../components/device/DeviceLoadingView.tsx | 6 +- .../web/src/components/device/DevicePanel.tsx | 86 +- .../components/device/DevicePhoneViewport.tsx | 6 +- .../web/src/components/device/DeviceSetup.tsx | 154 +- .../components/device/DeviceStreamView.tsx | 32 +- .../components/device/DeviceToolVersions.tsx | 52 +- .../components/device/DeviceToolsPanel.tsx | 213 +- .../src/components/device/DeviceWorkspace.tsx | 6 +- apps/web/src/components/device/deviceFold.ts | 12 +- .../components/device/deviceStreamSession.ts | 2 + .../diffs/DiffCommentAnnotation.tsx | 24 +- .../diffs/DiffFileLoadingBoundary.tsx | 4 +- .../src/components/diffs/DiffFileStatus.tsx | 8 +- .../web/src/components/diffs/DiffFileTree.tsx | 10 +- .../AttachmentFilePreview.browser.test.tsx | 10 +- ...achmentFilePreview.office.browser.test.tsx | 27 +- .../files/AttachmentFilePreview.tsx | 103 +- .../web/src/components/files/AudioPreview.tsx | 26 +- .../web/src/components/files/BinaryViewer.tsx | 104 +- .../src/components/files/DocumentPages.tsx | 8 +- .../src/components/files/FileBreadcrumbs.tsx | 36 +- .../src/components/files/FileBrowserPanel.tsx | 53 +- .../src/components/files/FileExplorerPane.tsx | 8 +- .../components/files/FilePreviewPanel.test.ts | 20 +- .../src/components/files/FilePreviewPanel.tsx | 123 +- apps/web/src/components/files/FontViewer.tsx | 37 +- .../src/components/files/LargeTextViewer.tsx | 50 +- .../src/components/files/MermaidViewer.tsx | 10 +- .../src/components/files/NotebookPreview.tsx | 31 +- .../web/src/components/files/OfficeViewer.tsx | 135 +- .../components/files/OpenXmlOfficeViewer.tsx | 41 +- apps/web/src/components/files/PdfViewer.tsx | 56 +- .../components/files/PreviewImageContent.tsx | 16 +- .../components/files/ProjectFilePicker.tsx | 42 +- .../files/binaryPreview.worker.test.ts | 6 +- .../components/files/binaryPreview.worker.ts | 43 +- .../components/files/binaryPreviewProtocol.ts | 3 +- .../components/files/decodeImagePreview.ts | 24 +- .../files/extendedDocumentPreview.ts | 81 +- .../files/fileCommentAnnotations.ts | 12 +- .../src/components/files/filePreviewMode.ts | 22 +- .../components/files/fileSurfaceChrome.tsx | 6 +- .../components/files/imageDecode.worker.ts | 67 +- .../src/components/files/largeText.worker.ts | 25 +- .../src/components/files/largeTextProtocol.ts | 3 +- .../components/files/office/OfficePages.tsx | 27 +- .../components/files/office/Presentation.tsx | 36 +- .../components/files/office/Spreadsheet.tsx | 31 +- .../components/files/office/WordDocument.tsx | 22 +- .../files/office/presentation.worker.ts | 3 +- .../components/files/office/word-document.ts | 5 +- .../src/components/files/office/worker-rpc.ts | 31 +- .../web/src/components/files/officeArchive.ts | 86 +- .../components/files/officePreview.worker.ts | 8 +- .../components/files/officePreviewProtocol.ts | 7 +- .../src/components/files/previewFailure.ts | 20 + .../files/previewFailureMessages.ts | 147 + .../files/projectFilesQueryState.ts | 25 +- .../src/components/files/readBinaryPreview.ts | 9 +- .../components/files/readBoundedDocument.ts | 8 +- .../components/files/useDirectoryEntries.ts | 5 +- apps/web/src/components/guest/GuestPage.tsx | 91 +- .../src/components/guest/guestStream.logic.ts | 24 +- .../components/guest/guestTurnItemSource.ts | 9 +- .../components/issue/IssueCommentComposer.tsx | 20 +- .../src/components/issue/IssueDetailGhost.tsx | 41 +- .../src/components/issue/IssueDetailPanel.tsx | 181 +- .../issue/IssueListFilterPickers.tsx | 52 +- apps/web/src/components/issue/IssuesPage.tsx | 125 +- .../src/components/issue/issueSavedViews.ts | 9 +- .../components/mcp/UseInAnotherAppDialog.tsx | 310 +- apps/web/src/components/mcp/mcpApps.ts | 59 +- apps/web/src/components/mcp/mcpGate.ts | 53 +- .../web/src/components/media/MediaActions.tsx | 80 +- .../src/components/media/MediaVideoPlayer.tsx | 12 +- .../src/components/media/OpenMediaLink.tsx | 4 +- apps/web/src/components/media/mediaContent.ts | 33 +- .../components/onboarding/FirstRunGate.tsx | 10 +- .../src/components/onboarding/WelcomePage.tsx | 347 +- .../permissions/PermissionChecklist.tsx | 10 +- .../permissions/usePermissionStatus.ts | 6 +- .../preview/PreviewAnnotationSpeech.tsx | 11 +- .../components/preview/PreviewChromeRow.tsx | 48 +- .../components/preview/PreviewEmptyState.tsx | 21 +- .../src/components/preview/PreviewFindBar.tsx | 14 +- .../preview/PreviewLocalServerCard.tsx | 10 +- .../components/preview/PreviewMoreMenu.tsx | 91 +- .../src/components/preview/PreviewPanel.tsx | 6 +- .../components/preview/PreviewPanelShell.tsx | 4 +- .../preview/PreviewRecentUrlCard.tsx | 4 +- .../components/preview/PreviewUnreachable.tsx | 52 +- .../src/components/preview/PreviewView.tsx | 119 +- .../preview/ThreadPreviewMiniPlayer.tsx | 40 +- .../components/preview/errorCodeMessages.ts | 10 +- .../components/preview/fileExplorerLabel.ts | 34 +- .../components/preview/previewConstants.ts | 26 +- .../src/components/projectScriptEditor.tsx | 112 +- .../promptLinks/HostedPromptLinkLanding.tsx | 72 +- .../promptLinks/NewThreadLinkView.tsx | 64 +- .../promptLinks/ThreadLinkPrompt.tsx | 9 +- .../components/promptLinks/copyPromptLink.ts | 7 +- .../components/promptLinks/linkedPrompt.ts | 21 +- .../pullRequest/ChangeBreakdownGrid.tsx | 21 +- .../pullRequest/LinkPullRequestDialog.tsx | 26 +- .../pullRequest/PullRequestActionsMenu.tsx | 169 +- .../PullRequestActivityUnavailableState.tsx | 19 +- .../pullRequest/PullRequestBaseBranch.tsx | 34 +- .../PullRequestChangeBreakdownStat.tsx | 5 +- .../pullRequest/PullRequestChecksPopover.tsx | 54 +- .../pullRequest/PullRequestCodeTab.tsx | 244 +- .../pullRequest/PullRequestCommentBody.tsx | 4 +- .../pullRequest/PullRequestCommentForm.tsx | 33 +- .../PullRequestCompactFilterMenu.tsx | 8 +- .../pullRequest/PullRequestComposer.tsx | 57 +- .../pullRequest/PullRequestCopyableCode.tsx | 11 +- .../pullRequest/PullRequestDetailActions.tsx | 107 +- .../pullRequest/PullRequestDetailCrumbs.tsx | 26 +- .../pullRequest/PullRequestDetailLayout.tsx | 10 +- .../pullRequest/PullRequestDetailPanel.tsx | 450 +- .../PullRequestDiffUnavailableState.tsx | 14 +- .../pullRequest/PullRequestGhosts.tsx | 135 +- .../pullRequest/PullRequestGuideTab.tsx | 39 +- .../pullRequest/PullRequestLabelPicker.tsx | 32 +- .../pullRequest/PullRequestLinkPreview.tsx | 4 +- .../pullRequest/PullRequestListEmptyState.tsx | 38 +- .../pullRequest/PullRequestListFilters.tsx | 113 +- .../pullRequest/PullRequestListGroups.tsx | 4 +- .../pullRequest/PullRequestMarkdown.tsx | 12 +- .../pullRequest/PullRequestMarkdownEditor.tsx | 20 +- .../PullRequestMarkdownTextarea.tsx | 33 +- .../pullRequest/PullRequestMoreReplies.tsx | 12 +- .../pullRequest/PullRequestReactions.tsx | 21 +- .../PullRequestResolveThreadButton.tsx | 8 +- .../PullRequestReviewAnnotation.tsx | 49 +- .../PullRequestReviewForm.browser.test.tsx | 2 +- .../pullRequest/PullRequestReviewForm.tsx | 51 +- .../pullRequest/PullRequestReviewerPicker.tsx | 63 +- .../components/pullRequest/PullRequestRow.tsx | 11 +- .../pullRequest/PullRequestSpeedActions.tsx | 57 +- .../pullRequest/PullRequestStackHeader.tsx | 11 +- .../PullRequestStackLayerContent.tsx | 13 +- .../pullRequest/PullRequestStackMenu.tsx | 104 +- .../pullRequest/PullRequestStackPopover.tsx | 24 +- .../pullRequest/PullRequestSummaryTab.tsx | 194 +- .../pullRequest/PullRequestThreadLinks.tsx | 70 +- .../pullRequest/PullRequestTimelineTab.tsx | 159 +- .../pullRequest/PullRequestTitleEditor.tsx | 27 +- .../pullRequest/PullRequestsColumn.tsx | 39 +- .../pullRequest/PullRequestsPage.tsx | 81 +- .../PullRequestsUnavailableState.tsx | 8 +- .../pullRequest/ThreadPullRequestsPanel.tsx | 97 +- .../pullRequest/changeRequestTerm.ts | 12 + .../pullRequest/filesViewedStore.ts | 6 +- .../pullRequest/guide/GuideExcerpt.tsx | 44 +- .../pullRequest/guide/GuideNotes.tsx | 8 +- .../pullRequest/guide/GuideRail.tsx | 21 +- .../pullRequest/guide/GuideStop.tsx | 49 +- .../pullRequest/guide/GuideTour.tsx | 9 +- .../guide/PullRequestGuideRunCoordinator.tsx | 6 +- .../pullRequest/guide/useGuideDiffFiles.ts | 3 +- .../pullRequest/guide/useReviewGuideWriter.ts | 7 +- .../pullRequest/pullRequestCheckoutToast.ts | 14 +- .../pullRequest/pullRequestDetail.logic.ts | 92 +- .../pullRequest/pullRequestDiffError.test.ts | 7 +- .../pullRequest/pullRequestDiffError.ts | 31 +- .../pullRequest/pullRequestIcons.tsx | 9 +- .../pullRequest/pullRequestLinkContextMenu.ts | 26 +- .../pullRequest/pullRequestList.logic.ts | 7 +- .../pullRequest/pullRequestListOptions.ts | 59 +- .../pullRequest/pullRequestPresentation.tsx | 191 +- .../pullRequest/pullRequestSavedViews.ts | 8 +- .../pullRequest/pullRequestStackSnapshot.ts | 8 +- .../pullRequest/usePullRequestActions.ts | 234 +- .../pullRequest/usePullRequestFilesViewed.ts | 2 + .../pullRequest/useThreadLinkedPullRequest.ts | 7 +- .../search/ProjectContentSearchDialog.tsx | 72 +- .../components/settings/AboutVersionTitle.tsx | 21 +- .../settings/AcpRegistrySearchStep.tsx | 62 +- .../settings/AcpSessionManagementSection.tsx | 119 +- .../settings/AddCodexAccountDialog.tsx | 31 +- .../settings/AddEnvironmentDialog.tsx | 128 +- .../AddProviderInstanceDialog.logic.ts | 19 +- .../settings/AddProviderInstanceDialog.tsx | 134 +- .../AddProviderInstanceWizardSteps.tsx | 5 +- .../settings/AddUsageLimitSourceDialog.tsx | 32 +- .../components/settings/AdvancedSettings.tsx | 3 +- .../settings/AppearanceSettingsPanel.tsx | 137 +- .../settings/ArchivedThreadsPanel.tsx | 62 +- .../settings/AuthorizedClientsSettings.tsx | 203 +- .../settings/BackgroundActivitySettings.tsx | 168 +- .../settings/BranchNamingSettings.tsx | 60 +- .../settings/BrowserImportWizard.tsx | 191 +- .../settings/CaptureShortcutConfig.tsx | 125 +- .../settings/ChatGptAccountPicker.tsx | 16 +- .../settings/ChatGptConnectionButton.tsx | 4 +- .../settings/ChatGptUsageButton.tsx | 3 +- .../settings/ChatGptWelcomeCoordinator.tsx | 19 +- .../settings/CliCommandSettingsRow.tsx | 60 +- .../settings/CloudVoiceConfiguration.tsx | 125 +- .../components/settings/CodexSetupSection.tsx | 266 +- .../ConnectDeviceApprovalSettings.tsx | 65 +- .../settings/ConnectionDiagnosisDetails.tsx | 69 +- .../settings/ConnectionsSettings.logic.ts | 132 +- .../settings/ConnectionsSettings.tsx | 345 +- .../components/settings/CustomModelEditor.tsx | 87 +- .../settings/DatabaseStorageNotice.tsx | 76 +- .../components/settings/DeviceHostEditor.tsx | 73 +- .../settings/DeviceSourcesSettings.tsx | 153 +- .../settings/DiagnosticsSettings.tsx | 341 +- .../settings/EasDeviceHostEditor.tsx | 96 +- .../settings/EnvironmentIconPicker.tsx | 29 +- .../settings/EnvironmentRoutesList.tsx | 40 +- .../components/settings/EnvironmentRow.tsx | 19 +- .../components/settings/ExpandableText.tsx | 7 +- .../components/settings/FontFamilyPicker.tsx | 20 +- .../settings/IntegrationsSettings.tsx | 324 +- .../settings/IntervalSecondsField.tsx | 12 +- .../settings/IssueTrackerSettings.tsx | 52 +- .../settings/KeybindingsSettings.logic.ts | 179 +- .../settings/KeybindingsSettings.tsx | 265 +- .../components/settings/LabsSettingsPanel.tsx | 75 +- .../components/settings/LinkAccessPicker.tsx | 19 +- .../components/settings/LinkMachineSelect.tsx | 31 +- .../settings/LinkedEnvironmentsSettings.tsx | 108 +- .../settings/LoadBalancingSettings.tsx | 47 +- .../settings/LocalEnvironmentSetting.tsx | 37 +- .../settings/MicrophoneOrderList.tsx | 21 +- .../components/settings/MicrophoneTest.tsx | 51 +- .../settings/MobileAppSettingsRow.tsx | 23 +- .../settings/MultipleAccountsNote.tsx | 21 +- .../settings/NotificationSettings.tsx | 32 +- .../settings/OpenSourceLicenses.tsx | 64 +- .../settings/PanelAnimationsPreview.tsx | 4 +- .../settings/ProcessSignalActions.tsx | 24 +- .../settings/ProjectActionsList.tsx | 12 +- .../settings/ProjectActionsSettings.tsx | 39 +- .../settings/ProjectDefaultsSettings.logic.ts | 28 +- .../settings/ProjectDefaultsSettings.tsx | 193 +- .../settings/ProjectFaviconPickerDialog.tsx | 43 +- .../settings/ProjectIconPickerDialog.tsx | 57 +- .../settings/ProjectSettingsPanel.tsx | 177 +- .../components/settings/ProjectsSettings.tsx | 6 +- .../settings/ProviderAccentColorPicker.tsx | 28 +- .../settings/ProviderAuthTerminal.tsx | 8 +- .../ProviderAuthenticationSection.tsx | 138 +- .../settings/ProviderInstanceCard.tsx | 185 +- .../settings/ProviderModelsSection.tsx | 100 +- .../settings/ProviderSettingsForm.tsx | 207 +- .../settings/ProviderSettingsPanel.tsx | 210 +- .../settings/ProviderSetupSection.tsx | 107 +- .../ProviderWizardAuthenticationStep.tsx | 15 +- .../settings/PullRequestRoutingSettings.tsx | 47 +- .../ResourceTelemetryDiagnostics.logic.ts | 40 +- .../settings/ResourceTelemetryDiagnostics.tsx | 453 +- .../settings/RevokeConnectDeviceDialog.tsx | 15 +- .../settings/SavedEnvironmentRows.tsx | 253 +- .../settings/ScheduledTasksSettings.tsx | 572 +- .../src/components/settings/SecretInput.tsx | 7 +- .../settings/SecretProviderDialog.logic.ts | 12 +- .../settings/SecretProviderDialog.tsx | 34 +- .../components/settings/SecretSourceInput.tsx | 41 +- .../settings/SecretsSettings.logic.ts | 17 +- .../components/settings/SecretsSettings.tsx | 67 +- .../settings/SessionPermissions.tsx | 34 +- .../settings/SettingInheritance.tsx | 125 +- .../settings/SettingsBreadcrumb.tsx | 5 +- .../settings/SettingsFontPreviews.tsx | 7 +- .../settings/SettingsPanels.logic.ts | 41 +- .../components/settings/SettingsPanels.tsx | 758 +- .../settings/SettingsScopeContext.tsx | 6 +- .../settings/SettingsScopeNotice.tsx | 8 +- .../settings/SettingsScopeSentence.tsx | 168 +- .../settings/SettingsSidebarNav.tsx | 3 +- .../settings/SimlockDeviceHostEditor.tsx | 89 +- .../settings/SnapShotSettings.logic.ts | 118 +- .../components/settings/SnapShotSettings.tsx | 130 +- .../settings/SnapShotSetupDialog.logic.ts | 20 +- .../settings/SnapShotSetupDialog.tsx | 179 +- .../settings/SnoozePresetsSettings.tsx | 125 +- .../settings/SourceControlAccountSettings.tsx | 106 +- .../SourceControlAppSignInSettings.tsx | 60 +- .../settings/SourceControlHostSettings.tsx | 3 +- .../settings/SourceControlSettings.tsx | 160 +- .../settings/SourceControlTokenSettings.tsx | 48 +- .../settings/SourceControlWritingSettings.tsx | 126 +- .../settings/SpeechLanguageSelect.tsx | 34 +- .../settings/SpeechModelComparison.tsx | 38 +- .../components/settings/StorageSettings.tsx | 266 +- .../settings/TelemetryExportSettings.tsx | 116 +- .../settings/TextGeneratorsSettings.tsx | 166 +- .../components/settings/ThemeColorPicker.tsx | 73 +- .../components/settings/ThemeCssEditor.tsx | 14 +- .../components/settings/ThemeEditorHost.tsx | 10 +- .../components/settings/ThemeEditorPanel.tsx | 206 +- .../components/settings/ThemeImportDialog.tsx | 69 +- .../settings/ThemePreviewCircles.tsx | 10 +- .../settings/ThemeSearchSection.tsx | 111 +- .../src/components/settings/ThemeSettings.tsx | 179 +- .../settings/ThreadDetailsItemsRow.tsx | 20 +- .../ThreadTitleInstructionsSettings.tsx | 15 +- .../settings/TypographySettings.tsx | 92 +- .../settings/UpdateTrackSwitchDialog.tsx | 91 +- .../settings/UsageProviderSettings.tsx | 37 +- .../settings/VoiceSettingsPanel.tsx | 485 +- .../components/settings/WorktreesSettings.tsx | 22 +- .../settings/browserImportWizard.logic.ts | 23 +- .../settings/customModelEditor.logic.ts | 112 +- .../settings/deviceHostConnectionChecks.ts | 11 +- .../settings/deviceHostsSettings.logic.ts | 9 +- .../settings/easDeviceHostsSettings.logic.ts | 25 +- .../src/components/settings/providerStatus.ts | 77 +- .../settings/scheduledTasksSettings.logic.ts | 123 +- .../src/components/settings/scopedSettings.ts | 30 +- .../components/settings/settingsLayout.tsx | 82 +- .../src/components/settings/settingsScope.ts | 30 +- .../settings/settingsSearch.test.ts | 5 +- .../src/components/settings/settingsSearch.ts | 690 +- .../simlockDeviceHostsSettings.logic.ts | 30 +- .../settings/updateTrackSwitch.logic.ts | 69 +- .../useAvailableSettingsSearchItems.ts | 2 + .../settings/useHostConnectionChecks.ts | 4 +- .../settings/useProjectScriptSettings.ts | 20 +- .../settings/useScopedModelAvailability.ts | 11 +- .../components/settings/useScopedSettings.ts | 22 +- .../settings/useSnapShotShortcutRecorder.tsx | 24 +- .../src/components/sidebar/SidebarChrome.tsx | 26 +- .../components/sidebar/SidebarDraftBlock.tsx | 14 +- .../components/sidebar/SidebarFolderDrop.tsx | 24 +- .../sidebar/SidebarProjectFolderHeader.tsx | 21 +- .../sidebar/SidebarProviderUpdatePill.tsx | 27 +- .../sidebar/SidebarThreadHeader.tsx | 23 +- .../components/sidebar/SidebarThreadRow.tsx | 164 +- .../sidebar/SidebarThreadUndoNotice.tsx | 20 +- .../sidebar/SidebarUpdateCapsule.tsx | 49 +- .../components/sidebar/SidebarUpdatePill.tsx | 70 +- .../sidebar/SidebarUpdateReleaseNotes.tsx | 36 +- .../sidebar/UpdateEverythingDialog.tsx | 75 +- .../sidebar/updateEverything.logic.test.ts | 8 +- .../sidebar/updateEverything.logic.ts | 401 +- .../sidebar/updateEverythingRun.tsx | 20 +- .../components/sidebar/useUpdateEverything.ts | 39 +- .../components/sourceControlAppAccessToast.ts | 14 +- .../src/components/threadActionMenu.logic.ts | 121 +- .../threadTitleRegenerationToast.ts | 37 +- .../src/components/ui/anchoredCopyToast.ts | 5 +- apps/web/src/components/ui/color-picker.tsx | 28 +- apps/web/src/components/ui/dialog.tsx | 4 +- apps/web/src/components/ui/sheet.tsx | 4 +- apps/web/src/components/ui/sidebar.tsx | 17 +- apps/web/src/components/ui/spinner.tsx | 4 +- .../web/src/components/ui/standalone-page.tsx | 1 + apps/web/src/components/ui/toast.tsx | 29 +- apps/web/src/components/ui/wizard.tsx | 14 +- apps/web/src/components/usage/UsageLimits.tsx | 96 +- .../components/usage/UsageLimitsPooled.tsx | 124 +- .../src/components/usage/UsageModelDialog.tsx | 43 +- apps/web/src/components/usage/UsagePage.tsx | 287 +- .../components/usage/UsagePriceOverrides.tsx | 160 +- .../components/usage/UsageProviderChart.tsx | 34 +- .../src/components/usage/UsageShareBar.tsx | 6 +- .../src/components/usage/usageBreakdown.ts | 30 +- .../src/components/usage/usagePriceForm.ts | 9 +- .../src/components/usage/usagePriceTable.ts | 60 +- .../src/components/usage/usagePriceTargets.ts | 9 +- .../src/components/usage/usageShortcuts.ts | 15 +- apps/web/src/composer-code-languages.ts | 14 +- apps/web/src/composerPlaceholder.ts | 4 +- apps/web/src/connection/clientMetadata.ts | 2 + apps/web/src/connection/platform.ts | 51 +- apps/web/src/connection/storage.ts | 100 +- apps/web/src/contextMenuFallback.ts | 5 +- apps/web/src/editorLabels.ts | 30 +- apps/web/src/editorPreferences.ts | 17 +- apps/web/src/environments/primary/auth.ts | 18 +- apps/web/src/environments/primary/target.ts | 4 +- apps/web/src/fileContextMenu.ts | 29 +- apps/web/src/hooks/showThreadUndoNotice.ts | 42 +- apps/web/src/hooks/useCopyToClipboard.test.ts | 4 +- apps/web/src/hooks/useCopyToClipboard.ts | 83 +- .../hooks/useIncrementalTimelineEntries.ts | 15 +- apps/web/src/hooks/useNewProject.ts | 41 +- apps/web/src/hooks/useOpenLocalWorkspace.ts | 8 +- apps/web/src/hooks/useProjectGroupUpdate.ts | 32 +- apps/web/src/hooks/usePullRequestLinking.ts | 9 +- apps/web/src/hooks/useRelativeTimeState.ts | 4 +- apps/web/src/hooks/useRemoveClonedProject.ts | 7 +- .../src/hooks/useRightPanelSurfaceClose.ts | 5 +- apps/web/src/hooks/useScratchProject.ts | 9 +- apps/web/src/hooks/useSettings.ts | 73 +- apps/web/src/hooks/useStartTriage.ts | 33 +- apps/web/src/hooks/useThreadActionMenu.ts | 71 +- apps/web/src/hooks/useThreadActions.ts | 92 +- apps/web/src/i18n/initializeI18n.ts | 2 + apps/web/src/i18n/messages.ts | 39 + apps/web/src/i18n/runtime.ts | 2 + apps/web/src/i18n/translations/de.json | 12071 ++++++++++++++- apps/web/src/i18n/translations/en.json | 12072 ++++++++++++++- apps/web/src/i18n/translations/es.json | 12070 ++++++++++++++- apps/web/src/i18n/translations/fr.json | 12087 ++++++++++++++- apps/web/src/i18n/translations/ja.json | 12019 ++++++++++++++- apps/web/src/i18n/translations/ko.json | 12013 ++++++++++++++- apps/web/src/i18n/translations/pt-BR.json | 12090 ++++++++++++++- apps/web/src/i18n/translations/ru.json | 12078 ++++++++++++++- apps/web/src/i18n/translations/sv.json | 12103 +++++++++++++++ apps/web/src/i18n/translations/zh.json | 12138 +++++++++++++++- .../web/src/lib/accessibilityAnnouncements.ts | 6 +- apps/web/src/lib/addProjectToMachine.ts | 19 +- apps/web/src/lib/attachmentUploadQueue.ts | 62 +- apps/web/src/lib/attachmentUploadState.ts | 29 +- apps/web/src/lib/bootError.ts | 5 + apps/web/src/lib/composerContextRecords.ts | 157 +- apps/web/src/lib/copyThreadReference.ts | 19 +- apps/web/src/lib/diffFileContents.ts | 4 +- apps/web/src/lib/diffRendering.ts | 8 +- apps/web/src/lib/discardComposerDraft.ts | 6 +- apps/web/src/lib/imageCompression.ts | 7 +- apps/web/src/lib/openPullRequestLink.ts | 11 +- apps/web/src/lib/projectScriptKeybindings.ts | 9 +- apps/web/src/lib/resourceTelemetryState.ts | 10 +- apps/web/src/lib/snapShotShortcut.ts | 1 + apps/web/src/lib/terminalCloseConfirm.ts | 21 +- apps/web/src/lib/toolCallDiff.ts | 8 +- apps/web/src/lib/utils.ts | 8 +- apps/web/src/localApi.ts | 10 +- apps/web/src/markdown-clipboard.ts | 1 + apps/web/src/onboarding/useProjectScans.ts | 4 +- apps/web/src/openVsxThemes.ts | 135 +- apps/web/src/projectIconColors.ts | 37 +- apps/web/src/projectIconOptions.ts | 62 +- apps/web/src/proposedPlan.ts | 6 +- apps/web/src/providerAuthDelivery.ts | 10 +- apps/web/src/reviewCommentContext.ts | 2 + apps/web/src/rightPanelStore.ts | 10 +- apps/web/src/routes/__root.tsx | 44 +- apps/web/src/routes/_chat.index.tsx | 12 +- apps/web/src/routes/_chat.new.tsx | 10 +- .../src/routes/_chat.settings.providers.tsx | 6 +- apps/web/src/routes/_chat.settings.tsx | 30 +- apps/web/src/session-logic.ts | 119 +- apps/web/src/shortcuts/chatRouteCommands.ts | 6 +- .../src/shortcuts/commandPaletteCommands.ts | 13 +- apps/web/src/sidebarProjectGrouping.ts | 8 +- apps/web/src/speech/browserMicrophones.ts | 4 +- apps/web/src/speech/browserPcmCapture.ts | 23 +- apps/web/src/speech/browserVoiceInput.ts | 9 +- .../src/speech/useEnvironmentSpeechInput.ts | 30 +- apps/web/src/speech/voiceInputSession.ts | 15 +- apps/web/src/state/desktopCliCommand.ts | 7 +- apps/web/src/state/desktopNetworkAccess.ts | 9 +- apps/web/src/state/desktopSnapShot.ts | 7 +- apps/web/src/state/desktopSshHosts.ts | 7 +- apps/web/src/state/desktopUpdate.ts | 9 +- apps/web/src/state/desktopWslState.ts | 7 +- apps/web/src/state/device.ts | 3 + apps/web/src/state/entities.ts | 5 +- apps/web/src/state/filesystem.ts | 22 +- apps/web/src/state/managedPolicy.ts | 13 +- apps/web/src/state/npmRelease.ts | 24 +- apps/web/src/state/queries.ts | 46 +- apps/web/src/state/query.ts | 19 +- apps/web/src/state/sourceControlActions.ts | 20 +- apps/web/src/state/terminalSessions.ts | 4 +- apps/web/src/state/usage.ts | 5 +- .../src/state/use-orchestration-command.ts | 9 +- apps/web/src/state/usePullRequestStack.ts | 5 +- apps/web/src/terminal/ghostty/surface.ts | 6 +- apps/web/src/textGenerators.ts | 21 +- apps/web/src/themePalette.ts | 96 +- apps/web/src/threadNotifications.ts | 9 +- apps/web/src/threadSync.ts | 9 +- apps/web/src/timestampFormat.ts | 150 +- apps/web/src/useNativeFileDrag.ts | 9 +- apps/web/src/versionSkew.ts | 10 +- apps/web/src/vscodeThemeImport.ts | 15 +- docs/internals/i18n.md | 46 + oxlint-plugin-t3code/index.ts | 2 + .../rules/no-untranslated-copy.ts | 452 + package.json | 1 + packages/client-runtime/package.json | 13 + .../src/authorization/service.ts | 23 +- .../client-runtime/src/composerThreadItems.ts | 45 +- .../src/connection/compatibility.ts | 15 +- .../src/connection/diagnosis.ts | 212 +- .../client-runtime/src/connection/driver.ts | 6 +- .../client-runtime/src/connection/errors.ts | 87 +- .../src/connection/hostFreeze.ts | 19 +- .../client-runtime/src/connection/model.ts | 4 + .../src/connection/onboarding.ts | 23 +- .../src/connection/outdatedHostUpdate.ts | 15 +- .../src/connection/presentation.ts | 79 +- .../pullRequestRoutingPermissions.ts | 10 +- .../client-runtime/src/connection/registry.ts | 11 +- .../client-runtime/src/connection/resolver.ts | 14 +- .../client-runtime/src/connection/routes.ts | 26 +- .../src/connection/supervisor.ts | 23 +- packages/client-runtime/src/contractLabels.ts | 287 + .../client-runtime/src/device/screenshot.ts | 10 +- packages/client-runtime/src/device/stream.ts | 85 +- packages/client-runtime/src/errors/index.ts | 1 + packages/client-runtime/src/errors/network.ts | 9 +- .../client-runtime/src/errors/translatable.ts | 115 + packages/client-runtime/src/filePreview.ts | 13 +- .../client-runtime/src/issuePresentation.ts | 52 +- packages/client-runtime/src/linkRequest.ts | 53 +- packages/client-runtime/src/listFormat.ts | 36 + packages/client-runtime/src/locales.ts | 1 + packages/client-runtime/src/modelTraits.ts | 29 +- .../client-runtime/src/operations/commands.ts | 8 +- .../client-runtime/src/operations/projects.ts | 74 +- .../src/operations/threadTitle.ts | 26 +- .../src/preview/serverBrowserStream.ts | 38 +- .../src/providerUpdateRequiredModels.ts | 37 +- .../src/pullRequestLinkInput.ts | 47 +- .../src/pullRequestReactions.ts | 80 +- packages/client-runtime/src/queuedRunEdit.ts | 15 +- .../client-runtime/src/relay/discovery.ts | 8 +- .../client-runtime/src/relay/dpopProof.ts | 6 +- .../src/relay/errorPresentation.ts | 153 +- .../client-runtime/src/relay/managedRelay.ts | 135 +- .../src/relay/managedRelayState.ts | 71 +- .../client-runtime/src/reviewGuideTour.ts | 11 +- packages/client-runtime/src/rpc/client.ts | 36 +- packages/client-runtime/src/rpc/http.ts | 45 +- packages/client-runtime/src/rpc/session.ts | 21 +- packages/client-runtime/src/savedViews.ts | 9 +- .../src/scheduledTaskWebhook.ts | 37 +- packages/client-runtime/src/secretRequest.ts | 88 +- .../src/state/attachmentUploads.ts | 8 +- .../client-runtime/src/state/attachments.ts | 31 +- .../src/state/commandPermissions.ts | 9 +- .../src/state/connectMcpApproval.ts | 8 +- packages/client-runtime/src/state/device.ts | 59 +- .../src/state/environmentHttpAuth.ts | 22 +- .../client-runtime/src/state/filesystem.ts | 33 +- .../client-runtime/src/state/gitActions.ts | 262 +- .../client-runtime/src/state/issueTrackers.ts | 52 +- packages/client-runtime/src/state/models.ts | 17 +- .../client-runtime/src/state/orchestration.ts | 6 +- .../src/state/outdatedServerUpdate.ts | 8 +- .../client-runtime/src/state/presentation.ts | 6 + .../src/state/projectCommands.ts | 10 +- .../src/state/projectGrouping.ts | 19 +- .../src/state/projectRemoval.ts | 79 +- .../src/state/pullRequestDiffHttp.ts | 12 +- .../src/state/pullRequestRouting.ts | 6 +- .../client-runtime/src/state/pullRequests.ts | 6 +- packages/client-runtime/src/state/runtime.ts | 18 +- packages/client-runtime/src/state/server.ts | 89 +- packages/client-runtime/src/state/shell.ts | 9 +- .../src/state/subagentDisplay.ts | 83 +- .../src/state/subagentRuntime.ts | 73 +- .../src/state/threadActivityAnnouncement.ts | 34 +- .../src/state/threadExecution.ts | 155 +- .../src/state/threadFamilies.ts | 4 +- .../src/state/threadFeedback.ts | 54 +- .../src/state/threadRequests.ts | 17 +- .../client-runtime/src/state/threadSettled.ts | 105 +- .../client-runtime/src/state/threadShell.ts | 24 +- .../src/state/threadSubagents.ts | 15 +- .../src/state/threadWorkflows.ts | 9 +- packages/client-runtime/src/state/threads.ts | 32 +- .../client-runtime/src/state/usageAccess.ts | 21 +- .../client-runtime/src/state/usageProgress.ts | 16 +- .../client-runtime/src/state/vcsAction.ts | 77 +- packages/client-runtime/src/t3ToolSummary.ts | 1695 ++- .../client-runtime/src/threadReference.ts | 34 +- packages/client-runtime/src/userMessage.ts | 9 +- .../src/voice-input/controller.ts | 168 +- .../client-runtime/src/voice-input/index.ts | 1 + .../client-runtime/src/voice-input/stream.ts | 35 +- .../src/voice-input/transcription.ts | 5 +- packages/client-runtime/src/webhookAddress.ts | 13 +- .../src/work-log/presentation.ts | 237 +- .../src/work-log/t3ToolSentences.ts | 876 ++ packages/client-runtime/src/zip/boundedZip.ts | 14 +- .../client-runtime/src/zip/zipDirectory.ts | 24 +- packages/client-runtime/src/zip/zipError.ts | 39 + .../src/zip/zipErrorMessages.ts | 22 + packages/shared/package.json | 49 + packages/shared/src/authScopeOptions.ts | 92 +- .../shared/src/codexArtifactTemplatesCopy.ts | 25 + .../shared/src/orchestrationTimingCopy.ts | 26 + packages/shared/src/paletteSearch.test.ts | 3 + packages/shared/src/paletteSearch.ts | 27 +- packages/shared/src/paletteSearchCopy.ts | 20 + packages/shared/src/projectScripts.ts | 8 - packages/shared/src/projectScriptsCopy.ts | 17 + packages/shared/src/promptLinks.ts | 58 +- packages/shared/src/promptLinksCopy.ts | 51 + packages/shared/src/speech.ts | 8 - packages/shared/src/speechCopy.ts | 24 + .../shared/src/t3McpToolPresentationCopy.ts | 128 + packages/shared/src/terminalLabels.ts | 15 +- packages/shared/src/terminalLabelsCopy.ts | 21 + packages/shared/src/thirdPartyLicenses.ts | 51 +- packages/shared/src/threadLinks.ts | 5 +- packages/shared/src/threadLinksCopy.ts | 16 + packages/shared/src/toolActivity.ts | 56 +- packages/shared/src/toolActivityCopy.ts | 57 + packages/shared/src/usageFormat.ts | 95 +- packages/shared/src/usageFormatCopy.ts | 66 + packages/shared/src/usageLimits.test.ts | 2 +- packages/shared/src/usageLimits.ts | 106 +- packages/shared/src/usageLimitsCopy.ts | 215 + pnpm-lock.yaml | 15 + scripts/i18n-check.ts | 24 +- scripts/i18n-untranslated.ts | 41 + vite.config.ts | 14 + 1408 files changed, 220145 insertions(+), 20867 deletions(-) create mode 100644 apps/desktop/gt.config.json create mode 100644 apps/desktop/scripts/i18n-generate.mjs create mode 100644 apps/desktop/src/i18n/messages.ts create mode 100644 apps/desktop/src/i18n/translations/de.json create mode 100644 apps/desktop/src/i18n/translations/en.json create mode 100644 apps/desktop/src/i18n/translations/es.json create mode 100644 apps/desktop/src/i18n/translations/fr.json create mode 100644 apps/desktop/src/i18n/translations/ja.json create mode 100644 apps/desktop/src/i18n/translations/ko.json create mode 100644 apps/desktop/src/i18n/translations/pt-BR.json create mode 100644 apps/desktop/src/i18n/translations/ru.json create mode 100644 apps/desktop/src/i18n/translations/sv.json create mode 100644 apps/desktop/src/i18n/translations/zh.json create mode 100644 apps/mobile/src/features/usage/usageAxisLabels.ts create mode 100644 apps/mobile/src/i18n/messages.ts create mode 100644 apps/mobile/src/i18n/translations/sv.json create mode 100644 apps/mobile/src/lib/changeRequestTerm.ts create mode 100644 apps/web/src/components/files/previewFailure.ts create mode 100644 apps/web/src/components/files/previewFailureMessages.ts create mode 100644 apps/web/src/components/pullRequest/changeRequestTerm.ts create mode 100644 apps/web/src/i18n/messages.ts create mode 100644 apps/web/src/i18n/translations/sv.json create mode 100644 docs/internals/i18n.md create mode 100644 oxlint-plugin-t3code/rules/no-untranslated-copy.ts create mode 100644 packages/client-runtime/src/contractLabels.ts create mode 100644 packages/client-runtime/src/errors/translatable.ts create mode 100644 packages/client-runtime/src/listFormat.ts create mode 100644 packages/client-runtime/src/work-log/t3ToolSentences.ts create mode 100644 packages/client-runtime/src/zip/zipError.ts create mode 100644 packages/client-runtime/src/zip/zipErrorMessages.ts create mode 100644 packages/shared/src/codexArtifactTemplatesCopy.ts create mode 100644 packages/shared/src/orchestrationTimingCopy.ts create mode 100644 packages/shared/src/paletteSearchCopy.ts create mode 100644 packages/shared/src/projectScriptsCopy.ts create mode 100644 packages/shared/src/promptLinksCopy.ts create mode 100644 packages/shared/src/speechCopy.ts create mode 100644 packages/shared/src/t3McpToolPresentationCopy.ts create mode 100644 packages/shared/src/terminalLabelsCopy.ts create mode 100644 packages/shared/src/threadLinksCopy.ts create mode 100644 packages/shared/src/toolActivityCopy.ts create mode 100644 packages/shared/src/usageFormatCopy.ts create mode 100644 packages/shared/src/usageLimitsCopy.ts create mode 100644 scripts/i18n-untranslated.ts diff --git a/apps/desktop/gt.config.json b/apps/desktop/gt.config.json new file mode 100644 index 000000000000..b77af550c763 --- /dev/null +++ b/apps/desktop/gt.config.json @@ -0,0 +1,10 @@ +{ + "defaultLocale": "en", + "locales": ["de", "es", "fr", "ja", "ko", "pt-BR", "ru", "sv", "zh"], + "src": ["src/**/*.ts", "!**/*.test.ts"], + "files": { + "gt": { + "output": "src/i18n/translations/[locale].json" + } + } +} diff --git a/apps/desktop/package.json b/apps/desktop/package.json index 0daa6f14cf5c..d91a9ee5e4cf 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -7,7 +7,8 @@ "scripts": { "ensure:electron": "node scripts/ensure-electron-runtime.mjs", "start": "node scripts/start-electron.mjs", - "test": "vp test run --passWithNoTests" + "test": "vp test run --passWithNoTests", + "i18n:generate": "node scripts/i18n-generate.mjs" }, "dependencies": { "@clerk/electron": "catalog:", @@ -27,6 +28,7 @@ "electron-updater": "6.8.9", "electron-webauthn": "catalog:", "ffi-rs": "1.3.2", + "gt-i18n": "1.0.40", "playwright-core": "1.64.1", "react-grab": "^0.1.32", "tldts": "catalog:" @@ -37,6 +39,7 @@ "acorn": "8.16.0", "cross-env": "^10.1.0", "electron-builder": "26.16.1", + "gt": "2.27.0", "jsdom": "^30.0.1", "tailwindcss": "^4.0.0", "vite-plus": "catalog:" diff --git a/apps/desktop/scripts/i18n-generate.mjs b/apps/desktop/scripts/i18n-generate.mjs new file mode 100644 index 000000000000..0fc5803202fa --- /dev/null +++ b/apps/desktop/scripts/i18n-generate.mjs @@ -0,0 +1,15 @@ +import * as NodeModule from "node:module"; + +// The gt CLI picks its commands from package.json, and gt-i18n alone gets no `generate`. +const { Command } = NodeModule.createRequire(import.meta.resolve("gt"))("commander"); +const { NodeCLI } = await import("gt/cli/node"); + +const program = new Command("gt"); +new NodeCLI(program, "gt-node", []).init(); +await program.parseAsync([ + "node", + "gt", + "generate", + "--skip-version-check", + ...process.argv.slice(2), +]); diff --git a/apps/desktop/src/app/DesktopApp.ts b/apps/desktop/src/app/DesktopApp.ts index 56fe979cf8c6..34476ee7855b 100644 --- a/apps/desktop/src/app/DesktopApp.ts +++ b/apps/desktop/src/app/DesktopApp.ts @@ -42,6 +42,8 @@ import * as DesktopSnapShot from "../snapShot/DesktopSnapShot.ts"; import * as DesktopWslBackend from "../wsl/DesktopWslBackend.ts"; import * as DesktopRendererHistory from "../telemetry/DesktopRendererHistory.ts"; import * as HostProcess from "@t3tools/shared/HostProcess"; +import { msg } from "gt-i18n"; +import { m } from "../i18n/messages.ts"; const DEFAULT_DESKTOP_BACKEND_PORT = 3773; const MAX_TCP_PORT = 65_535; @@ -147,7 +149,7 @@ const handleFatalStartupError = Effect.fn("desktop.startup.handleFatalStartupErr const wasQuitting = yield* Ref.getAndSet(state.quitting, true); if (!wasQuitting) { yield* electronDialog.showErrorBox( - "T3 Code failed to start", + m(msg("T3 Code failed to start")), `Stage: ${stage}\n${message}${detail}`, ); } @@ -216,7 +218,7 @@ const startLocalBackend = Effect.gen(function* () { owner: Option.getOrNull(owner), }); yield* (yield* ElectronDialog.ElectronDialog).showErrorBox( - "This T3 home is unavailable", + m(msg("This T3 home is unavailable")), DesktopHomeOwner.homeOwnedMessage(owner), ); yield* (yield* ElectronApp.ElectronApp).quit; diff --git a/apps/desktop/src/app/DesktopStartupRecovery.ts b/apps/desktop/src/app/DesktopStartupRecovery.ts index 769a30cf7680..768fe2ee3d8d 100644 --- a/apps/desktop/src/app/DesktopStartupRecovery.ts +++ b/apps/desktop/src/app/DesktopStartupRecovery.ts @@ -7,11 +7,13 @@ import type * as Scope from "effect/Scope"; import * as Stream from "effect/Stream"; import * as SubscriptionRef from "effect/SubscriptionRef"; import type * as Electron from "electron"; +import { msg } from "gt-i18n"; import * as ElectronApp from "../electron/ElectronApp.ts"; import * as ElectronShell from "../electron/ElectronShell.ts"; import * as ElectronTheme from "../electron/ElectronTheme.ts"; import * as ElectronWindow from "../electron/ElectronWindow.ts"; +import { m } from "../i18n/messages.ts"; import * as DesktopUpdates from "../updates/DesktopUpdates.ts"; import type { BackendStartupFailure } from "../backend/DesktopBackendManager.ts"; import * as DesktopEnvironment from "./DesktopEnvironment.ts"; @@ -81,30 +83,59 @@ const actionLink = (action: StartupRecoveryAction, label: string, primary = fals function describeOffer(offer: StartupRecoveryOffer): { text: string; action: string } { switch (offer._tag) { case "Checking": - return { text: "Checking for a newer version…", action: "" }; + return { text: m(msg("Checking for a newer version…")), action: "" }; case "Update": return { - text: `Version ${offer.version} is available. It can contain a fix.`, - action: actionLink("update", `Update to ${offer.version}`, true), + text: m(msg("Version {version} is available. It can contain a fix."), { + version: offer.version, + }), + action: actionLink( + "update", + m(msg("Update to {version}"), { version: offer.version }), + true, + ), }; case "Downloading": return { - text: `Downloading ${offer.version}${offer.percent === null ? "" : ` (${Math.floor(offer.percent / 10) * 10}%)`}. T3 Code restarts when the download is done.`, + text: + offer.percent === null + ? m(msg("Downloading {version}. T3 Code restarts when the download is done."), { + version: offer.version, + }) + : m( + msg( + "Downloading {version} ({percent}%). T3 Code restarts when the download is done.", + ), + { version: offer.version, percent: String(Math.floor(offer.percent / 10) * 10) }, + ), action: "", }; case "Reinstall": return { - text: `Version ${offer.version} started correctly on this computer. Download it and install it to go back.`, - action: actionLink("reinstall", `Download ${offer.version}`, true), + text: m( + msg( + "Version {version} started correctly on this computer. Download it and install it to go back.", + ), + { version: offer.version }, + ), + action: actionLink( + "reinstall", + m(msg("Download {version}"), { version: offer.version }), + true, + ), }; case "Releases": return { - text: "Get a different version from the releases page.", - action: actionLink("releases", "Open releases", true), + text: m(msg("Get a different version from the releases page.")), + action: actionLink("releases", m(msg("Open releases")), true), }; case "ManagedPolicy": return { - text: "Your organization's managed policy stopped T3 Code from starting. Send the details below to your IT administrator.", + text: m( + msg( + "Your organization's managed policy stopped T3 Code from starting. Send the details below to your IT administrator.", + ), + ), action: "", }; } @@ -118,7 +149,8 @@ function buildStartupRecoveryHtml(input: { }): string { const offer = describeOffer(input.offer); const output = input.failure.output.trim(); - return `T3 Code could not start -

T3 Code could not start

+

${title}

${escapeHtml(input.failure.reason)}

${escapeHtml(offer.text)}

-
${offer.action}${actionLink("copy", "Copy details")}${actionLink("quit", "Quit")}
-
${escapeHtml(output.length > 0 ? output : "The server wrote no output.")}
-

Version ${escapeHtml(input.appVersion)}. T3 Code tries again in the background. Logs: ${escapeHtml(input.logDir)}

+
${offer.action}${actionLink("copy", m(msg("Copy details")))}${actionLink("quit", m(msg("Quit", { $context: "button, quits the app" })))}
+
${escapeHtml(output.length > 0 ? output : m(msg("The server wrote no output.")))}
+

${escapeHtml(m(msg("Version {version}. T3 Code tries again in the background. Logs: {logDir}"), { version: input.appVersion, logDir: input.logDir }))}

`; } @@ -270,7 +302,7 @@ export const listen: Effect.Effect< minWidth: 420, minHeight: 320, show: false, - title: "T3 Code could not start", + title: m(msg("T3 Code could not start")), autoHideMenuBar: true, backgroundColor: shouldUseDarkColors ? "#000000" : "#ffffff", webPreferences: { diff --git a/apps/desktop/src/backend/DesktopBackendPool.ts b/apps/desktop/src/backend/DesktopBackendPool.ts index 62c811996b1a..1221b38d9020 100644 --- a/apps/desktop/src/backend/DesktopBackendPool.ts +++ b/apps/desktop/src/backend/DesktopBackendPool.ts @@ -16,6 +16,7 @@ import * as Schema from "effect/Schema"; import * as Scope from "effect/Scope"; import * as SubscriptionRef from "effect/SubscriptionRef"; import * as SynchronizedRef from "effect/SynchronizedRef"; +import { msg } from "gt-i18n"; import * as FileSystem from "effect/FileSystem"; import { HttpClient } from "effect/http"; @@ -34,6 +35,7 @@ import * as DesktopWindow from "../window/DesktopWindow.ts"; import * as DesktopWslEnvironment from "../wsl/DesktopWslEnvironment.ts"; import * as ElectronDialog from "../electron/ElectronDialog.ts"; import * as ElectronApp from "../electron/ElectronApp.ts"; +import { m } from "../i18n/messages.ts"; const { logWarning: logBackendPoolWarning } = DesktopObservability.makeComponentLogger("desktop-backend-pool"); @@ -189,8 +191,8 @@ export const layer = Layer.effect( { reason }, ); yield* electronDialog.showErrorBox( - "WSL backend is still unavailable", - `${reason}\n\nT3 Code will use the Windows backend for this launch and retry WSL the next time the app starts.`, + m(msg("WSL backend is still unavailable")), + `${reason}\n\n${m(msg("T3 Code will use the Windows backend for this launch and retry WSL the next time the app starts."))}`, ); yield* appSettings.applyWslWindowsFallbackInMemory; return true; @@ -200,8 +202,8 @@ export const layer = Layer.effect( reason, }); yield* electronDialog.showErrorBox( - "WSL backend couldn't start", - `${reason}\n\nFalling back to the Windows backend so T3 Code can open. Re-enable the WSL backend from Settings > Sharing & access once the WSL distro is fixed.`, + m(msg("WSL backend couldn't start")), + `${reason}\n\n${m(msg("Falling back to the Windows backend so T3 Code can open. Re-enable the WSL backend from Settings > Sharing & access once the WSL distro is fixed."))}`, ); // Clear wslOnly too so enabling WSL cannot restore a failed mode. // Keep the in-memory fallback if persistence fails. @@ -248,7 +250,7 @@ export const layer = Layer.effect( DesktopHomeOwner.readLiveHomeOwner().pipe( Effect.flatMap((owner) => electronDialog.showErrorBox( - "This T3 home is unavailable", + m(msg("This T3 home is unavailable")), DesktopHomeOwner.homeOwnedMessage(owner), ), ), diff --git a/apps/desktop/src/backend/DesktopHomeOwner.ts b/apps/desktop/src/backend/DesktopHomeOwner.ts index 9313591eb7b9..7fc833a3fc10 100644 --- a/apps/desktop/src/backend/DesktopHomeOwner.ts +++ b/apps/desktop/src/backend/DesktopHomeOwner.ts @@ -7,8 +7,10 @@ import * as FileSystem from "effect/FileSystem"; import * as Option from "effect/Option"; import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; +import { msg } from "gt-i18n"; import * as DesktopEnvironment from "../app/DesktopEnvironment.ts"; +import { m } from "../i18n/messages.ts"; import { BACKEND_QUIT_STOP_TIMEOUT } from "./DesktopBackendManager.ts"; // The fields of the server's `server-runtime.json` that identify the owner of a T3 home. @@ -92,15 +94,44 @@ export const readLiveHomeOwner = Effect.fn("DesktopHomeOwner.readLiveHomeOwner") export const homeOwnedMessage = (owner: Option.Option): string => Option.match(owner, { onNone: () => - "Another T3 Code server, such as the background service, is using this data directory, or an older background service is set up for it. Stop that server or try `t3 update`. If the older launcher cannot update, run `t3 service uninstall` and optionally reinstall with `t3 service install` from a current CLI. Use `npx t3@latest` if `t3` is missing or outdated, and pass `--base-dir` with the service's T3 home to each command. Then reopen T3 Code. You can also set a separate T3CODE_HOME and pair with the running server.", + m( + msg( + "Another T3 Code server, such as the background service, is using this data directory, or an older background service is set up for it. Stop that server or try `t3 update`. If the older launcher cannot update, run `t3 service uninstall` and optionally reinstall with `t3 service install` from a current CLI. Use `npx t3@latest` if `t3` is missing or outdated, and pass `--base-dir` with the service's T3 home to each command. Then reopen T3 Code. You can also set a separate T3CODE_HOME and pair with the running server.", + ), + ), onSome: (owner) => { - const kind = owner.serviceManaged - ? "The T3 Code background service" - : "Another T3 Code server (for example `t3 serve`, or one started over SSH)"; - const version = owner.serverVersion ? `, version ${owner.serverVersion}` : ""; - const stop = owner.serviceManaged - ? "Stop it with `t3 service uninstall`, passing `--base-dir` with this T3 home" - : "If a T3 Code app on another machine started it over SSH, that app restarts it: remove or disconnect that SSH environment there, or quit that app. Then stop the server"; - return `${kind} is using this T3 home (PID ${owner.pid}, port ${owner.port}${version}). ${stop}, and reopen T3 Code. You can also set a separate T3CODE_HOME and pair with the running server.`; + const variables = { + pid: String(owner.pid), + port: String(owner.port), + version: owner.serverVersion ?? "", + }; + if (owner.serviceManaged) { + return owner.serverVersion + ? m( + msg( + "The T3 Code background service is using this T3 home (PID {pid}, port {port}, version {version}). Stop it with `t3 service uninstall`, passing `--base-dir` with this T3 home, and reopen T3 Code. You can also set a separate T3CODE_HOME and pair with the running server.", + ), + variables, + ) + : m( + msg( + "The T3 Code background service is using this T3 home (PID {pid}, port {port}). Stop it with `t3 service uninstall`, passing `--base-dir` with this T3 home, and reopen T3 Code. You can also set a separate T3CODE_HOME and pair with the running server.", + ), + variables, + ); + } + return owner.serverVersion + ? m( + msg( + "Another T3 Code server (for example `t3 serve`, or one started over SSH) is using this T3 home (PID {pid}, port {port}, version {version}). If a T3 Code app on another machine started it over SSH, that app restarts it: remove or disconnect that SSH environment there, or quit that app. Then stop the server, and reopen T3 Code. You can also set a separate T3CODE_HOME and pair with the running server.", + ), + variables, + ) + : m( + msg( + "Another T3 Code server (for example `t3 serve`, or one started over SSH) is using this T3 home (PID {pid}, port {port}). If a T3 Code app on another machine started it over SSH, that app restarts it: remove or disconnect that SSH environment there, or quit that app. Then stop the server, and reopen T3 Code. You can also set a separate T3CODE_HOME and pair with the running server.", + ), + variables, + ); }, }); diff --git a/apps/desktop/src/i18n/messages.ts b/apps/desktop/src/i18n/messages.ts new file mode 100644 index 000000000000..72fe7487796c --- /dev/null +++ b/apps/desktop/src/i18n/messages.ts @@ -0,0 +1,83 @@ +import { resolveLocale } from "@t3tools/client-runtime/locales"; +import * as Effect from "effect/Effect"; +import { decodeOptions, gtFallback } from "gt-i18n"; +import { hashMessage } from "gt-i18n/internal"; + +import * as ElectronApp from "../electron/ElectronApp.ts"; + +type Catalog = Readonly>; + +const DEFAULT_LOCALE = "en"; + +// English is the source text and loads nothing. Keep the keys in step with gt.config.json. +const CATALOGS: Readonly Promise<{ readonly default: Catalog }>>> = { + de: () => import("./translations/de.json", { with: { type: "json" } }), + es: () => import("./translations/es.json", { with: { type: "json" } }), + fr: () => import("./translations/fr.json", { with: { type: "json" } }), + ja: () => import("./translations/ja.json", { with: { type: "json" } }), + ko: () => import("./translations/ko.json", { with: { type: "json" } }), + "pt-BR": () => import("./translations/pt-BR.json", { with: { type: "json" } }), + ru: () => import("./translations/ru.json", { with: { type: "json" } }), + sv: () => import("./translations/sv.json", { with: { type: "json" } }), + zh: () => import("./translations/zh.json", { with: { type: "json" } }), +}; +const SUPPORTED_LOCALES = [DEFAULT_LOCALE, ...Object.keys(CATALOGS)]; + +const loadedCatalogs = new Map([[DEFAULT_LOCALE, {}]]); +const listeners = new Set<() => void>(); +let activeLocale = DEFAULT_LOCALE; +let activeCatalog: Catalog = {}; +let requestedLocale = DEFAULT_LOCALE; + +/** + * Resolves a `msg()` string in the active UI language at call time. Variables are strings so + * ICU never reformats a number (a PID of 12345 would print "12,345"). + */ +export function m(message: string, variables: Readonly> = {}): string { + const decoded = decodeOptions(message); + const source = typeof decoded?.$_source === "string" ? decoded.$_source : message; + const options = typeof decoded?.$_source === "string" ? decoded : variables; + const target = + activeLocale === DEFAULT_LOCALE + ? undefined + : activeCatalog[hashMessage(source, { ...options, $format: "ICU" })]; + // Untranslated text is English, so it takes English plural rules. + return target === undefined + ? gtFallback(source, { ...options, $locale: DEFAULT_LOCALE }) + : gtFallback(target, { ...options, $locale: activeLocale, $_fallback: source }); +} + +/** Runs `listener` after each switch to a different UI language. */ +export function onLocaleChange(listener: () => void): () => void { + listeners.add(listener); + return () => { + listeners.delete(listener); + }; +} + +const loadCatalog = async (locale: string): Promise => { + const loaded = loadedCatalogs.get(locale); + if (loaded) return loaded; + const catalog = (await CATALOGS[locale]!()).default; + loadedCatalogs.set(locale, catalog); + return catalog; +}; + +/** Activates the saved `language` client setting; "system" follows the OS language order. */ +export const applyLanguage = Effect.fn("desktop.i18n.applyLanguage")(function* (language: string) { + const electronApp = yield* ElectronApp.ElectronApp; + const locale = resolveLocale( + language, + yield* electronApp.preferredSystemLanguages, + SUPPORTED_LOCALES, + DEFAULT_LOCALE, + ); + requestedLocale = locale; + if (locale === activeLocale) return; + const catalog = yield* Effect.promise(() => loadCatalog(locale)); + // A later call may have asked for another language while this catalog loaded. + if (requestedLocale !== locale) return; + activeLocale = locale; + activeCatalog = catalog; + for (const listener of listeners) listener(); +}); diff --git a/apps/desktop/src/i18n/translations/de.json b/apps/desktop/src/i18n/translations/de.json new file mode 100644 index 000000000000..bd128da18cd1 --- /dev/null +++ b/apps/desktop/src/i18n/translations/de.json @@ -0,0 +1,103 @@ +{ + "743bb98558dcdddf": "T3 Code konnte nicht gestartet werden", + "45e444e807bececb": "Dieses T3-Home ist nicht verfügbar", + "97665653aa9129ad": "Nach einer neueren Version wird gesucht…", + "dce25e68e60eb512": "Version {version} ist verfügbar. Sie enthält möglicherweise eine Korrektur.", + "2f015e6d5459dce9": "Auf {version} aktualisieren", + "ca9838012a0eb084": "{version} wird heruntergeladen. T3 Code startet neu, wenn der Download fertig ist.", + "c38cbed9acc5b0d1": "{version} wird heruntergeladen ({percent} %). T3 Code startet neu, wenn der Download fertig ist.", + "4b4cf6843a4e0aba": "Version {version} lief auf diesem Computer korrekt. Lade sie herunter und installiere sie, um zurückzuwechseln.", + "b57c6134d74c0848": "{version} herunterladen", + "1eeed583c2254507": "Hol dir eine andere Version von der Release-Seite.", + "4cd5b64eeb26e1ee": "Releases öffnen", + "7e21da2485a8e0bb": "Die verwaltete Richtlinie deiner Organisation hat den Start von T3 Code verhindert. Sende die folgenden Details an deinen IT-Administrator.", + "55a19ca527948aaa": "T3 Code konnte nicht starten", + "4825d2a18a5fc093": "Details kopieren", + "3874c9f538653a6d": "Beenden", + "0eec8b51246f5e2c": "Der Server hat keine Ausgabe geschrieben.", + "6cb1b68bddf39b35": "Version {version}. T3 Code versucht es im Hintergrund erneut. Logs: {logDir}", + "895f988b9de16f88": "Das WSL-Backend ist weiterhin nicht verfügbar", + "eeb7ea62dc4706c1": "T3 Code verwendet für diesen Start das Windows-Backend und versucht es beim nächsten App-Start erneut mit WSL.", + "b5435aa5b470bafd": "Das WSL-Backend konnte nicht starten", + "d82d7c96e1904629": "Es wird auf das Windows-Backend ausgewichen, damit T3 Code sich öffnen kann. Aktiviere das WSL-Backend unter Einstellungen > Freigabe & Zugriff wieder, sobald die WSL-Distribution repariert ist.", + "a4acf18834787a4f": "Ein anderer T3-Code-Server, etwa der Hintergrunddienst, verwendet dieses Datenverzeichnis, oder ein älterer Hintergrunddienst ist dafür eingerichtet. Stoppe diesen Server oder versuche `t3 update`. Wenn der ältere Launcher sich nicht aktualisieren kann, führe `t3 service uninstall` aus und installiere ihn optional mit `t3 service install` aus einer aktuellen CLI neu. Verwende `npx t3@latest`, wenn `t3` fehlt oder veraltet ist, und übergib jedem Befehl `--base-dir` mit dem T3-Home des Dienstes. Öffne T3 Code dann erneut. Du kannst auch ein separates T3CODE_HOME setzen und mit dem laufenden Server koppeln.", + "0e306130a55a3954": "Der T3-Code-Hintergrunddienst verwendet dieses T3-Home (PID {pid}, Port {port}, Version {version}). Stoppe ihn mit `t3 service uninstall` und übergib dabei `--base-dir` mit diesem T3-Home, und öffne T3 Code dann erneut. Du kannst auch ein separates T3CODE_HOME setzen und mit dem laufenden Server koppeln.", + "7379a43c1ac009d2": "Der T3-Code-Hintergrunddienst verwendet dieses T3-Home (PID {pid}, Port {port}). Stoppe ihn mit `t3 service uninstall` und übergib dabei `--base-dir` mit diesem T3-Home, und öffne T3 Code dann erneut. Du kannst auch ein separates T3CODE_HOME setzen und mit dem laufenden Server koppeln.", + "1510c6547cde9c2e": "Ein anderer T3-Code-Server (zum Beispiel `t3 serve` oder einer, der über SSH gestartet wurde) verwendet dieses T3-Home (PID {pid}, Port {port}, Version {version}). Wenn eine T3-Code-App auf einem anderen Rechner ihn über SSH gestartet hat, startet diese App ihn neu: Entferne oder trenne dort diese SSH-Umgebung oder beende diese App. Stoppe dann den Server und öffne T3 Code erneut. Du kannst auch ein separates T3CODE_HOME setzen und mit dem laufenden Server koppeln.", + "8d8628520de0d9f1": "Ein anderer T3-Code-Server (zum Beispiel `t3 serve` oder einer, der über SSH gestartet wurde) verwendet dieses T3-Home (PID {pid}, Port {port}). Wenn eine T3-Code-App auf einem anderen Rechner ihn über SSH gestartet hat, startet diese App ihn neu: Entferne oder trenne dort diese SSH-Umgebung oder beende diese App. Stoppe dann den Server und öffne T3 Code erneut. Du kannst auch ein separates T3CODE_HOME setzen und mit dem laufenden Server koppeln.", + "6574442caf8bfd15": "Bildschirmaufnahme einrichten", + "a8210440c691b062": "Bedienungshilfen einrichten", + "0cbbbd8abd25f9d4": "Festplattenvollzugriff einrichten", + "4cd679200c978949": "Berechtigungshilfe schließen", + "ea4f056c8f6b5c15": "↑ Ziehe T3 Code in die Liste oben", + "4bcb0f4db00936b1": "Ziehe T3 Code in die Systemeinstellungen oder klicke, um es im Finder anzuzeigen", + "278648c9ff6fb9ce": "Keine vertrauenswürdige Stelle hat dieses Zertifikat ausgestellt.", + "cf346dcfb658d4d3": "Dieses Zertifikat gilt nicht für diese Adresse.", + "20665d9b0c7c3e52": "Dieses Zertifikat ist abgelaufen oder noch nicht gültig.", + "565970a378986341": "Öffnen", + "00ad8aeed0a6c461": "Abbrechen", + "2107cc3e7c4ac833": "Diesen {protocol}-Link öffnen?", + "050db36de6624203": "Eine Seite im Browser möchte eine andere Anwendung öffnen:\n\n{url}", + "c1d7515ac0214ca1": "Vertrauen und merken", + "e89b5b30b1bc99bb": "{host} hat ein nicht vertrauenswürdiges Zertifikat", + "16d4c8a1431bd8c2": "Ausgestellt für: {name}", + "5862c92e2dabefab": "Ausgestellt von: {name}", + "cf559f06dc2e5432": "Gültig: {start} – {end}", + "86fe6451f52e722a": "Fingerabdruck: {fingerprint}", + "7b20c92539acb4b6": "Vertraue ihm nur, wenn du weißt, dass dieses Zertifikat zur Website gehört. Beim Löschen der Cookies dieses Browserprofils wird es vergessen.", + "c67ec08c2c8d0cd9": "Dem Zertifikat für {host} konnte nicht vertraut werden", + "935a340963533dcf": "T3 Code konnte diese Genehmigung nicht speichern, daher bleibt die Seite blockiert. Prüfe, ob die Festplatte voll ist und ob ihr Datenordner beschreibbar ist, und versuche es dann erneut.", + "a0315d43e8e5be7e": "Erlauben", + "2ec823ca24387055": "Blockieren", + "8fc0b116123fb50b": "{origin} möchte in die Zwischenablage kopierte Texte und Bilder sehen", + "c0f756221736393f": "Vorschau · {title}", + "6994444f4fec4070": "Browservorschau", + "49de6209699eb616": "Unbenannter Passkey", + "b4a5bb1075d95154": "Passkey auswählen", + "1f12213f4d809e89": "Du bist auf dem neuesten Stand!", + "c6399b55619e2f67": "T3 Code {version} ist derzeit die neueste verfügbare Version.", + "b6e5b31255e011c5": "OK", + "2ee2077700686fbb": "Update verfügbar", + "d3104b65052b993b": "Eine neue Version von T3 Code ist verfügbar.", + "35fff5a1cd1d6473": "T3 Code {version} ist verfügbar.", + "63fbea040532a9ab": "Du verwendest T3 Code {version}.", + "374b1cb8cb616d27": "Herunterladen", + "b0d022fe9d78def7": "Später", + "b9a0301ee1348da9": "Update wird heruntergeladen", + "bbaf6039d665a7a7": "Eine neue Version von T3 Code wird bereits heruntergeladen.", + "27b49ef7007c126d": "T3 Code {version} wird bereits heruntergeladen.", + "bd6818c7f005654c": "Update bereit", + "e0e13c85665bd62f": "Eine neue Version von T3 Code ist bereit zur Installation.", + "dfe6e415877b0533": "T3 Code {version} ist bereit zur Installation.", + "d1d10979d6dcb162": "T3 Code startet zur Installation neu. Laufende Aufgaben werden unterbrochen.", + "2f0a8211a72e29aa": "Neu starten", + "116a21f6cc215e5f": "Suche nach Updates fehlgeschlagen", + "32c88cd9421abf33": "Es konnte nicht nach Updates gesucht werden.", + "b37aca07d3c644d9": "Ein unbekannter Fehler ist aufgetreten. Bitte versuche es später erneut.", + "c8c23435e780a60c": "Updates nicht verfügbar", + "aecf7c98b81bef7a": "Automatische Updates sind derzeit nicht verfügbar.", + "835247f842c92bc9": "Über {appName}", + "959e09151d75e25b": "Nach Updates suchen...", + "0c753e71e2dca0d0": "Einstellungen...", + "a9fad846cd549d96": "{appName} ausblenden", + "4b375f39bfce229e": "{appName} beenden", + "83506e64878b7b48": "Datei", + "b1f24efbd4e80225": "Entwicklertools schließen", + "2c85ee66be8b81b5": "Fenster schließen", + "31bfa0ca146dc77f": "Bearbeiten", + "ebf150404ed417d5": "Als Text einfügen", + "660715835d05ddca": "Sprachausgabe", + "25994350fd047a38": "Ansicht", + "573a9e6b17f4e9e3": "Neu laden", + "826cb3059ebc7cc3": "Neu laden erzwingen", + "8340487d05e832e8": "Entwicklertools ein-/ausblenden", + "a7ab66e786347118": "Originalgröße", + "a4ad1b27fdc9032d": "Vergrößern", + "df6ed2014f1737a8": "Verkleinern", + "953979a4737f48fa": "Keine Vorschläge", + "202e13f15a3dcd30": "Link kopieren", + "8af79268f2349f4c": "E-Mail-Adresse kopieren", + "a9f9254d458e49fe": "Bild kopieren", + "9c1b20fbc881de5d": "Desktop-Konfiguration", + "1b14230874f19eb9": "Bilder" +} diff --git a/apps/desktop/src/i18n/translations/en.json b/apps/desktop/src/i18n/translations/en.json new file mode 100644 index 000000000000..ad77a1a07a9a --- /dev/null +++ b/apps/desktop/src/i18n/translations/en.json @@ -0,0 +1,103 @@ +{ + "743bb98558dcdddf": "T3 Code failed to start", + "45e444e807bececb": "This T3 home is unavailable", + "97665653aa9129ad": "Checking for a newer version…", + "dce25e68e60eb512": "Version {version} is available. It can contain a fix.", + "2f015e6d5459dce9": "Update to {version}", + "ca9838012a0eb084": "Downloading {version}. T3 Code restarts when the download is done.", + "c38cbed9acc5b0d1": "Downloading {version} ({percent}%). T3 Code restarts when the download is done.", + "4b4cf6843a4e0aba": "Version {version} started correctly on this computer. Download it and install it to go back.", + "b57c6134d74c0848": "Download {version}", + "1eeed583c2254507": "Get a different version from the releases page.", + "4cd5b64eeb26e1ee": "Open releases", + "7e21da2485a8e0bb": "Your organization's managed policy stopped T3 Code from starting. Send the details below to your IT administrator.", + "55a19ca527948aaa": "T3 Code could not start", + "4825d2a18a5fc093": "Copy details", + "3874c9f538653a6d": "Quit", + "0eec8b51246f5e2c": "The server wrote no output.", + "6cb1b68bddf39b35": "Version {version}. T3 Code tries again in the background. Logs: {logDir}", + "895f988b9de16f88": "WSL backend is still unavailable", + "eeb7ea62dc4706c1": "T3 Code will use the Windows backend for this launch and retry WSL the next time the app starts.", + "b5435aa5b470bafd": "WSL backend couldn't start", + "d82d7c96e1904629": "Falling back to the Windows backend so T3 Code can open. Re-enable the WSL backend from Settings > Sharing & access once the WSL distro is fixed.", + "a4acf18834787a4f": "Another T3 Code server, such as the background service, is using this data directory, or an older background service is set up for it. Stop that server or try `t3 update`. If the older launcher cannot update, run `t3 service uninstall` and optionally reinstall with `t3 service install` from a current CLI. Use `npx t3@latest` if `t3` is missing or outdated, and pass `--base-dir` with the service's T3 home to each command. Then reopen T3 Code. You can also set a separate T3CODE_HOME and pair with the running server.", + "0e306130a55a3954": "The T3 Code background service is using this T3 home (PID {pid}, port {port}, version {version}). Stop it with `t3 service uninstall`, passing `--base-dir` with this T3 home, and reopen T3 Code. You can also set a separate T3CODE_HOME and pair with the running server.", + "7379a43c1ac009d2": "The T3 Code background service is using this T3 home (PID {pid}, port {port}). Stop it with `t3 service uninstall`, passing `--base-dir` with this T3 home, and reopen T3 Code. You can also set a separate T3CODE_HOME and pair with the running server.", + "1510c6547cde9c2e": "Another T3 Code server (for example `t3 serve`, or one started over SSH) is using this T3 home (PID {pid}, port {port}, version {version}). If a T3 Code app on another machine started it over SSH, that app restarts it: remove or disconnect that SSH environment there, or quit that app. Then stop the server, and reopen T3 Code. You can also set a separate T3CODE_HOME and pair with the running server.", + "8d8628520de0d9f1": "Another T3 Code server (for example `t3 serve`, or one started over SSH) is using this T3 home (PID {pid}, port {port}). If a T3 Code app on another machine started it over SSH, that app restarts it: remove or disconnect that SSH environment there, or quit that app. Then stop the server, and reopen T3 Code. You can also set a separate T3CODE_HOME and pair with the running server.", + "6574442caf8bfd15": "Set up Screen Recording", + "a8210440c691b062": "Set up Accessibility", + "0cbbbd8abd25f9d4": "Set up Full Disk Access", + "4cd679200c978949": "Close permission helper", + "ea4f056c8f6b5c15": "↑ Drag T3 Code into the list above", + "4bcb0f4db00936b1": "Drag T3 Code to System Settings, or click to reveal in Finder", + "278648c9ff6fb9ce": "No trusted authority issued this certificate.", + "cf346dcfb658d4d3": "This certificate is not for this address.", + "20665d9b0c7c3e52": "This certificate has expired or is not valid yet.", + "565970a378986341": "Open", + "00ad8aeed0a6c461": "Cancel", + "2107cc3e7c4ac833": "Open this {protocol} link?", + "050db36de6624203": "A page in the browser wants to open another application:\n\n{url}", + "c1d7515ac0214ca1": "Trust and Remember", + "e89b5b30b1bc99bb": "{host} has an untrusted certificate", + "16d4c8a1431bd8c2": "Issued to: {name}", + "5862c92e2dabefab": "Issued by: {name}", + "cf559f06dc2e5432": "Valid: {start} – {end}", + "86fe6451f52e722a": "Fingerprint: {fingerprint}", + "7b20c92539acb4b6": "Trust it only if you know this certificate belongs to the site. Clearing this browser profile's cookies forgets it.", + "c67ec08c2c8d0cd9": "Could not trust the certificate for {host}", + "935a340963533dcf": "T3 Code could not save this approval, so the page stays blocked. Check that the disk is not full and its data folder is writable, then try again.", + "a0315d43e8e5be7e": "Allow", + "2ec823ca24387055": "Block", + "8fc0b116123fb50b": "{origin} wants to see text and images copied to the clipboard", + "c0f756221736393f": "Preview · {title}", + "6994444f4fec4070": "Browser preview", + "49de6209699eb616": "Unnamed passkey", + "b4a5bb1075d95154": "Choose a passkey", + "1f12213f4d809e89": "You're up to date!", + "c6399b55619e2f67": "T3 Code {version} is currently the newest version available.", + "b6e5b31255e011c5": "OK", + "2ee2077700686fbb": "Update available", + "d3104b65052b993b": "A new version of T3 Code is available.", + "35fff5a1cd1d6473": "T3 Code {version} is available.", + "63fbea040532a9ab": "You're running T3 Code {version}.", + "374b1cb8cb616d27": "Download", + "b0d022fe9d78def7": "Later", + "b9a0301ee1348da9": "Update downloading", + "bbaf6039d665a7a7": "A new version of T3 Code is already downloading.", + "27b49ef7007c126d": "T3 Code {version} is already downloading.", + "bd6818c7f005654c": "Update ready", + "e0e13c85665bd62f": "A new version of T3 Code is ready to install.", + "dfe6e415877b0533": "T3 Code {version} is ready to install.", + "d1d10979d6dcb162": "T3 Code will restart to install it. Any running tasks will be interrupted.", + "2f0a8211a72e29aa": "Restart", + "116a21f6cc215e5f": "Update check failed", + "32c88cd9421abf33": "Could not check for updates.", + "b37aca07d3c644d9": "An unknown error occurred. Please try again later.", + "c8c23435e780a60c": "Updates unavailable", + "aecf7c98b81bef7a": "Automatic updates are not available right now.", + "835247f842c92bc9": "About {appName}", + "959e09151d75e25b": "Check for Updates...", + "0c753e71e2dca0d0": "Settings...", + "a9fad846cd549d96": "Hide {appName}", + "4b375f39bfce229e": "Quit {appName}", + "83506e64878b7b48": "File", + "b1f24efbd4e80225": "Close Developer Tools", + "2c85ee66be8b81b5": "Close Window", + "31bfa0ca146dc77f": "Edit", + "ebf150404ed417d5": "Paste as Text", + "660715835d05ddca": "Speech", + "25994350fd047a38": "View", + "573a9e6b17f4e9e3": "Reload", + "826cb3059ebc7cc3": "Force Reload", + "8340487d05e832e8": "Toggle Developer Tools", + "a7ab66e786347118": "Actual Size", + "a4ad1b27fdc9032d": "Zoom In", + "df6ed2014f1737a8": "Zoom Out", + "953979a4737f48fa": "No suggestions", + "202e13f15a3dcd30": "Copy Link", + "8af79268f2349f4c": "Copy Email Address", + "a9f9254d458e49fe": "Copy Image", + "9c1b20fbc881de5d": "Desktop config", + "1b14230874f19eb9": "Images" +} diff --git a/apps/desktop/src/i18n/translations/es.json b/apps/desktop/src/i18n/translations/es.json new file mode 100644 index 000000000000..0b3243ebe918 --- /dev/null +++ b/apps/desktop/src/i18n/translations/es.json @@ -0,0 +1,103 @@ +{ + "743bb98558dcdddf": "T3 Code no pudo iniciarse", + "45e444e807bececb": "Este directorio de T3 no está disponible", + "97665653aa9129ad": "Buscando una versión más reciente…", + "dce25e68e60eb512": "La versión {version} está disponible. Puede incluir una corrección.", + "2f015e6d5459dce9": "Actualizar a {version}", + "ca9838012a0eb084": "Descargando {version}. T3 Code se reiniciará cuando termine la descarga.", + "c38cbed9acc5b0d1": "Descargando {version} ({percent} %). T3 Code se reiniciará cuando termine la descarga.", + "4b4cf6843a4e0aba": "La versión {version} se inició correctamente en este ordenador. Descárgala e instálala para volver a ella.", + "b57c6134d74c0848": "Descargar {version}", + "1eeed583c2254507": "Consigue otra versión en la página de versiones.", + "4cd5b64eeb26e1ee": "Abrir versiones", + "7e21da2485a8e0bb": "La política gestionada de tu organización impidió que T3 Code se iniciara. Envía los detalles de abajo a tu administrador de TI.", + "55a19ca527948aaa": "T3 Code no pudo iniciarse", + "4825d2a18a5fc093": "Copiar detalles", + "3874c9f538653a6d": "Salir", + "0eec8b51246f5e2c": "El servidor no escribió ninguna salida.", + "6cb1b68bddf39b35": "Versión {version}. T3 Code lo vuelve a intentar en segundo plano. Registros: {logDir}", + "895f988b9de16f88": "El backend de WSL sigue sin estar disponible", + "eeb7ea62dc4706c1": "T3 Code usará el backend de Windows en este inicio y volverá a intentar WSL la próxima vez que se abra la app.", + "b5435aa5b470bafd": "No se pudo iniciar el backend de WSL", + "d82d7c96e1904629": "Se usa el backend de Windows para que T3 Code pueda abrirse. Vuelve a activar el backend de WSL en Ajustes > Compartir y acceso cuando la distro de WSL esté arreglada.", + "a4acf18834787a4f": "Otro servidor de T3 Code, como el servicio en segundo plano, está usando este directorio de datos, o hay configurado un servicio en segundo plano antiguo para él. Detén ese servidor o prueba `t3 update`. Si el lanzador antiguo no puede actualizarse, ejecuta `t3 service uninstall` y, si quieres, reinstálalo con `t3 service install` desde una CLI actual. Usa `npx t3@latest` si falta `t3` o está desactualizado, y pasa `--base-dir` con el directorio de T3 del servicio a cada comando. Después vuelve a abrir T3 Code. También puedes definir otro T3CODE_HOME y emparejarte con el servidor en ejecución.", + "0e306130a55a3954": "El servicio en segundo plano de T3 Code está usando este directorio de T3 (PID {pid}, puerto {port}, versión {version}). Detenlo con `t3 service uninstall`, pasando `--base-dir` con este directorio de T3, y vuelve a abrir T3 Code. También puedes definir otro T3CODE_HOME y emparejarte con el servidor en ejecución.", + "7379a43c1ac009d2": "El servicio en segundo plano de T3 Code está usando este directorio de T3 (PID {pid}, puerto {port}). Detenlo con `t3 service uninstall`, pasando `--base-dir` con este directorio de T3, y vuelve a abrir T3 Code. También puedes definir otro T3CODE_HOME y emparejarte con el servidor en ejecución.", + "1510c6547cde9c2e": "Otro servidor de T3 Code (por ejemplo, `t3 serve` o uno iniciado por SSH) está usando este directorio de T3 (PID {pid}, puerto {port}, versión {version}). Si lo inició por SSH una app de T3 Code en otra máquina, esa app lo reinicia: quita o desconecta allí ese entorno SSH, o cierra esa app. Después detén el servidor y vuelve a abrir T3 Code. También puedes definir otro T3CODE_HOME y emparejarte con el servidor en ejecución.", + "8d8628520de0d9f1": "Otro servidor de T3 Code (por ejemplo, `t3 serve` o uno iniciado por SSH) está usando este directorio de T3 (PID {pid}, puerto {port}). Si lo inició por SSH una app de T3 Code en otra máquina, esa app lo reinicia: quita o desconecta allí ese entorno SSH, o cierra esa app. Después detén el servidor y vuelve a abrir T3 Code. También puedes definir otro T3CODE_HOME y emparejarte con el servidor en ejecución.", + "6574442caf8bfd15": "Configurar Grabación de pantalla", + "a8210440c691b062": "Configurar Accesibilidad", + "0cbbbd8abd25f9d4": "Configurar Acceso total al disco", + "4cd679200c978949": "Cerrar el asistente de permisos", + "ea4f056c8f6b5c15": "↑ Arrastra T3 Code a la lista de arriba", + "4bcb0f4db00936b1": "Arrastra T3 Code a Ajustes del Sistema o haz clic para mostrarlo en el Finder", + "278648c9ff6fb9ce": "Ninguna autoridad de confianza emitió este certificado.", + "cf346dcfb658d4d3": "Este certificado no es para esta dirección.", + "20665d9b0c7c3e52": "Este certificado ha caducado o aún no es válido.", + "565970a378986341": "Abrir", + "00ad8aeed0a6c461": "Cancelar", + "2107cc3e7c4ac833": "¿Abrir este enlace {protocol}?", + "050db36de6624203": "Una página del navegador quiere abrir otra aplicación:\n\n{url}", + "c1d7515ac0214ca1": "Confiar y recordar", + "e89b5b30b1bc99bb": "{host} tiene un certificado que no es de confianza", + "16d4c8a1431bd8c2": "Emitido para: {name}", + "5862c92e2dabefab": "Emitido por: {name}", + "cf559f06dc2e5432": "Válido: {start} – {end}", + "86fe6451f52e722a": "Huella digital: {fingerprint}", + "7b20c92539acb4b6": "Confía en él solo si sabes que este certificado pertenece al sitio. Al borrar las cookies de este perfil del navegador se olvida.", + "c67ec08c2c8d0cd9": "No se pudo confiar en el certificado de {host}", + "935a340963533dcf": "T3 Code no pudo guardar esta aprobación, así que la página sigue bloqueada. Comprueba que el disco no está lleno y que se puede escribir en su carpeta de datos y vuelve a intentarlo.", + "a0315d43e8e5be7e": "Permitir", + "2ec823ca24387055": "Bloquear", + "8fc0b116123fb50b": "{origin} quiere ver el texto y las imágenes copiados al portapapeles", + "c0f756221736393f": "Vista previa · {title}", + "6994444f4fec4070": "Vista previa del navegador", + "49de6209699eb616": "Llave de acceso sin nombre", + "b4a5bb1075d95154": "Elige una llave de acceso", + "1f12213f4d809e89": "¡Estás al día!", + "c6399b55619e2f67": "T3 Code {version} es la versión más reciente disponible.", + "b6e5b31255e011c5": "Aceptar", + "2ee2077700686fbb": "Actualización disponible", + "d3104b65052b993b": "Hay una nueva versión de T3 Code disponible.", + "35fff5a1cd1d6473": "T3 Code {version} está disponible.", + "63fbea040532a9ab": "Estás usando T3 Code {version}.", + "374b1cb8cb616d27": "Descargar", + "b0d022fe9d78def7": "Más tarde", + "b9a0301ee1348da9": "Descargando actualización", + "bbaf6039d665a7a7": "Ya se está descargando una nueva versión de T3 Code.", + "27b49ef7007c126d": "Ya se está descargando T3 Code {version}.", + "bd6818c7f005654c": "Actualización lista", + "e0e13c85665bd62f": "Una nueva versión de T3 Code está lista para instalarse.", + "dfe6e415877b0533": "T3 Code {version} está listo para instalarse.", + "d1d10979d6dcb162": "T3 Code se reiniciará para instalarla. Las tareas en ejecución se interrumpirán.", + "2f0a8211a72e29aa": "Reiniciar", + "116a21f6cc215e5f": "Error al buscar actualizaciones", + "32c88cd9421abf33": "No se pudo buscar actualizaciones.", + "b37aca07d3c644d9": "Se produjo un error desconocido. Vuelve a intentarlo más tarde.", + "c8c23435e780a60c": "Actualizaciones no disponibles", + "aecf7c98b81bef7a": "Las actualizaciones automáticas no están disponibles ahora mismo.", + "835247f842c92bc9": "Acerca de {appName}", + "959e09151d75e25b": "Buscar actualizaciones...", + "0c753e71e2dca0d0": "Ajustes...", + "a9fad846cd549d96": "Ocultar {appName}", + "4b375f39bfce229e": "Salir de {appName}", + "83506e64878b7b48": "Archivo", + "b1f24efbd4e80225": "Cerrar las herramientas de desarrollo", + "2c85ee66be8b81b5": "Cerrar ventana", + "31bfa0ca146dc77f": "Edición", + "ebf150404ed417d5": "Pegar como texto", + "660715835d05ddca": "Voz", + "25994350fd047a38": "Ver", + "573a9e6b17f4e9e3": "Recargar", + "826cb3059ebc7cc3": "Forzar recarga", + "8340487d05e832e8": "Mostrar u ocultar las herramientas de desarrollo", + "a7ab66e786347118": "Tamaño real", + "a4ad1b27fdc9032d": "Acercar", + "df6ed2014f1737a8": "Alejar", + "953979a4737f48fa": "Sin sugerencias", + "202e13f15a3dcd30": "Copiar enlace", + "8af79268f2349f4c": "Copiar dirección de correo", + "a9f9254d458e49fe": "Copiar imagen", + "9c1b20fbc881de5d": "Configuración de escritorio", + "1b14230874f19eb9": "Imágenes" +} diff --git a/apps/desktop/src/i18n/translations/fr.json b/apps/desktop/src/i18n/translations/fr.json new file mode 100644 index 000000000000..a0dcf1bd13ac --- /dev/null +++ b/apps/desktop/src/i18n/translations/fr.json @@ -0,0 +1,103 @@ +{ + "743bb98558dcdddf": "Échec du démarrage de T3 Code", + "45e444e807bececb": "Ce home T3 n’est pas disponible", + "97665653aa9129ad": "Recherche d’une version plus récente…", + "dce25e68e60eb512": "La version {version} est disponible. Elle peut contenir un correctif.", + "2f015e6d5459dce9": "Mettre à jour vers {version}", + "ca9838012a0eb084": "Téléchargement de {version}. T3 Code redémarrera une fois le téléchargement terminé.", + "c38cbed9acc5b0d1": "Téléchargement de {version} ({percent} %). T3 Code redémarrera une fois le téléchargement terminé.", + "4b4cf6843a4e0aba": "La version {version} a démarré correctement sur cet ordinateur. Téléchargez-la et installez-la pour y revenir.", + "b57c6134d74c0848": "Télécharger {version}", + "1eeed583c2254507": "Obtenez une autre version depuis la page des versions.", + "4cd5b64eeb26e1ee": "Ouvrir les versions", + "7e21da2485a8e0bb": "La politique gérée de votre organisation a empêché T3 Code de démarrer. Envoyez les détails ci-dessous à votre administrateur informatique.", + "55a19ca527948aaa": "T3 Code n’a pas pu démarrer", + "4825d2a18a5fc093": "Copier les détails", + "3874c9f538653a6d": "Quitter", + "0eec8b51246f5e2c": "Le serveur n’a écrit aucune sortie.", + "6cb1b68bddf39b35": "Version {version}. T3 Code réessaie en arrière-plan. Journaux : {logDir}", + "895f988b9de16f88": "Le backend WSL est toujours indisponible", + "eeb7ea62dc4706c1": "T3 Code utilisera le backend Windows pour ce lancement et réessaiera WSL au prochain démarrage de l’app.", + "b5435aa5b470bafd": "Le backend WSL n’a pas pu démarrer", + "d82d7c96e1904629": "Retour au backend Windows pour que T3 Code puisse s’ouvrir. Réactivez le backend WSL depuis Paramètres > Partage et accès une fois la distribution WSL réparée.", + "a4acf18834787a4f": "Un autre serveur T3 Code, comme le service en arrière-plan, utilise ce répertoire de données, ou un ancien service en arrière-plan est configuré pour lui. Arrêtez ce serveur ou essayez `t3 update`. Si l’ancien lanceur ne peut pas se mettre à jour, exécutez `t3 service uninstall` puis, si besoin, réinstallez avec `t3 service install` depuis une CLI à jour. Utilisez `npx t3@latest` si `t3` est absent ou obsolète, et passez `--base-dir` avec le home T3 du service à chaque commande. Rouvrez ensuite T3 Code. Vous pouvez aussi définir un T3CODE_HOME distinct et vous appairer avec le serveur en cours d’exécution.", + "0e306130a55a3954": "Le service en arrière-plan de T3 Code utilise ce home T3 (PID {pid}, port {port}, version {version}). Arrêtez-le avec `t3 service uninstall` en passant `--base-dir` avec ce home T3, puis rouvrez T3 Code. Vous pouvez aussi définir un T3CODE_HOME distinct et vous appairer avec le serveur en cours d’exécution.", + "7379a43c1ac009d2": "Le service en arrière-plan de T3 Code utilise ce home T3 (PID {pid}, port {port}). Arrêtez-le avec `t3 service uninstall` en passant `--base-dir` avec ce home T3, puis rouvrez T3 Code. Vous pouvez aussi définir un T3CODE_HOME distinct et vous appairer avec le serveur en cours d’exécution.", + "1510c6547cde9c2e": "Un autre serveur T3 Code (par exemple `t3 serve`, ou un serveur démarré via SSH) utilise ce home T3 (PID {pid}, port {port}, version {version}). Si une app T3 Code sur une autre machine l’a démarré via SSH, cette app le redémarre : supprimez ou déconnectez-y cet environnement SSH, ou quittez cette app. Arrêtez ensuite le serveur et rouvrez T3 Code. Vous pouvez aussi définir un T3CODE_HOME distinct et vous appairer avec le serveur en cours d’exécution.", + "8d8628520de0d9f1": "Un autre serveur T3 Code (par exemple `t3 serve`, ou un serveur démarré via SSH) utilise ce home T3 (PID {pid}, port {port}). Si une app T3 Code sur une autre machine l’a démarré via SSH, cette app le redémarre : supprimez ou déconnectez-y cet environnement SSH, ou quittez cette app. Arrêtez ensuite le serveur et rouvrez T3 Code. Vous pouvez aussi définir un T3CODE_HOME distinct et vous appairer avec le serveur en cours d’exécution.", + "6574442caf8bfd15": "Configurer l’enregistrement de l’écran", + "a8210440c691b062": "Configurer l’accessibilité", + "0cbbbd8abd25f9d4": "Configurer l’accès complet au disque", + "4cd679200c978949": "Fermer l’assistant d’autorisations", + "ea4f056c8f6b5c15": "↑ Faites glisser T3 Code dans la liste ci-dessus", + "4bcb0f4db00936b1": "Faites glisser T3 Code vers Réglages Système, ou cliquez pour l’afficher dans le Finder", + "278648c9ff6fb9ce": "Aucune autorité de confiance n’a émis ce certificat.", + "cf346dcfb658d4d3": "Ce certificat ne correspond pas à cette adresse.", + "20665d9b0c7c3e52": "Ce certificat a expiré ou n’est pas encore valide.", + "565970a378986341": "Ouvrir", + "00ad8aeed0a6c461": "Annuler", + "2107cc3e7c4ac833": "Ouvrir ce lien {protocol} ?", + "050db36de6624203": "Une page du navigateur veut ouvrir une autre application :\n\n{url}", + "c1d7515ac0214ca1": "Faire confiance et mémoriser", + "e89b5b30b1bc99bb": "{host} a un certificat non fiable", + "16d4c8a1431bd8c2": "Délivré à : {name}", + "5862c92e2dabefab": "Délivré par : {name}", + "cf559f06dc2e5432": "Valide : {start} – {end}", + "86fe6451f52e722a": "Empreinte : {fingerprint}", + "7b20c92539acb4b6": "Faites-lui confiance uniquement si vous savez que ce certificat appartient au site. Effacer les cookies de ce profil de navigateur l’oublie.", + "c67ec08c2c8d0cd9": "Impossible de faire confiance au certificat de {host}", + "935a340963533dcf": "T3 Code n’a pas pu enregistrer cette approbation, la page reste donc bloquée. Vérifiez que le disque n’est pas plein et que son dossier de données est accessible en écriture, puis réessayez.", + "a0315d43e8e5be7e": "Autoriser", + "2ec823ca24387055": "Bloquer", + "8fc0b116123fb50b": "{origin} veut voir le texte et les images copiés dans le presse-papiers", + "c0f756221736393f": "Aperçu · {title}", + "6994444f4fec4070": "Aperçu du navigateur", + "49de6209699eb616": "Clé d’accès sans nom", + "b4a5bb1075d95154": "Choisir une clé d’accès", + "1f12213f4d809e89": "Vous êtes à jour !", + "c6399b55619e2f67": "T3 Code {version} est actuellement la version la plus récente.", + "b6e5b31255e011c5": "OK", + "2ee2077700686fbb": "Mise à jour disponible", + "d3104b65052b993b": "Une nouvelle version de T3 Code est disponible.", + "35fff5a1cd1d6473": "T3 Code {version} est disponible.", + "63fbea040532a9ab": "Vous utilisez T3 Code {version}.", + "374b1cb8cb616d27": "Télécharger", + "b0d022fe9d78def7": "Plus tard", + "b9a0301ee1348da9": "Téléchargement de la mise à jour", + "bbaf6039d665a7a7": "Une nouvelle version de T3 Code est déjà en cours de téléchargement.", + "27b49ef7007c126d": "T3 Code {version} est déjà en cours de téléchargement.", + "bd6818c7f005654c": "Mise à jour prête", + "e0e13c85665bd62f": "Une nouvelle version de T3 Code est prête à être installée.", + "dfe6e415877b0533": "T3 Code {version} est prêt à être installé.", + "d1d10979d6dcb162": "T3 Code va redémarrer pour l’installer. Les tâches en cours seront interrompues.", + "2f0a8211a72e29aa": "Redémarrer", + "116a21f6cc215e5f": "Échec de la recherche de mises à jour", + "32c88cd9421abf33": "Impossible de rechercher des mises à jour.", + "b37aca07d3c644d9": "Une erreur inconnue s’est produite. Veuillez réessayer plus tard.", + "c8c23435e780a60c": "Mises à jour indisponibles", + "aecf7c98b81bef7a": "Les mises à jour automatiques ne sont pas disponibles pour le moment.", + "835247f842c92bc9": "À propos de {appName}", + "959e09151d75e25b": "Rechercher des mises à jour...", + "0c753e71e2dca0d0": "Paramètres...", + "a9fad846cd549d96": "Masquer {appName}", + "4b375f39bfce229e": "Quitter {appName}", + "83506e64878b7b48": "Fichier", + "b1f24efbd4e80225": "Fermer les outils de développement", + "2c85ee66be8b81b5": "Fermer la fenêtre", + "31bfa0ca146dc77f": "Édition", + "ebf150404ed417d5": "Coller en texte brut", + "660715835d05ddca": "Parole", + "25994350fd047a38": "Présentation", + "573a9e6b17f4e9e3": "Recharger", + "826cb3059ebc7cc3": "Forcer le rechargement", + "8340487d05e832e8": "Afficher/masquer les outils de développement", + "a7ab66e786347118": "Taille réelle", + "a4ad1b27fdc9032d": "Zoom avant", + "df6ed2014f1737a8": "Zoom arrière", + "953979a4737f48fa": "Aucune suggestion", + "202e13f15a3dcd30": "Copier le lien", + "8af79268f2349f4c": "Copier l’adresse e-mail", + "a9f9254d458e49fe": "Copier l’image", + "9c1b20fbc881de5d": "Configuration du bureau", + "1b14230874f19eb9": "Images" +} diff --git a/apps/desktop/src/i18n/translations/ja.json b/apps/desktop/src/i18n/translations/ja.json new file mode 100644 index 000000000000..93553bbf1a74 --- /dev/null +++ b/apps/desktop/src/i18n/translations/ja.json @@ -0,0 +1,103 @@ +{ + "743bb98558dcdddf": "T3 Code の起動に失敗しました", + "45e444e807bececb": "この T3 ホームは利用できません", + "97665653aa9129ad": "新しいバージョンを確認しています…", + "dce25e68e60eb512": "バージョン {version} を利用できます。修正が含まれている可能性があります。", + "2f015e6d5459dce9": "{version} に更新", + "ca9838012a0eb084": "{version} をダウンロードしています。ダウンロードが完了すると T3 Code が再起動します。", + "c38cbed9acc5b0d1": "{version} をダウンロードしています ({percent}%)。ダウンロードが完了すると T3 Code が再起動します。", + "4b4cf6843a4e0aba": "バージョン {version} はこのコンピューターで正常に起動しました。元に戻すには、ダウンロードしてインストールしてください。", + "b57c6134d74c0848": "{version} をダウンロード", + "1eeed583c2254507": "リリースページから別のバージョンを入手してください。", + "4cd5b64eeb26e1ee": "リリースを開く", + "7e21da2485a8e0bb": "組織の管理ポリシーにより T3 Code の起動が停止されました。以下の詳細を IT 管理者に送ってください。", + "55a19ca527948aaa": "T3 Code を起動できませんでした", + "4825d2a18a5fc093": "詳細をコピー", + "3874c9f538653a6d": "終了", + "0eec8b51246f5e2c": "サーバーは何も出力しませんでした。", + "6cb1b68bddf39b35": "バージョン {version}。T3 Code はバックグラウンドで再試行します。ログ: {logDir}", + "895f988b9de16f88": "WSL バックエンドはまだ利用できません", + "eeb7ea62dc4706c1": "今回の起動では Windows バックエンドを使用し、次回アプリの起動時に WSL を再試行します。", + "b5435aa5b470bafd": "WSL バックエンドを起動できませんでした", + "d82d7c96e1904629": "T3 Code を開けるように Windows バックエンドに切り替えます。WSL ディストリビューションを修正したら、設定 > 共有とアクセスで WSL バックエンドを再度有効にしてください。", + "a4acf18834787a4f": "バックグラウンドサービスなどの別の T3 Code サーバーがこのデータディレクトリを使用しているか、古いバックグラウンドサービスがこのディレクトリ用に設定されています。そのサーバーを停止するか、`t3 update` を試してください。古いランチャーが更新できない場合は、`t3 service uninstall` を実行し、必要に応じて最新の CLI から `t3 service install` で再インストールしてください。`t3` がない、または古い場合は `npx t3@latest` を使い、各コマンドにサービスの T3 ホームを指定した `--base-dir` を渡してください。その後、T3 Code を開き直してください。別の T3CODE_HOME を設定して、実行中のサーバーとペアリングすることもできます。", + "0e306130a55a3954": "T3 Code のバックグラウンドサービスがこの T3 ホームを使用しています (PID {pid}、ポート {port}、バージョン {version})。この T3 ホームを指定した `--base-dir` を付けて `t3 service uninstall` で停止し、T3 Code を開き直してください。別の T3CODE_HOME を設定して、実行中のサーバーとペアリングすることもできます。", + "7379a43c1ac009d2": "T3 Code のバックグラウンドサービスがこの T3 ホームを使用しています (PID {pid}、ポート {port})。この T3 ホームを指定した `--base-dir` を付けて `t3 service uninstall` で停止し、T3 Code を開き直してください。別の T3CODE_HOME を設定して、実行中のサーバーとペアリングすることもできます。", + "1510c6547cde9c2e": "別の T3 Code サーバー (`t3 serve` や SSH 経由で起動したものなど) がこの T3 ホームを使用しています (PID {pid}、ポート {port}、バージョン {version})。別のマシンの T3 Code アプリが SSH 経由で起動した場合、そのアプリが再起動します。そのアプリで SSH 環境を削除するか切断するか、アプリを終了してください。その後サーバーを停止し、T3 Code を開き直してください。別の T3CODE_HOME を設定して、実行中のサーバーとペアリングすることもできます。", + "8d8628520de0d9f1": "別の T3 Code サーバー (`t3 serve` や SSH 経由で起動したものなど) がこの T3 ホームを使用しています (PID {pid}、ポート {port})。別のマシンの T3 Code アプリが SSH 経由で起動した場合、そのアプリが再起動します。そのアプリで SSH 環境を削除するか切断するか、アプリを終了してください。その後サーバーを停止し、T3 Code を開き直してください。別の T3CODE_HOME を設定して、実行中のサーバーとペアリングすることもできます。", + "6574442caf8bfd15": "画面収録を設定", + "a8210440c691b062": "アクセシビリティを設定", + "0cbbbd8abd25f9d4": "フルディスクアクセスを設定", + "4cd679200c978949": "権限ヘルパーを閉じる", + "ea4f056c8f6b5c15": "↑ T3 Code を上のリストにドラッグしてください", + "4bcb0f4db00936b1": "T3 Code をシステム設定にドラッグするか、クリックして Finder で表示", + "278648c9ff6fb9ce": "この証明書は信頼された認証局によって発行されていません。", + "cf346dcfb658d4d3": "この証明書はこのアドレス用ではありません。", + "20665d9b0c7c3e52": "この証明書は期限切れか、まだ有効になっていません。", + "565970a378986341": "開く", + "00ad8aeed0a6c461": "キャンセル", + "2107cc3e7c4ac833": "この {protocol} リンクを開きますか?", + "050db36de6624203": "ブラウザー内のページが別のアプリケーションを開こうとしています:\n\n{url}", + "c1d7515ac0214ca1": "信頼して記憶", + "e89b5b30b1bc99bb": "{host} の証明書は信頼されていません", + "16d4c8a1431bd8c2": "発行先: {name}", + "5862c92e2dabefab": "発行者: {name}", + "cf559f06dc2e5432": "有効期間: {start} – {end}", + "86fe6451f52e722a": "フィンガープリント: {fingerprint}", + "7b20c92539acb4b6": "この証明書がサイトのものであると確信できる場合にのみ信頼してください。このブラウザープロファイルの Cookie を消去すると、この設定は失われます。", + "c67ec08c2c8d0cd9": "{host} の証明書を信頼できませんでした", + "935a340963533dcf": "T3 Code はこの承認を保存できなかったため、ページはブロックされたままです。ディスクがいっぱいでないこと、データフォルダーに書き込めることを確認してから、もう一度お試しください。", + "a0315d43e8e5be7e": "許可", + "2ec823ca24387055": "ブロック", + "8fc0b116123fb50b": "{origin} がクリップボードにコピーされたテキストと画像の表示を求めています", + "c0f756221736393f": "プレビュー · {title}", + "6994444f4fec4070": "ブラウザープレビュー", + "49de6209699eb616": "名前のないパスキー", + "b4a5bb1075d95154": "パスキーを選択", + "1f12213f4d809e89": "最新の状態です", + "c6399b55619e2f67": "T3 Code {version} が現在利用できる最新バージョンです。", + "b6e5b31255e011c5": "OK", + "2ee2077700686fbb": "更新があります", + "d3104b65052b993b": "T3 Code の新しいバージョンを利用できます。", + "35fff5a1cd1d6473": "T3 Code {version} を利用できます。", + "63fbea040532a9ab": "T3 Code {version} を実行しています。", + "374b1cb8cb616d27": "ダウンロード", + "b0d022fe9d78def7": "後で", + "b9a0301ee1348da9": "更新をダウンロード中", + "bbaf6039d665a7a7": "T3 Code の新しいバージョンはすでにダウンロード中です。", + "27b49ef7007c126d": "T3 Code {version} はすでにダウンロード中です。", + "bd6818c7f005654c": "更新の準備ができました", + "e0e13c85665bd62f": "T3 Code の新しいバージョンをインストールする準備ができました。", + "dfe6e415877b0533": "T3 Code {version} をインストールする準備ができました。", + "d1d10979d6dcb162": "インストールするために T3 Code が再起動します。実行中のタスクは中断されます。", + "2f0a8211a72e29aa": "再起動", + "116a21f6cc215e5f": "更新の確認に失敗しました", + "32c88cd9421abf33": "更新を確認できませんでした。", + "b37aca07d3c644d9": "不明なエラーが発生しました。しばらくしてからもう一度お試しください。", + "c8c23435e780a60c": "更新を利用できません", + "aecf7c98b81bef7a": "現在、自動更新は利用できません。", + "835247f842c92bc9": "{appName} について", + "959e09151d75e25b": "更新を確認...", + "0c753e71e2dca0d0": "設定...", + "a9fad846cd549d96": "{appName} を隠す", + "4b375f39bfce229e": "{appName} を終了", + "83506e64878b7b48": "ファイル", + "b1f24efbd4e80225": "開発者ツールを閉じる", + "2c85ee66be8b81b5": "ウィンドウを閉じる", + "31bfa0ca146dc77f": "編集", + "ebf150404ed417d5": "テキストとして貼り付け", + "660715835d05ddca": "スピーチ", + "25994350fd047a38": "表示", + "573a9e6b17f4e9e3": "再読み込み", + "826cb3059ebc7cc3": "強制再読み込み", + "8340487d05e832e8": "開発者ツールの切り替え", + "a7ab66e786347118": "実際のサイズ", + "a4ad1b27fdc9032d": "拡大", + "df6ed2014f1737a8": "縮小", + "953979a4737f48fa": "候補はありません", + "202e13f15a3dcd30": "リンクをコピー", + "8af79268f2349f4c": "メールアドレスをコピー", + "a9f9254d458e49fe": "画像をコピー", + "9c1b20fbc881de5d": "デスクトップの構成", + "1b14230874f19eb9": "画像" +} diff --git a/apps/desktop/src/i18n/translations/ko.json b/apps/desktop/src/i18n/translations/ko.json new file mode 100644 index 000000000000..aac215f3a63d --- /dev/null +++ b/apps/desktop/src/i18n/translations/ko.json @@ -0,0 +1,103 @@ +{ + "743bb98558dcdddf": "T3 Code를 시작하지 못했습니다", + "45e444e807bececb": "이 T3 홈을 사용할 수 없습니다", + "97665653aa9129ad": "새 버전을 확인하는 중…", + "dce25e68e60eb512": "버전 {version}을(를) 사용할 수 있습니다. 문제가 수정되었을 수 있습니다.", + "2f015e6d5459dce9": "{version}(으)로 업데이트", + "ca9838012a0eb084": "{version}을(를) 다운로드하는 중입니다. 다운로드가 끝나면 T3 Code가 다시 시작됩니다.", + "c38cbed9acc5b0d1": "{version}을(를) 다운로드하는 중입니다({percent}%). 다운로드가 끝나면 T3 Code가 다시 시작됩니다.", + "4b4cf6843a4e0aba": "버전 {version}은(는) 이 컴퓨터에서 정상적으로 시작되었습니다. 되돌아가려면 다운로드하여 설치하세요.", + "b57c6134d74c0848": "{version} 다운로드", + "1eeed583c2254507": "릴리스 페이지에서 다른 버전을 받으세요.", + "4cd5b64eeb26e1ee": "릴리스 열기", + "7e21da2485a8e0bb": "조직의 관리 정책 때문에 T3 Code를 시작하지 못했습니다. 아래 세부 정보를 IT 관리자에게 보내세요.", + "55a19ca527948aaa": "T3 Code를 시작할 수 없습니다", + "4825d2a18a5fc093": "세부 정보 복사", + "3874c9f538653a6d": "종료", + "0eec8b51246f5e2c": "서버가 출력을 남기지 않았습니다.", + "6cb1b68bddf39b35": "버전 {version}. T3 Code가 백그라운드에서 다시 시도합니다. 로그: {logDir}", + "895f988b9de16f88": "WSL 백엔드를 여전히 사용할 수 없습니다", + "eeb7ea62dc4706c1": "이번 실행에서는 T3 Code가 Windows 백엔드를 사용하고, 다음에 앱을 시작할 때 WSL을 다시 시도합니다.", + "b5435aa5b470bafd": "WSL 백엔드를 시작할 수 없습니다", + "d82d7c96e1904629": "T3 Code를 열 수 있도록 Windows 백엔드로 전환합니다. WSL 배포판을 고친 후 설정 > 공유 및 액세스에서 WSL 백엔드를 다시 켜세요.", + "a4acf18834787a4f": "백그라운드 서비스 같은 다른 T3 Code 서버가 이 데이터 디렉터리를 사용 중이거나, 이 디렉터리에 이전 백그라운드 서비스가 설정되어 있습니다. 해당 서버를 중지하거나 `t3 update`를 실행해 보세요. 이전 실행기를 업데이트할 수 없으면 `t3 service uninstall`을 실행하고, 필요하면 최신 CLI에서 `t3 service install`로 다시 설치하세요. `t3`이 없거나 오래되었으면 `npx t3@latest`를 사용하고, 각 명령에 서비스의 T3 홈과 함께 `--base-dir`을 전달하세요. 그런 다음 T3 Code를 다시 여세요. 별도의 T3CODE_HOME을 설정하고 실행 중인 서버와 페어링할 수도 있습니다.", + "0e306130a55a3954": "T3 Code 백그라운드 서비스가 이 T3 홈을 사용 중입니다(PID {pid}, 포트 {port}, 버전 {version}). 이 T3 홈과 함께 `--base-dir`을 전달해 `t3 service uninstall`로 중지한 후 T3 Code를 다시 여세요. 별도의 T3CODE_HOME을 설정하고 실행 중인 서버와 페어링할 수도 있습니다.", + "7379a43c1ac009d2": "T3 Code 백그라운드 서비스가 이 T3 홈을 사용 중입니다(PID {pid}, 포트 {port}). 이 T3 홈과 함께 `--base-dir`을 전달해 `t3 service uninstall`로 중지한 후 T3 Code를 다시 여세요. 별도의 T3CODE_HOME을 설정하고 실행 중인 서버와 페어링할 수도 있습니다.", + "1510c6547cde9c2e": "다른 T3 Code 서버(예: `t3 serve` 또는 SSH로 시작한 서버)가 이 T3 홈을 사용 중입니다(PID {pid}, 포트 {port}, 버전 {version}). 다른 머신의 T3 Code 앱이 SSH로 시작했다면 그 앱이 서버를 다시 시작합니다. 그 앱에서 해당 SSH 환경을 제거하거나 연결을 끊거나, 앱을 종료하세요. 그런 다음 서버를 중지하고 T3 Code를 다시 여세요. 별도의 T3CODE_HOME을 설정하고 실행 중인 서버와 페어링할 수도 있습니다.", + "8d8628520de0d9f1": "다른 T3 Code 서버(예: `t3 serve` 또는 SSH로 시작한 서버)가 이 T3 홈을 사용 중입니다(PID {pid}, 포트 {port}). 다른 머신의 T3 Code 앱이 SSH로 시작했다면 그 앱이 서버를 다시 시작합니다. 그 앱에서 해당 SSH 환경을 제거하거나 연결을 끊거나, 앱을 종료하세요. 그런 다음 서버를 중지하고 T3 Code를 다시 여세요. 별도의 T3CODE_HOME을 설정하고 실행 중인 서버와 페어링할 수도 있습니다.", + "6574442caf8bfd15": "화면 기록 설정", + "a8210440c691b062": "손쉬운 사용 설정", + "0cbbbd8abd25f9d4": "전체 디스크 접근 권한 설정", + "4cd679200c978949": "권한 도우미 닫기", + "ea4f056c8f6b5c15": "↑ T3 Code를 위 목록으로 끌어 놓으세요", + "4bcb0f4db00936b1": "T3 Code를 시스템 설정으로 끌어 놓거나, 클릭하여 Finder에서 보기", + "278648c9ff6fb9ce": "신뢰할 수 있는 기관에서 발급한 인증서가 아닙니다.", + "cf346dcfb658d4d3": "이 주소용 인증서가 아닙니다.", + "20665d9b0c7c3e52": "이 인증서는 만료되었거나 아직 유효하지 않습니다.", + "565970a378986341": "열기", + "00ad8aeed0a6c461": "취소", + "2107cc3e7c4ac833": "이 {protocol} 링크를 열까요?", + "050db36de6624203": "브라우저의 페이지에서 다른 애플리케이션을 열려고 합니다:\n\n{url}", + "c1d7515ac0214ca1": "신뢰하고 기억", + "e89b5b30b1bc99bb": "{host}의 인증서를 신뢰할 수 없습니다", + "16d4c8a1431bd8c2": "발급 대상: {name}", + "5862c92e2dabefab": "발급자: {name}", + "cf559f06dc2e5432": "유효 기간: {start} – {end}", + "86fe6451f52e722a": "지문: {fingerprint}", + "7b20c92539acb4b6": "이 인증서가 해당 사이트의 것임을 알 때만 신뢰하세요. 이 브라우저 프로필의 쿠키를 지우면 신뢰 정보도 삭제됩니다.", + "c67ec08c2c8d0cd9": "{host}의 인증서를 신뢰할 수 없습니다", + "935a340963533dcf": "T3 Code가 이 승인을 저장하지 못해 페이지가 계속 차단됩니다. 디스크가 가득 차지 않았는지, 데이터 폴더에 쓸 수 있는지 확인한 후 다시 시도하세요.", + "a0315d43e8e5be7e": "허용", + "2ec823ca24387055": "차단", + "8fc0b116123fb50b": "{origin}에서 클립보드에 복사된 텍스트와 이미지를 보려고 합니다", + "c0f756221736393f": "미리 보기 · {title}", + "6994444f4fec4070": "브라우저 미리 보기", + "49de6209699eb616": "이름 없는 패스키", + "b4a5bb1075d95154": "패스키 선택", + "1f12213f4d809e89": "최신 버전입니다!", + "c6399b55619e2f67": "T3 Code {version}이(가) 현재 사용 가능한 최신 버전입니다.", + "b6e5b31255e011c5": "확인", + "2ee2077700686fbb": "업데이트 사용 가능", + "d3104b65052b993b": "새 버전의 T3 Code를 사용할 수 있습니다.", + "35fff5a1cd1d6473": "T3 Code {version}을(를) 사용할 수 있습니다.", + "63fbea040532a9ab": "T3 Code {version}을(를) 실행 중입니다.", + "374b1cb8cb616d27": "다운로드", + "b0d022fe9d78def7": "나중에", + "b9a0301ee1348da9": "업데이트 다운로드 중", + "bbaf6039d665a7a7": "새 버전의 T3 Code를 이미 다운로드하고 있습니다.", + "27b49ef7007c126d": "T3 Code {version}을(를) 이미 다운로드하고 있습니다.", + "bd6818c7f005654c": "업데이트 준비됨", + "e0e13c85665bd62f": "새 버전의 T3 Code를 설치할 준비가 되었습니다.", + "dfe6e415877b0533": "T3 Code {version}을(를) 설치할 준비가 되었습니다.", + "d1d10979d6dcb162": "설치하려면 T3 Code가 다시 시작됩니다. 실행 중인 작업은 중단됩니다.", + "2f0a8211a72e29aa": "다시 시작", + "116a21f6cc215e5f": "업데이트 확인 실패", + "32c88cd9421abf33": "업데이트를 확인할 수 없습니다.", + "b37aca07d3c644d9": "알 수 없는 오류가 발생했습니다. 나중에 다시 시도하세요.", + "c8c23435e780a60c": "업데이트를 사용할 수 없음", + "aecf7c98b81bef7a": "지금은 자동 업데이트를 사용할 수 없습니다.", + "835247f842c92bc9": "{appName} 정보", + "959e09151d75e25b": "업데이트 확인...", + "0c753e71e2dca0d0": "설정...", + "a9fad846cd549d96": "{appName} 가리기", + "4b375f39bfce229e": "{appName} 종료", + "83506e64878b7b48": "파일", + "b1f24efbd4e80225": "개발자 도구 닫기", + "2c85ee66be8b81b5": "창 닫기", + "31bfa0ca146dc77f": "편집", + "ebf150404ed417d5": "텍스트로 붙여넣기", + "660715835d05ddca": "말하기", + "25994350fd047a38": "보기", + "573a9e6b17f4e9e3": "새로 고침", + "826cb3059ebc7cc3": "강제 새로 고침", + "8340487d05e832e8": "개발자 도구 전환", + "a7ab66e786347118": "실제 크기", + "a4ad1b27fdc9032d": "확대", + "df6ed2014f1737a8": "축소", + "953979a4737f48fa": "제안 없음", + "202e13f15a3dcd30": "링크 복사", + "8af79268f2349f4c": "이메일 주소 복사", + "a9f9254d458e49fe": "이미지 복사", + "9c1b20fbc881de5d": "데스크톱 구성", + "1b14230874f19eb9": "이미지" +} diff --git a/apps/desktop/src/i18n/translations/pt-BR.json b/apps/desktop/src/i18n/translations/pt-BR.json new file mode 100644 index 000000000000..78e635076cf7 --- /dev/null +++ b/apps/desktop/src/i18n/translations/pt-BR.json @@ -0,0 +1,103 @@ +{ + "743bb98558dcdddf": "O T3 Code não conseguiu iniciar", + "45e444e807bececb": "Este T3 home não está disponível", + "97665653aa9129ad": "Verificando se há uma versão mais recente…", + "dce25e68e60eb512": "A versão {version} está disponível. Ela pode conter uma correção.", + "2f015e6d5459dce9": "Atualizar para {version}", + "ca9838012a0eb084": "Baixando {version}. O T3 Code reinicia quando o download terminar.", + "c38cbed9acc5b0d1": "Baixando {version} ({percent}%). O T3 Code reinicia quando o download terminar.", + "4b4cf6843a4e0aba": "A versão {version} iniciou corretamente neste computador. Baixe e instale-a para voltar.", + "b57c6134d74c0848": "Baixar {version}", + "1eeed583c2254507": "Obtenha outra versão na página de versões.", + "4cd5b64eeb26e1ee": "Abrir versões", + "7e21da2485a8e0bb": "A política gerenciada da sua organização impediu o T3 Code de iniciar. Envie os detalhes abaixo para o administrador de TI.", + "55a19ca527948aaa": "O T3 Code não pôde iniciar", + "4825d2a18a5fc093": "Copiar detalhes", + "3874c9f538653a6d": "Sair", + "0eec8b51246f5e2c": "O servidor não gerou saída.", + "6cb1b68bddf39b35": "Versão {version}. O T3 Code tenta novamente em segundo plano. Logs: {logDir}", + "895f988b9de16f88": "O backend do WSL continua indisponível", + "eeb7ea62dc4706c1": "O T3 Code vai usar o backend do Windows nesta execução e tentar o WSL de novo na próxima vez que o app iniciar.", + "b5435aa5b470bafd": "O backend do WSL não pôde iniciar", + "d82d7c96e1904629": "Usando o backend do Windows para que o T3 Code possa abrir. Reative o backend do WSL em Configurações > Compartilhamento e acesso quando a distro do WSL for corrigida.", + "a4acf18834787a4f": "Outro servidor do T3 Code, como o serviço em segundo plano, está usando este diretório de dados, ou um serviço em segundo plano mais antigo está configurado para ele. Pare esse servidor ou tente `t3 update`. Se o inicializador mais antigo não conseguir atualizar, execute `t3 service uninstall` e, se quiser, reinstale com `t3 service install` a partir de uma CLI atual. Use `npx t3@latest` se o `t3` estiver ausente ou desatualizado e passe `--base-dir` com o T3 home do serviço em cada comando. Depois, reabra o T3 Code. Você também pode definir um T3CODE_HOME separado e parear com o servidor em execução.", + "0e306130a55a3954": "O serviço em segundo plano do T3 Code está usando este T3 home (PID {pid}, porta {port}, versão {version}). Pare-o com `t3 service uninstall`, passando `--base-dir` com este T3 home, e reabra o T3 Code. Você também pode definir um T3CODE_HOME separado e parear com o servidor em execução.", + "7379a43c1ac009d2": "O serviço em segundo plano do T3 Code está usando este T3 home (PID {pid}, porta {port}). Pare-o com `t3 service uninstall`, passando `--base-dir` com este T3 home, e reabra o T3 Code. Você também pode definir um T3CODE_HOME separado e parear com o servidor em execução.", + "1510c6547cde9c2e": "Outro servidor do T3 Code (por exemplo, `t3 serve` ou um iniciado por SSH) está usando este T3 home (PID {pid}, porta {port}, versão {version}). Se um app do T3 Code em outra máquina o iniciou por SSH, esse app o reinicia: remova ou desconecte esse ambiente SSH lá ou feche esse app. Depois, pare o servidor e reabra o T3 Code. Você também pode definir um T3CODE_HOME separado e parear com o servidor em execução.", + "8d8628520de0d9f1": "Outro servidor do T3 Code (por exemplo, `t3 serve` ou um iniciado por SSH) está usando este T3 home (PID {pid}, porta {port}). Se um app do T3 Code em outra máquina o iniciou por SSH, esse app o reinicia: remova ou desconecte esse ambiente SSH lá ou feche esse app. Depois, pare o servidor e reabra o T3 Code. Você também pode definir um T3CODE_HOME separado e parear com o servidor em execução.", + "6574442caf8bfd15": "Configurar Gravação de Tela", + "a8210440c691b062": "Configurar Acessibilidade", + "0cbbbd8abd25f9d4": "Configurar Acesso Total ao Disco", + "4cd679200c978949": "Fechar o assistente de permissões", + "ea4f056c8f6b5c15": "↑ Arraste o T3 Code para a lista acima", + "4bcb0f4db00936b1": "Arraste o T3 Code para os Ajustes do Sistema ou clique para mostrar no Finder", + "278648c9ff6fb9ce": "Nenhuma autoridade confiável emitiu este certificado.", + "cf346dcfb658d4d3": "Este certificado não é para este endereço.", + "20665d9b0c7c3e52": "Este certificado expirou ou ainda não é válido.", + "565970a378986341": "Abrir", + "00ad8aeed0a6c461": "Cancelar", + "2107cc3e7c4ac833": "Abrir este link {protocol}?", + "050db36de6624203": "Uma página no navegador quer abrir outro aplicativo:\n\n{url}", + "c1d7515ac0214ca1": "Confiar e lembrar", + "e89b5b30b1bc99bb": "{host} tem um certificado não confiável", + "16d4c8a1431bd8c2": "Emitido para: {name}", + "5862c92e2dabefab": "Emitido por: {name}", + "cf559f06dc2e5432": "Válido: {start} – {end}", + "86fe6451f52e722a": "Impressão digital: {fingerprint}", + "7b20c92539acb4b6": "Confie nele só se você souber que este certificado pertence ao site. Limpar os cookies deste perfil do navegador faz com que ele seja esquecido.", + "c67ec08c2c8d0cd9": "Não foi possível confiar no certificado de {host}", + "935a340963533dcf": "O T3 Code não conseguiu salvar esta aprovação, então a página continua bloqueada. Verifique se o disco não está cheio e se a pasta de dados permite gravação e tente novamente.", + "a0315d43e8e5be7e": "Permitir", + "2ec823ca24387055": "Bloquear", + "8fc0b116123fb50b": "{origin} quer ver textos e imagens copiados para a área de transferência", + "c0f756221736393f": "Pré-visualização · {title}", + "6994444f4fec4070": "Pré-visualização do navegador", + "49de6209699eb616": "Chave de acesso sem nome", + "b4a5bb1075d95154": "Escolha uma chave de acesso", + "1f12213f4d809e89": "Você está atualizado!", + "c6399b55619e2f67": "O T3 Code {version} é a versão mais recente disponível.", + "b6e5b31255e011c5": "OK", + "2ee2077700686fbb": "Atualização disponível", + "d3104b65052b993b": "Há uma nova versão do T3 Code disponível.", + "35fff5a1cd1d6473": "O T3 Code {version} está disponível.", + "63fbea040532a9ab": "Você está usando o T3 Code {version}.", + "374b1cb8cb616d27": "Baixar", + "b0d022fe9d78def7": "Depois", + "b9a0301ee1348da9": "Baixando atualização", + "bbaf6039d665a7a7": "Uma nova versão do T3 Code já está sendo baixada.", + "27b49ef7007c126d": "O T3 Code {version} já está sendo baixado.", + "bd6818c7f005654c": "Atualização pronta", + "e0e13c85665bd62f": "Uma nova versão do T3 Code está pronta para instalar.", + "dfe6e415877b0533": "O T3 Code {version} está pronto para instalar.", + "d1d10979d6dcb162": "O T3 Code será reiniciado para instalá-la. As tarefas em execução serão interrompidas.", + "2f0a8211a72e29aa": "Reiniciar", + "116a21f6cc215e5f": "Falha ao verificar atualizações", + "32c88cd9421abf33": "Não foi possível verificar atualizações.", + "b37aca07d3c644d9": "Ocorreu um erro desconhecido. Tente novamente mais tarde.", + "c8c23435e780a60c": "Atualizações indisponíveis", + "aecf7c98b81bef7a": "As atualizações automáticas não estão disponíveis no momento.", + "835247f842c92bc9": "Sobre o {appName}", + "959e09151d75e25b": "Verificar atualizações...", + "0c753e71e2dca0d0": "Configurações...", + "a9fad846cd549d96": "Ocultar {appName}", + "4b375f39bfce229e": "Sair do {appName}", + "83506e64878b7b48": "Arquivo", + "b1f24efbd4e80225": "Fechar ferramentas do desenvolvedor", + "2c85ee66be8b81b5": "Fechar janela", + "31bfa0ca146dc77f": "Editar", + "ebf150404ed417d5": "Colar como texto", + "660715835d05ddca": "Fala", + "25994350fd047a38": "Exibir", + "573a9e6b17f4e9e3": "Recarregar", + "826cb3059ebc7cc3": "Forçar recarregamento", + "8340487d05e832e8": "Alternar ferramentas do desenvolvedor", + "a7ab66e786347118": "Tamanho real", + "a4ad1b27fdc9032d": "Aumentar zoom", + "df6ed2014f1737a8": "Diminuir zoom", + "953979a4737f48fa": "Nenhuma sugestão", + "202e13f15a3dcd30": "Copiar link", + "8af79268f2349f4c": "Copiar endereço de e-mail", + "a9f9254d458e49fe": "Copiar imagem", + "9c1b20fbc881de5d": "Configuração do desktop", + "1b14230874f19eb9": "Imagens" +} diff --git a/apps/desktop/src/i18n/translations/ru.json b/apps/desktop/src/i18n/translations/ru.json new file mode 100644 index 000000000000..deb40ac5292c --- /dev/null +++ b/apps/desktop/src/i18n/translations/ru.json @@ -0,0 +1,103 @@ +{ + "743bb98558dcdddf": "Не удалось запустить T3 Code", + "45e444e807bececb": "Этот домашний каталог T3 недоступен", + "97665653aa9129ad": "Поиск новой версии…", + "dce25e68e60eb512": "Доступна версия {version}. В ней может быть исправление.", + "2f015e6d5459dce9": "Обновить до {version}", + "ca9838012a0eb084": "Загрузка {version}. T3 Code перезапустится после завершения загрузки.", + "c38cbed9acc5b0d1": "Загрузка {version} ({percent}%). T3 Code перезапустится после завершения загрузки.", + "4b4cf6843a4e0aba": "Версия {version} корректно запускалась на этом компьютере. Скачайте и установите её, чтобы вернуться.", + "b57c6134d74c0848": "Скачать {version}", + "1eeed583c2254507": "Скачайте другую версию со страницы релизов.", + "4cd5b64eeb26e1ee": "Открыть релизы", + "7e21da2485a8e0bb": "Управляемая политика вашей организации не дала запустить T3 Code. Отправьте сведения ниже вашему ИТ-администратору.", + "55a19ca527948aaa": "T3 Code не удалось запустить", + "4825d2a18a5fc093": "Копировать подробности", + "3874c9f538653a6d": "Выйти", + "0eec8b51246f5e2c": "Сервер ничего не вывел.", + "6cb1b68bddf39b35": "Версия {version}. T3 Code повторит попытку в фоне. Логи: {logDir}", + "895f988b9de16f88": "Бэкенд WSL по-прежнему недоступен", + "eeb7ea62dc4706c1": "T3 Code использует бэкенд Windows при этом запуске и повторит попытку с WSL при следующем запуске приложения.", + "b5435aa5b470bafd": "Не удалось запустить бэкенд WSL", + "d82d7c96e1904629": "Переключение на бэкенд Windows, чтобы T3 Code мог открыться. Снова включите бэкенд WSL в Настройки > Общий доступ, когда дистрибутив WSL будет исправлен.", + "a4acf18834787a4f": "Этот каталог данных использует другой сервер T3 Code, например фоновая служба, или для него настроена старая фоновая служба. Остановите этот сервер или попробуйте `t3 update`. Если старый лаунчер не может обновиться, выполните `t3 service uninstall` и при необходимости переустановите командой `t3 service install` из актуального CLI. Используйте `npx t3@latest`, если `t3` отсутствует или устарел, и передавайте в каждую команду `--base-dir` с домашним каталогом T3 этой службы. Затем снова откройте T3 Code. Также можно задать отдельный T3CODE_HOME и выполнить сопряжение с запущенным сервером.", + "0e306130a55a3954": "Этот домашний каталог T3 использует фоновая служба T3 Code (PID {pid}, порт {port}, версия {version}). Остановите её командой `t3 service uninstall`, передав `--base-dir` с этим домашним каталогом T3, и снова откройте T3 Code. Также можно задать отдельный T3CODE_HOME и выполнить сопряжение с запущенным сервером.", + "7379a43c1ac009d2": "Этот домашний каталог T3 использует фоновая служба T3 Code (PID {pid}, порт {port}). Остановите её командой `t3 service uninstall`, передав `--base-dir` с этим домашним каталогом T3, и снова откройте T3 Code. Также можно задать отдельный T3CODE_HOME и выполнить сопряжение с запущенным сервером.", + "1510c6547cde9c2e": "Этот домашний каталог T3 использует другой сервер T3 Code (например, `t3 serve` или запущенный через SSH) (PID {pid}, порт {port}, версия {version}). Если его запустило через SSH приложение T3 Code на другом компьютере, это приложение перезапустит его: удалите или отключите там это SSH-окружение либо закройте то приложение. Затем остановите сервер и снова откройте T3 Code. Также можно задать отдельный T3CODE_HOME и выполнить сопряжение с запущенным сервером.", + "8d8628520de0d9f1": "Этот домашний каталог T3 использует другой сервер T3 Code (например, `t3 serve` или запущенный через SSH) (PID {pid}, порт {port}). Если его запустило через SSH приложение T3 Code на другом компьютере, это приложение перезапустит его: удалите или отключите там это SSH-окружение либо закройте то приложение. Затем остановите сервер и снова откройте T3 Code. Также можно задать отдельный T3CODE_HOME и выполнить сопряжение с запущенным сервером.", + "6574442caf8bfd15": "Настроить запись экрана", + "a8210440c691b062": "Настроить универсальный доступ", + "0cbbbd8abd25f9d4": "Настроить полный доступ к диску", + "4cd679200c978949": "Закрыть помощник разрешений", + "ea4f056c8f6b5c15": "↑ Перетащите T3 Code в список выше", + "4bcb0f4db00936b1": "Перетащите T3 Code в Системные настройки или нажмите, чтобы показать в Finder", + "278648c9ff6fb9ce": "Этот сертификат выдан недоверенным центром.", + "cf346dcfb658d4d3": "Этот сертификат выдан не для этого адреса.", + "20665d9b0c7c3e52": "Срок действия этого сертификата истёк или ещё не начался.", + "565970a378986341": "Открыть", + "00ad8aeed0a6c461": "Отмена", + "2107cc3e7c4ac833": "Открыть эту ссылку {protocol}?", + "050db36de6624203": "Страница в браузере хочет открыть другое приложение:\n\n{url}", + "c1d7515ac0214ca1": "Доверять и запомнить", + "e89b5b30b1bc99bb": "У {host} недоверенный сертификат", + "16d4c8a1431bd8c2": "Кому выдан: {name}", + "5862c92e2dabefab": "Кем выдан: {name}", + "cf559f06dc2e5432": "Действителен: {start} – {end}", + "86fe6451f52e722a": "Отпечаток: {fingerprint}", + "7b20c92539acb4b6": "Доверяйте, только если знаете, что этот сертификат принадлежит сайту. Очистка cookie этого профиля браузера сбросит доверие.", + "c67ec08c2c8d0cd9": "Не удалось доверять сертификату для {host}", + "935a340963533dcf": "T3 Code не удалось сохранить это разрешение, поэтому страница остаётся заблокированной. Убедитесь, что диск не заполнен, а папка данных доступна для записи, и повторите попытку.", + "a0315d43e8e5be7e": "Разрешить", + "2ec823ca24387055": "Блокировать", + "8fc0b116123fb50b": "{origin} хочет видеть текст и изображения, скопированные в буфер обмена", + "c0f756221736393f": "Предпросмотр · {title}", + "6994444f4fec4070": "Предпросмотр в браузере", + "49de6209699eb616": "Безымянный ключ доступа", + "b4a5bb1075d95154": "Выберите ключ доступа", + "1f12213f4d809e89": "У вас последняя версия!", + "c6399b55619e2f67": "T3 Code {version} — новейшая доступная версия.", + "b6e5b31255e011c5": "OK", + "2ee2077700686fbb": "Доступно обновление", + "d3104b65052b993b": "Доступна новая версия T3 Code.", + "35fff5a1cd1d6473": "Доступна версия T3 Code {version}.", + "63fbea040532a9ab": "У вас T3 Code {version}.", + "374b1cb8cb616d27": "Скачать", + "b0d022fe9d78def7": "Позже", + "b9a0301ee1348da9": "Загрузка обновления", + "bbaf6039d665a7a7": "Новая версия T3 Code уже загружается.", + "27b49ef7007c126d": "T3 Code {version} уже загружается.", + "bd6818c7f005654c": "Обновление готово", + "e0e13c85665bd62f": "Новая версия T3 Code готова к установке.", + "dfe6e415877b0533": "T3 Code {version} готов к установке.", + "d1d10979d6dcb162": "T3 Code перезапустится для установки. Все выполняющиеся задачи будут прерваны.", + "2f0a8211a72e29aa": "Перезапустить", + "116a21f6cc215e5f": "Ошибка проверки обновлений", + "32c88cd9421abf33": "Не удалось проверить обновления.", + "b37aca07d3c644d9": "Произошла неизвестная ошибка. Повторите попытку позже.", + "c8c23435e780a60c": "Обновления недоступны", + "aecf7c98b81bef7a": "Автоматические обновления сейчас недоступны.", + "835247f842c92bc9": "О приложении {appName}", + "959e09151d75e25b": "Проверить обновления...", + "0c753e71e2dca0d0": "Настройки...", + "a9fad846cd549d96": "Скрыть {appName}", + "4b375f39bfce229e": "Выйти из {appName}", + "83506e64878b7b48": "Файл", + "b1f24efbd4e80225": "Закрыть инструменты разработчика", + "2c85ee66be8b81b5": "Закрыть окно", + "31bfa0ca146dc77f": "Правка", + "ebf150404ed417d5": "Вставить как текст", + "660715835d05ddca": "Речь", + "25994350fd047a38": "Вид", + "573a9e6b17f4e9e3": "Перезагрузить", + "826cb3059ebc7cc3": "Принудительная перезагрузка", + "8340487d05e832e8": "Инструменты разработчика", + "a7ab66e786347118": "Фактический размер", + "a4ad1b27fdc9032d": "Увеличить", + "df6ed2014f1737a8": "Уменьшить", + "953979a4737f48fa": "Нет вариантов", + "202e13f15a3dcd30": "Копировать ссылку", + "8af79268f2349f4c": "Копировать адрес электронной почты", + "a9f9254d458e49fe": "Копировать изображение", + "9c1b20fbc881de5d": "Конфигурация десктопа", + "1b14230874f19eb9": "Изображения" +} diff --git a/apps/desktop/src/i18n/translations/sv.json b/apps/desktop/src/i18n/translations/sv.json new file mode 100644 index 000000000000..aa30b26073b3 --- /dev/null +++ b/apps/desktop/src/i18n/translations/sv.json @@ -0,0 +1,103 @@ +{ + "743bb98558dcdddf": "T3 Code kunde inte starta", + "45e444e807bececb": "Den här T3-hemkatalogen är inte tillgänglig", + "97665653aa9129ad": "Söker efter en nyare version…", + "dce25e68e60eb512": "Version {version} är tillgänglig. Den kan innehålla en korrigering.", + "2f015e6d5459dce9": "Uppdatera till {version}", + "ca9838012a0eb084": "Laddar ner {version}. T3 Code startar om när nedladdningen är klar.", + "c38cbed9acc5b0d1": "Laddar ner {version} ({percent} %). T3 Code startar om när nedladdningen är klar.", + "4b4cf6843a4e0aba": "Version {version} startade korrekt på den här datorn. Ladda ner och installera den för att gå tillbaka.", + "b57c6134d74c0848": "Ladda ner {version}", + "1eeed583c2254507": "Hämta en annan version från versionssidan.", + "4cd5b64eeb26e1ee": "Öppna versioner", + "7e21da2485a8e0bb": "Din organisations hanterade policy hindrade T3 Code från att starta. Skicka informationen nedan till din IT-administratör.", + "55a19ca527948aaa": "T3 Code kunde inte starta", + "4825d2a18a5fc093": "Kopiera detaljer", + "3874c9f538653a6d": "Avsluta", + "0eec8b51246f5e2c": "Servern skrev ingen utdata.", + "6cb1b68bddf39b35": "Version {version}. T3 Code försöker igen i bakgrunden. Loggar: {logDir}", + "895f988b9de16f88": "WSL-backend är fortfarande inte tillgänglig", + "eeb7ea62dc4706c1": "T3 Code använder Windows-backend för den här starten och försöker med WSL igen nästa gång appen startar.", + "b5435aa5b470bafd": "WSL-backend kunde inte starta", + "d82d7c96e1904629": "Faller tillbaka på Windows-backend så att T3 Code kan öppnas. Aktivera WSL-backend igen i Inställningar > Delning och åtkomst när WSL-distributionen är åtgärdad.", + "a4acf18834787a4f": "En annan T3 Code-server, till exempel bakgrundstjänsten, använder den här datakatalogen, eller så är en äldre bakgrundstjänst konfigurerad för den. Stoppa den servern eller prova `t3 update`. Om den äldre startaren inte kan uppdatera kör du `t3 service uninstall` och installerar eventuellt om med `t3 service install` från ett aktuellt CLI. Använd `npx t3@latest` om `t3` saknas eller är inaktuellt, och skicka med `--base-dir` med tjänstens T3-hemkatalog till varje kommando. Öppna sedan T3 Code igen. Du kan också ange en separat T3CODE_HOME och parkoppla med servern som körs.", + "0e306130a55a3954": "T3 Codes bakgrundstjänst använder den här T3-hemkatalogen (PID {pid}, port {port}, version {version}). Stoppa den med `t3 service uninstall`, med `--base-dir` satt till den här T3-hemkatalogen, och öppna T3 Code igen. Du kan också ange en separat T3CODE_HOME och parkoppla med servern som körs.", + "7379a43c1ac009d2": "T3 Codes bakgrundstjänst använder den här T3-hemkatalogen (PID {pid}, port {port}). Stoppa den med `t3 service uninstall`, med `--base-dir` satt till den här T3-hemkatalogen, och öppna T3 Code igen. Du kan också ange en separat T3CODE_HOME och parkoppla med servern som körs.", + "1510c6547cde9c2e": "En annan T3 Code-server (till exempel `t3 serve` eller en som startats över SSH) använder den här T3-hemkatalogen (PID {pid}, port {port}, version {version}). Om en T3 Code-app på en annan dator startade den över SSH startar den appen om den: ta bort eller koppla från SSH-miljön där, eller avsluta appen. Stoppa sedan servern och öppna T3 Code igen. Du kan också ange en separat T3CODE_HOME och parkoppla med servern som körs.", + "8d8628520de0d9f1": "En annan T3 Code-server (till exempel `t3 serve` eller en som startats över SSH) använder den här T3-hemkatalogen (PID {pid}, port {port}). Om en T3 Code-app på en annan dator startade den över SSH startar den appen om den: ta bort eller koppla från SSH-miljön där, eller avsluta appen. Stoppa sedan servern och öppna T3 Code igen. Du kan också ange en separat T3CODE_HOME och parkoppla med servern som körs.", + "6574442caf8bfd15": "Konfigurera skärminspelning", + "a8210440c691b062": "Konfigurera hjälpmedel", + "0cbbbd8abd25f9d4": "Konfigurera Full skivåtkomst", + "4cd679200c978949": "Stäng behörighetshjälpen", + "ea4f056c8f6b5c15": "↑ Dra T3 Code till listan ovan", + "4bcb0f4db00936b1": "Dra T3 Code till Systeminställningar eller klicka för att visa i Finder", + "278648c9ff6fb9ce": "Ingen betrodd utfärdare utfärdade det här certifikatet.", + "cf346dcfb658d4d3": "Det här certifikatet gäller inte den här adressen.", + "20665d9b0c7c3e52": "Det här certifikatet har gått ut eller är inte giltigt än.", + "565970a378986341": "Öppna", + "00ad8aeed0a6c461": "Avbryt", + "2107cc3e7c4ac833": "Öppna den här {protocol}-länken?", + "050db36de6624203": "En sida i webbläsaren vill öppna ett annat program:\n\n{url}", + "c1d7515ac0214ca1": "Lita på och kom ihåg", + "e89b5b30b1bc99bb": "{host} har ett certifikat som inte är betrott", + "16d4c8a1431bd8c2": "Utfärdat till: {name}", + "5862c92e2dabefab": "Utfärdat av: {name}", + "cf559f06dc2e5432": "Giltigt: {start} – {end}", + "86fe6451f52e722a": "Fingeravtryck: {fingerprint}", + "7b20c92539acb4b6": "Lita bara på det om du vet att certifikatet tillhör webbplatsen. Om du rensar cookies i den här webbläsarprofilen glöms det.", + "c67ec08c2c8d0cd9": "Kunde inte lita på certifikatet för {host}", + "935a340963533dcf": "T3 Code kunde inte spara det här godkännandet, så sidan förblir blockerad. Kontrollera att disken inte är full och att datamappen är skrivbar och försök sedan igen.", + "a0315d43e8e5be7e": "Tillåt", + "2ec823ca24387055": "Blockera", + "8fc0b116123fb50b": "{origin} vill se text och bilder som kopierats till urklipp", + "c0f756221736393f": "Förhandsvisning · {title}", + "6994444f4fec4070": "Förhandsvisning i webbläsaren", + "49de6209699eb616": "Namnlös lösenordsnyckel", + "b4a5bb1075d95154": "Välj en lösenordsnyckel", + "1f12213f4d809e89": "Du har den senaste versionen!", + "c6399b55619e2f67": "T3 Code {version} är den senaste tillgängliga versionen.", + "b6e5b31255e011c5": "OK", + "2ee2077700686fbb": "Uppdatering tillgänglig", + "d3104b65052b993b": "En ny version av T3 Code är tillgänglig.", + "35fff5a1cd1d6473": "T3 Code {version} är tillgänglig.", + "63fbea040532a9ab": "Du kör T3 Code {version}.", + "374b1cb8cb616d27": "Ladda ned", + "b0d022fe9d78def7": "Senare", + "b9a0301ee1348da9": "Uppdateringen laddas ner", + "bbaf6039d665a7a7": "En ny version av T3 Code laddas redan ner.", + "27b49ef7007c126d": "T3 Code {version} laddas redan ner.", + "bd6818c7f005654c": "Uppdatering klar", + "e0e13c85665bd62f": "En ny version av T3 Code är redo att installeras.", + "dfe6e415877b0533": "T3 Code {version} är redo att installeras.", + "d1d10979d6dcb162": "T3 Code startar om för att installera den. Uppgifter som körs avbryts.", + "2f0a8211a72e29aa": "Starta om", + "116a21f6cc215e5f": "Sökningen efter uppdateringar misslyckades", + "32c88cd9421abf33": "Kunde inte söka efter uppdateringar.", + "b37aca07d3c644d9": "Ett okänt fel inträffade. Försök igen senare.", + "c8c23435e780a60c": "Uppdateringar är inte tillgängliga", + "aecf7c98b81bef7a": "Automatiska uppdateringar är inte tillgängliga just nu.", + "835247f842c92bc9": "Om {appName}", + "959e09151d75e25b": "Sök efter uppdateringar...", + "0c753e71e2dca0d0": "Inställningar...", + "a9fad846cd549d96": "Dölj {appName}", + "4b375f39bfce229e": "Avsluta {appName}", + "83506e64878b7b48": "Arkiv", + "b1f24efbd4e80225": "Stäng utvecklarverktyg", + "2c85ee66be8b81b5": "Stäng fönster", + "31bfa0ca146dc77f": "Redigera", + "ebf150404ed417d5": "Klistra in som text", + "660715835d05ddca": "Tal", + "25994350fd047a38": "Visa", + "573a9e6b17f4e9e3": "Läs in igen", + "826cb3059ebc7cc3": "Tvinga omladdning", + "8340487d05e832e8": "Växla utvecklarverktyg", + "a7ab66e786347118": "Verklig storlek", + "a4ad1b27fdc9032d": "Zooma in", + "df6ed2014f1737a8": "Zooma ut", + "953979a4737f48fa": "Inga förslag", + "202e13f15a3dcd30": "Kopiera länk", + "8af79268f2349f4c": "Kopiera e-postadress", + "a9f9254d458e49fe": "Kopiera bild", + "9c1b20fbc881de5d": "Skrivbordskonfiguration", + "1b14230874f19eb9": "Bilder" +} diff --git a/apps/desktop/src/i18n/translations/zh.json b/apps/desktop/src/i18n/translations/zh.json new file mode 100644 index 000000000000..f8c6a6e6be21 --- /dev/null +++ b/apps/desktop/src/i18n/translations/zh.json @@ -0,0 +1,103 @@ +{ + "743bb98558dcdddf": "T3 Code 启动失败", + "45e444e807bececb": "此 T3 主目录不可用", + "97665653aa9129ad": "正在检查新版本…", + "dce25e68e60eb512": "版本 {version} 可用。它可能包含修复。", + "2f015e6d5459dce9": "更新到 {version}", + "ca9838012a0eb084": "正在下载 {version}。下载完成后 T3 Code 将重启。", + "c38cbed9acc5b0d1": "正在下载 {version}({percent}%)。下载完成后 T3 Code 将重启。", + "4b4cf6843a4e0aba": "版本 {version} 曾在此计算机上正常启动。下载并安装它即可回退。", + "b57c6134d74c0848": "下载 {version}", + "1eeed583c2254507": "从发布页面获取其他版本。", + "4cd5b64eeb26e1ee": "打开发布页面", + "7e21da2485a8e0bb": "你的组织托管策略阻止了 T3 Code 启动。请将以下详细信息发送给你的 IT 管理员。", + "55a19ca527948aaa": "T3 Code 无法启动", + "4825d2a18a5fc093": "复制详情", + "3874c9f538653a6d": "退出", + "0eec8b51246f5e2c": "服务器没有输出任何内容。", + "6cb1b68bddf39b35": "版本 {version}。T3 Code 会在后台重试。日志:{logDir}", + "895f988b9de16f88": "WSL 后端仍不可用", + "eeb7ea62dc4706c1": "本次启动 T3 Code 将使用 Windows 后端,并在下次启动应用时重试 WSL。", + "b5435aa5b470bafd": "WSL 后端无法启动", + "d82d7c96e1904629": "正在回退到 Windows 后端,以便打开 T3 Code。修复 WSL 发行版后,请在“设置 > 共享与访问”中重新启用 WSL 后端。", + "a4acf18834787a4f": "另一个 T3 Code 服务器(例如后台服务)正在使用此数据目录,或此目录已配置旧版后台服务。请停止该服务器,或尝试 `t3 update`。如果旧版启动器无法更新,请运行 `t3 service uninstall`,并可使用当前 CLI 运行 `t3 service install` 重新安装。如果 `t3` 缺失或过旧,请使用 `npx t3@latest`,并在每条命令中通过 `--base-dir` 指定该服务的 T3 主目录。然后重新打开 T3 Code。你也可以设置单独的 T3CODE_HOME,并与正在运行的服务器配对。", + "0e306130a55a3954": "T3 Code 后台服务正在使用此 T3 主目录(PID {pid},端口 {port},版本 {version})。请使用 `t3 service uninstall` 停止它,并通过 `--base-dir` 传入此 T3 主目录,然后重新打开 T3 Code。你也可以设置单独的 T3CODE_HOME 并与正在运行的服务器配对。", + "7379a43c1ac009d2": "T3 Code 后台服务正在使用此 T3 主目录(PID {pid},端口 {port})。请使用 `t3 service uninstall` 停止它,并通过 `--base-dir` 传入此 T3 主目录,然后重新打开 T3 Code。你也可以设置单独的 T3CODE_HOME 并与正在运行的服务器配对。", + "1510c6547cde9c2e": "另一个 T3 Code 服务器(例如 `t3 serve`,或通过 SSH 启动的服务器)正在使用此 T3 主目录(PID {pid},端口 {port},版本 {version})。如果是另一台机器上的 T3 Code 应用通过 SSH 启动了它,该应用会重新启动它:请在那里移除或断开该 SSH 环境,或退出该应用。然后停止该服务器,并重新打开 T3 Code。你也可以设置单独的 T3CODE_HOME 并与正在运行的服务器配对。", + "8d8628520de0d9f1": "另一个 T3 Code 服务器(例如 `t3 serve`,或通过 SSH 启动的服务器)正在使用此 T3 主目录(PID {pid},端口 {port})。如果是另一台机器上的 T3 Code 应用通过 SSH 启动了它,该应用会重新启动它:请在那里移除或断开该 SSH 环境,或退出该应用。然后停止该服务器,并重新打开 T3 Code。你也可以设置单独的 T3CODE_HOME 并与正在运行的服务器配对。", + "6574442caf8bfd15": "设置屏幕录制", + "a8210440c691b062": "设置辅助功能", + "0cbbbd8abd25f9d4": "设置完全磁盘访问权限", + "4cd679200c978949": "关闭权限助手", + "ea4f056c8f6b5c15": "↑ 将 T3 Code 拖入上方列表", + "4bcb0f4db00936b1": "将 T3 Code 拖入系统设置,或点击在 Finder 中显示", + "278648c9ff6fb9ce": "此证书并非由受信任的机构签发。", + "cf346dcfb658d4d3": "此证书不适用于当前地址。", + "20665d9b0c7c3e52": "此证书已过期或尚未生效。", + "565970a378986341": "打开", + "00ad8aeed0a6c461": "取消", + "2107cc3e7c4ac833": "要打开此 {protocol} 链接吗?", + "050db36de6624203": "浏览器中的页面想打开另一个应用:\n\n{url}", + "c1d7515ac0214ca1": "信任并记住", + "e89b5b30b1bc99bb": "{host} 的证书不受信任", + "16d4c8a1431bd8c2": "颁发给:{name}", + "5862c92e2dabefab": "颁发者:{name}", + "cf559f06dc2e5432": "有效期:{start} – {end}", + "86fe6451f52e722a": "指纹:{fingerprint}", + "7b20c92539acb4b6": "仅在确认此证书属于该网站时信任它。清除此浏览器配置的 cookies 后将不再信任此证书。", + "c67ec08c2c8d0cd9": "无法信任 {host} 的证书", + "935a340963533dcf": "T3 Code 无法保存此次批准,因此页面仍被阻止。请检查磁盘空间和数据目录的写入权限后重试。", + "a0315d43e8e5be7e": "允许", + "2ec823ca24387055": "阻止", + "8fc0b116123fb50b": "{origin} 想查看复制到剪贴板的文字和图片", + "c0f756221736393f": "预览 · {title}", + "6994444f4fec4070": "浏览器预览", + "49de6209699eb616": "未命名通行密钥", + "b4a5bb1075d95154": "选择通行密钥", + "1f12213f4d809e89": "已是最新版本!", + "c6399b55619e2f67": "T3 Code {version} 已是最新版本。", + "b6e5b31255e011c5": "确定", + "2ee2077700686fbb": "有可用更新", + "d3104b65052b993b": "T3 Code 有新版本可用。", + "35fff5a1cd1d6473": "T3 Code {version} 可用。", + "63fbea040532a9ab": "你当前运行的是 T3 Code {version}。", + "374b1cb8cb616d27": "下载", + "b0d022fe9d78def7": "稍后", + "b9a0301ee1348da9": "正在下载更新", + "bbaf6039d665a7a7": "T3 Code 的新版本已在下载中。", + "27b49ef7007c126d": "T3 Code {version} 已在下载中。", + "bd6818c7f005654c": "更新已就绪", + "e0e13c85665bd62f": "T3 Code 的新版本已准备好安装。", + "dfe6e415877b0533": "T3 Code {version} 已准备好安装。", + "d1d10979d6dcb162": "T3 Code 将重启以安装更新,正在运行的任务会被中断。", + "2f0a8211a72e29aa": "重启", + "116a21f6cc215e5f": "检查更新失败", + "32c88cd9421abf33": "无法检查更新。", + "b37aca07d3c644d9": "发生未知错误,请稍后重试。", + "c8c23435e780a60c": "更新不可用", + "aecf7c98b81bef7a": "目前无法自动更新。", + "835247f842c92bc9": "关于 {appName}", + "959e09151d75e25b": "检查更新…", + "0c753e71e2dca0d0": "设置…", + "a9fad846cd549d96": "隐藏 {appName}", + "4b375f39bfce229e": "退出 {appName}", + "83506e64878b7b48": "文件", + "b1f24efbd4e80225": "关闭开发者工具", + "2c85ee66be8b81b5": "关闭窗口", + "31bfa0ca146dc77f": "编辑", + "ebf150404ed417d5": "粘贴为纯文本", + "660715835d05ddca": "语音", + "25994350fd047a38": "查看", + "573a9e6b17f4e9e3": "重新加载", + "826cb3059ebc7cc3": "强制重新加载", + "8340487d05e832e8": "切换开发者工具", + "a7ab66e786347118": "实际大小", + "a4ad1b27fdc9032d": "放大", + "df6ed2014f1737a8": "缩小", + "953979a4737f48fa": "无建议", + "202e13f15a3dcd30": "复制链接", + "8af79268f2349f4c": "复制邮箱地址", + "a9f9254d458e49fe": "复制图片", + "9c1b20fbc881de5d": "桌面配置", + "1b14230874f19eb9": "图片" +} diff --git a/apps/desktop/src/ipc/methods/clientSettings.ts b/apps/desktop/src/ipc/methods/clientSettings.ts index 7a647a58dc43..56e861944871 100644 --- a/apps/desktop/src/ipc/methods/clientSettings.ts +++ b/apps/desktop/src/ipc/methods/clientSettings.ts @@ -3,6 +3,7 @@ import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; +import { applyLanguage } from "../../i18n/messages.ts"; import * as DesktopClientSettings from "../../settings/DesktopClientSettings.ts"; import * as DesktopSnapShot from "../../snapShot/DesktopSnapShot.ts"; import * as IpcChannels from "../channels.ts"; @@ -27,5 +28,6 @@ export const setClientSettings = DesktopIpc.makeIpcMethod({ const snapShot = yield* DesktopSnapShot.DesktopSnapShot; yield* clientSettings.set(settings); yield* snapShot.configure(settings); + yield* applyLanguage(settings.language); }), }); diff --git a/apps/desktop/src/ipc/methods/snapShot.ts b/apps/desktop/src/ipc/methods/snapShot.ts index dff64081b70c..1a37882f4871 100644 --- a/apps/desktop/src/ipc/methods/snapShot.ts +++ b/apps/desktop/src/ipc/methods/snapShot.ts @@ -14,11 +14,13 @@ import { import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; +import { msg } from "gt-i18n"; import type * as Electron from "electron"; import * as ElectronWindow from "../../electron/ElectronWindow.ts"; import * as ElectronDialog from "../../electron/ElectronDialog.ts"; import * as DesktopSnapShot from "../../snapShot/DesktopSnapShot.ts"; +import { m } from "../../i18n/messages.ts"; import * as IpcChannels from "../channels.ts"; import * as DesktopIpc from "../DesktopIpc.ts"; @@ -118,7 +120,7 @@ export const previewSnapShotConfig = DesktopIpc.makeIpcMethod({ defaultPath: Option.fromUndefinedOr(state.shortcutConfigPath), filters: [ { - name: "Desktop config", + name: m(msg("Desktop config")), extensions: state.linuxBackend === "niri" ? ["kdl"] : ["conf", "lua"], }, ], diff --git a/apps/desktop/src/ipc/methods/window.ts b/apps/desktop/src/ipc/methods/window.ts index 2545cb9dc539..abf4ec929a7b 100644 --- a/apps/desktop/src/ipc/methods/window.ts +++ b/apps/desktop/src/ipc/methods/window.ts @@ -45,8 +45,10 @@ import * as ElectronShell from "../../electron/ElectronShell.ts"; import * as ElectronTheme from "../../electron/ElectronTheme.ts"; import * as ElectronWindow from "../../electron/ElectronWindow.ts"; import * as Electron from "electron"; +import { msg } from "gt-i18n"; import * as MacPermissions from "../../permissions/MacPermissions.ts"; import { safariPermissionCheck } from "../../preview/BrowserImport/SafariPermission.ts"; +import { m } from "../../i18n/messages.ts"; import * as IpcChannels from "../channels.ts"; import * as DesktopIpc from "../DesktopIpc.ts"; import { @@ -316,7 +318,7 @@ export const pickProjectFavicon = DesktopIpc.makeIpcMethod({ multiple: false, filters: [ { - name: "Images", + name: m(msg("Images")), extensions: PROJECT_FAVICON_EXTENSIONS.map((extension) => extension.slice(1)), }, ], diff --git a/apps/desktop/src/permissions/MacPermission.ts b/apps/desktop/src/permissions/MacPermission.ts index e72d796c876a..bc9f41fe286a 100644 --- a/apps/desktop/src/permissions/MacPermission.ts +++ b/apps/desktop/src/permissions/MacPermission.ts @@ -1,3 +1,5 @@ +import { msg } from "gt-i18n"; + export const MAC_PERMISSION_SETTINGS_URLS = { "screen-recording": "x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture", @@ -8,8 +10,8 @@ export const MAC_PERMISSION_SETTINGS_URLS = { export type MacPermission = keyof typeof MAC_PERMISSION_SETTINGS_URLS; -export const MAC_PERMISSION_TITLES: Record = { - "screen-recording": "Screen Recording", - accessibility: "Accessibility", - "full-disk-access": "Full Disk Access", +export const MAC_PERMISSION_SETUP_TITLES: Record = { + "screen-recording": msg("Set up Screen Recording"), + accessibility: msg("Set up Accessibility"), + "full-disk-access": msg("Set up Full Disk Access"), }; diff --git a/apps/desktop/src/permissions/MacPermissionHelper.ts b/apps/desktop/src/permissions/MacPermissionHelper.ts index 0b50e147785f..cad9c5590609 100644 --- a/apps/desktop/src/permissions/MacPermissionHelper.ts +++ b/apps/desktop/src/permissions/MacPermissionHelper.ts @@ -1,5 +1,8 @@ // @effect-diagnostics globalTimers:off -- Poll TCC only while the native permission helper is open. import * as Electron from "electron"; +import { msg } from "gt-i18n"; + +import { m } from "../i18n/messages.ts"; import { MAC_PERMISSION_HELPER_CHANNEL } from "../ipc/channels.ts"; import { @@ -8,7 +11,7 @@ import { type SettingsWindow, } from "./MacSettingsWindow.ts"; -import { MAC_PERMISSION_TITLES, type MacPermission } from "./MacPermission.ts"; +import { MAC_PERMISSION_SETUP_TITLES, type MacPermission } from "./MacPermission.ts"; const permissionGranted = (permission: MacPermission) => { if (permission === "screen-recording") @@ -39,10 +42,10 @@ const escapeHtml = (value: string) => }); function helperHtml(permission: MacPermission, icon: string) { - const title = MAC_PERMISSION_TITLES[permission]; + const title = escapeHtml(m(MAC_PERMISSION_SETUP_TITLES[permission])); return ` -Set up ${title}
- -
↑ Drag T3 Code into the list above
- + +
${escapeHtml(m(msg("↑ Drag T3 Code into the list above")))}
+
`; } @@ -109,7 +112,7 @@ export class MacPermissionHelper { fullscreenable: false, alwaysOnTop: true, skipTaskbar: true, - title: `Set up ${MAC_PERMISSION_TITLES[permission]}`, + title: m(MAC_PERMISSION_SETUP_TITLES[permission]), webPreferences: { preload, sandbox: true, contextIsolation: true, nodeIntegration: false }, }); this.window = window; diff --git a/apps/desktop/src/preview/BrowserSession.ts b/apps/desktop/src/preview/BrowserSession.ts index 1400f2c9cbe0..c3a189f08a6d 100644 --- a/apps/desktop/src/preview/BrowserSession.ts +++ b/apps/desktop/src/preview/BrowserSession.ts @@ -1,6 +1,7 @@ import * as HostProcess from "@t3tools/shared/HostProcess"; import type { Certificate, Session, WebContents } from "electron"; import { BrowserWindow, session } from "electron"; +import { msg } from "gt-i18n"; import * as Context from "effect/Context"; import * as DateTime from "effect/DateTime"; import * as Digest from "effect/crypto/Digest"; @@ -17,6 +18,7 @@ import * as SynchronizedRef from "effect/SynchronizedRef"; import * as ElectronApp from "../electron/ElectronApp.ts"; import * as ElectronDialog from "../electron/ElectronDialog.ts"; +import { m } from "../i18n/messages.ts"; const PREVIEW_PARTITION_PREFIX = "persist:t3code-preview-"; /** Ephemeral partitions omit persist: but retain a product prefix so the webview gate recognizes them. */ @@ -85,9 +87,9 @@ const permissionOrigin = (rawUrl: string | undefined): string | null => { * prompt shows. Every other error keeps Electron's denial. */ const OVERRIDABLE_CERTIFICATE_ERRORS: ReadonlyMap = new Map([ - ["net::ERR_CERT_AUTHORITY_INVALID", "No trusted authority issued this certificate."], - ["net::ERR_CERT_COMMON_NAME_INVALID", "This certificate is not for this address."], - ["net::ERR_CERT_DATE_INVALID", "This certificate has expired or is not valid yet."], + ["net::ERR_CERT_AUTHORITY_INVALID", msg("No trusted authority issued this certificate.")], + ["net::ERR_CERT_COMMON_NAME_INVALID", msg("This certificate is not for this address.")], + ["net::ERR_CERT_DATE_INVALID", msg("This certificate has expired or is not valid yet.")], ]); /** @@ -323,9 +325,16 @@ export const make = Effect.gen(function* BrowserSessionMake() { promptPermission( requester, { - buttons: ["Open", "Cancel"], - message: `Open this ${new URL(url).protocol.slice(0, -1)} link?`, - detail: `A page in the browser wants to open another application:\n\n${truncateForPrompt(url)}`, + buttons: [ + m(msg("Open", { $context: "button, opens a link in another app" })), + m(msg("Cancel")), + ], + message: m(msg("Open this {protocol} link?"), { + protocol: new URL(url).protocol.slice(0, -1), + }), + detail: m(msg("A page in the browser wants to open another application:\n\n{url}"), { + url: truncateForPrompt(url), + }), }, (answer) => callback(answer === true), ); @@ -454,20 +463,29 @@ export const make = Effect.gen(function* BrowserSessionMake() { .showMessageBox( { type: "warning", - buttons: ["Trust and Remember", "Cancel"], + buttons: [m(msg("Trust and Remember")), m(msg("Cancel"))], defaultId: 1, cancelId: 1, signal: dismiss.signal, - message: `${host} has an untrusted certificate`, + message: m(msg("{host} has an untrusted certificate"), { host }), detail: [ - reason, + m(reason), "", - `Issued to: ${promptCertificateName(certificate.subjectName)}`, - `Issued by: ${promptCertificateName(certificate.issuerName)}`, - `Valid: ${promptCertificateDate(certificate.validStart)} – ${promptCertificateDate(certificate.validExpiry)}`, - `Fingerprint: ${approval.fingerprint}`, + m(msg("Issued to: {name}"), { + name: promptCertificateName(certificate.subjectName), + }), + m(msg("Issued by: {name}"), { name: promptCertificateName(certificate.issuerName) }), + m(msg("Valid: {start} – {end}"), { + start: promptCertificateDate(certificate.validStart), + end: promptCertificateDate(certificate.validExpiry), + }), + m(msg("Fingerprint: {fingerprint}"), { fingerprint: approval.fingerprint }), "", - "Trust it only if you know this certificate belongs to the site. Clearing this browser profile's cookies forgets it.", + m( + msg( + "Trust it only if you know this certificate belongs to the site. Clearing this browser profile's cookies forgets it.", + ), + ), ].join("\n"), }, // In the reporter's Windows test, a box owned by the host window @@ -482,8 +500,12 @@ export const make = Effect.gen(function* BrowserSessionMake() { Effect.logWarning("Failed to save a certificate approval.", { cause }).pipe( Effect.andThen( electronDialog.showErrorBox( - `Could not trust the certificate for ${host}`, - "T3 Code could not save this approval, so the page stays blocked. Check that the disk is not full and its data folder is writable, then try again.", + m(msg("Could not trust the certificate for {host}"), { host }), + m( + msg( + "T3 Code could not save this approval, so the page stays blocked. Check that the disk is not full and its data folder is writable, then try again.", + ), + ), ), ), Effect.as(false), @@ -605,8 +627,13 @@ export const make = Effect.gen(function* BrowserSessionMake() { promptPermission( requester, { - buttons: ["Allow", "Block"], - message: `${truncateForPrompt(origin)} wants to see text and images copied to the clipboard`, + buttons: [ + m(msg("Allow", { $context: "button, grants a site permission" })), + m(msg("Block", { $context: "button, denies a site permission" })), + ], + message: m(msg("{origin} wants to see text and images copied to the clipboard"), { + origin: truncateForPrompt(origin), + }), }, (answer) => { if (answer !== undefined) clipboardReadDecisions.set(origin, answer); diff --git a/apps/desktop/src/preview/Manager.ts b/apps/desktop/src/preview/Manager.ts index 32ac876996c8..1f28826bcc19 100644 --- a/apps/desktop/src/preview/Manager.ts +++ b/apps/desktop/src/preview/Manager.ts @@ -61,8 +61,10 @@ import * as Stream from "effect/Stream"; import * as Schedule from "effect/Schedule"; import * as Scope from "effect/Scope"; import * as SynchronizedRef from "effect/SynchronizedRef"; +import { msg } from "gt-i18n"; import * as DesktopEnvironment from "../app/DesktopEnvironment.ts"; +import { m } from "../i18n/messages.ts"; import * as DesktopRendererHistory from "../telemetry/DesktopRendererHistory.ts"; import { MENU_ACTION_CHANNEL, @@ -3157,7 +3159,10 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function height: PICTURE_IN_PICTURE_INITIAL_HEIGHT, minWidth: PICTURE_IN_PICTURE_MIN_WIDTH, minHeight: PICTURE_IN_PICTURE_MIN_HEIGHT, - title: title.length > 0 ? `Preview · ${title}` : "Browser preview", + title: + title.length > 0 + ? m(msg("Preview · {title}"), { title }) + : m(msg("Browser preview")), show: false, alwaysOnTop: true, autoHideMenuBar: true, diff --git a/apps/desktop/src/preview/Passkeys.ts b/apps/desktop/src/preview/Passkeys.ts index 34db1404aacb..62c47db81f53 100644 --- a/apps/desktop/src/preview/Passkeys.ts +++ b/apps/desktop/src/preview/Passkeys.ts @@ -1,6 +1,7 @@ // @effect-diagnostics globalTimers:off - Ceremonies settle inside IPC handlers, outside an Effect runtime. import type { IpcMainInvokeEvent, Session, WebContents, WebFrameMain } from "electron"; import { app, BrowserWindow, dialog, webContents as electronWebContents } from "electron"; +import { msg } from "gt-i18n"; import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; @@ -8,6 +9,7 @@ import * as Layer from "effect/Layer"; import * as Schema from "effect/Schema"; import * as DesktopEnvironment from "../app/DesktopEnvironment.ts"; +import { m } from "../i18n/messages.ts"; import { PASSKEY_CREATE_CHANNEL, PASSKEY_GET_CHANNEL } from "./GuestProtocol.ts"; import type { PasskeyBackend, PasskeyCeremonyContext } from "./PasskeyBackend.ts"; import { macPasskeyBackend } from "./PasskeyBackendMac.ts"; @@ -53,7 +55,7 @@ const notAllowed: PasskeyCeremonyResult = { success: false, error: "NotAllowedEr const accountLabel = (account: Electron.WebAuthnAccount) => account.displayName && account.name && account.displayName !== account.name ? `${account.displayName} (${account.name})` - : (account.name ?? account.displayName ?? "Unnamed passkey"); + : (account.name ?? account.displayName ?? m(msg("Unnamed passkey"))); const ownerWindow = (frame: WebFrameMain | null) => { const contents = frame ? electronWebContents.fromFrame(frame) : undefined; @@ -67,9 +69,9 @@ const chooseAccount = async (details: Electron.SelectWebauthnAccountDetails) => if (details.accounts.length === 1) return onlyAccount?.credentialId; const options: Electron.MessageBoxOptions = { type: "none", - message: "Choose a passkey", + message: m(msg("Choose a passkey")), detail: details.relyingPartyId, - buttons: [...details.accounts.map(accountLabel), "Cancel"], + buttons: [...details.accounts.map(accountLabel), m(msg("Cancel"))], cancelId: details.accounts.length, defaultId: 0, noLink: true, diff --git a/apps/desktop/src/window/DesktopApplicationMenu.ts b/apps/desktop/src/window/DesktopApplicationMenu.ts index b4025ebfde8e..4c5475f8a602 100644 --- a/apps/desktop/src/window/DesktopApplicationMenu.ts +++ b/apps/desktop/src/window/DesktopApplicationMenu.ts @@ -5,11 +5,15 @@ import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; import * as Electron from "electron"; +import { msg } from "gt-i18n"; import { makeComponentLogger } from "../app/DesktopObservability.ts"; +import * as ElectronApp from "../electron/ElectronApp.ts"; import * as ElectronDialog from "../electron/ElectronDialog.ts"; import * as ElectronMenu from "../electron/ElectronMenu.ts"; import * as DesktopEnvironment from "../app/DesktopEnvironment.ts"; +import { applyLanguage, m, onLocaleChange } from "../i18n/messages.ts"; +import * as DesktopClientSettings from "../settings/DesktopClientSettings.ts"; import * as DesktopUpdates from "../updates/DesktopUpdates.ts"; import * as DesktopWindow from "./DesktopWindow.ts"; @@ -64,9 +68,6 @@ const runMainContentsCommand = Effect.fn("desktop.menu.runMainContentsCommand")( yield* desktopWindow.runMainContentsCommand(command); }); -const describeUpdate = (version: string | null) => - version === null ? "A new version of T3 Code" : `T3 Code ${version}`; - const checkForUpdatesFromMenu = Effect.gen(function* () { const updates = yield* DesktopUpdates.DesktopUpdates; const electronDialog = yield* ElectronDialog.ElectronDialog; @@ -76,17 +77,27 @@ const checkForUpdatesFromMenu = Effect.gen(function* () { if (updateState.status === "up-to-date") { yield* electronDialog.showMessageBox({ type: "info", - title: "You're up to date!", - message: `T3 Code ${updateState.currentVersion} is currently the newest version available.`, - buttons: ["OK"], + title: m(msg("You're up to date!")), + message: m(msg("T3 Code {version} is currently the newest version available."), { + version: updateState.currentVersion, + }), + buttons: [m(msg("OK"))], }); } else if (updateState.status === "available") { const { response } = yield* electronDialog.showMessageBox({ type: "info", - title: "Update available", - message: `${describeUpdate(updateState.availableVersion)} is available.`, - detail: `You're running T3 Code ${updateState.currentVersion}.`, - buttons: ["Download", "Later"], + title: m(msg("Update available")), + message: + updateState.availableVersion === null + ? m(msg("A new version of T3 Code is available.")) + : m(msg("T3 Code {version} is available."), { version: updateState.availableVersion }), + detail: m(msg("You're running T3 Code {version}."), { + version: updateState.currentVersion, + }), + buttons: [ + m(msg("Download", { $context: "button, downloads an app update" })), + m(msg("Later")), + ], defaultId: 0, cancelId: 1, }); @@ -94,17 +105,26 @@ const checkForUpdatesFromMenu = Effect.gen(function* () { } else if (updateState.status === "downloading") { yield* electronDialog.showMessageBox({ type: "info", - title: "Update downloading", - message: `${describeUpdate(updateState.availableVersion)} is already downloading.`, - buttons: ["OK"], + title: m(msg("Update downloading")), + message: + updateState.availableVersion === null + ? m(msg("A new version of T3 Code is already downloading.")) + : m(msg("T3 Code {version} is already downloading."), { + version: updateState.availableVersion, + }), + buttons: [m(msg("OK"))], }); } else if (updateState.status === "downloaded") { + const version = updateState.downloadedVersion ?? updateState.availableVersion; const { response } = yield* electronDialog.showMessageBox({ type: "info", - title: "Update ready", - message: `${describeUpdate(updateState.downloadedVersion ?? updateState.availableVersion)} is ready to install.`, - detail: "T3 Code will restart to install it. Any running tasks will be interrupted.", - buttons: ["Restart", "Later"], + title: m(msg("Update ready")), + message: + version === null + ? m(msg("A new version of T3 Code is ready to install.")) + : m(msg("T3 Code {version} is ready to install."), { version }), + detail: m(msg("T3 Code will restart to install it. Any running tasks will be interrupted.")), + buttons: [m(msg("Restart", { $context: "button, restarts the app" })), m(msg("Later"))], defaultId: 0, cancelId: 1, }); @@ -112,10 +132,10 @@ const checkForUpdatesFromMenu = Effect.gen(function* () { } else if (updateState.status === "error") { yield* electronDialog.showMessageBox({ type: "warning", - title: "Update check failed", - message: "Could not check for updates.", - detail: updateState.message ?? "An unknown error occurred. Please try again later.", - buttons: ["OK"], + title: m(msg("Update check failed")), + message: m(msg("Could not check for updates.")), + detail: updateState.message ?? m(msg("An unknown error occurred. Please try again later.")), + buttons: [m(msg("OK"))], }); } }).pipe(Effect.withSpan("desktop.menu.checkForUpdates")); @@ -130,10 +150,10 @@ const handleCheckForUpdatesMenuClick = Effect.gen(function* () { }); yield* electronDialog.showMessageBox({ type: "info", - title: "Updates unavailable", - message: "Automatic updates are not available right now.", + title: m(msg("Updates unavailable")), + message: m(msg("Automatic updates are not available right now.")), detail: disabledReason.value, - buttons: ["OK"], + buttons: [m(msg("OK"))], }); return; } @@ -148,8 +168,11 @@ const handleCheckForUpdatesMenuClick = Effect.gen(function* () { export const make = Effect.gen(function* () { const electronMenu = yield* ElectronMenu.ElectronMenu; const environment = yield* DesktopEnvironment.DesktopEnvironment; + const electronApp = yield* ElectronApp.ElectronApp; + const clientSettings = yield* Effect.serviceOption(DesktopClientSettings.DesktopClientSettings); const context = yield* Effect.context(); const runPromise = Effect.runPromiseWith(context); + const runFork = Effect.runForkWith(context); const runMenuEffect = ( action: string, @@ -195,45 +218,45 @@ export const make = Effect.gen(function* () { template.push({ label: environment.displayName, submenu: [ - { role: "about", label: `About ${environment.displayName}` }, + { role: "about", label: m(msg("About {appName}"), { appName: environment.displayName }) }, { - label: "Check for Updates...", + label: m(msg("Check for Updates...")), click: checkForUpdatesClick, }, { type: "separator" }, { - label: "Settings...", + label: m(msg("Settings...")), accelerator: "CmdOrCtrl+,", click: settingsClick, }, { type: "separator" }, { role: "services" }, { type: "separator" }, - { role: "hide", label: `Hide ${environment.displayName}` }, + { role: "hide", label: m(msg("Hide {appName}"), { appName: environment.displayName }) }, { role: "hideOthers" }, { role: "unhide" }, { type: "separator" }, - { role: "quit", label: `Quit ${environment.displayName}` }, + { role: "quit", label: m(msg("Quit {appName}"), { appName: environment.displayName }) }, ], }); } template.push( { - label: "File", + label: m(msg("File", { $context: "menu bar title" })), submenu: [ ...(environment.platform === "darwin" ? [] : [ { - label: "Settings...", + label: m(msg("Settings...")), accelerator: "CmdOrCtrl+,", click: settingsClick, }, { type: "separator" as const }, ]), { - label: "Close Developer Tools", + label: m(msg("Close Developer Tools")), accelerator: "CmdOrCtrl+W", visible: false, click: () => { @@ -245,12 +268,12 @@ export const make = Effect.gen(function* () { }, // Cmd/Ctrl+W belongs to the renderer's tab close; it must never close the window. environment.platform === "darwin" - ? { label: "Close Window", click: (_item, window) => window?.close() } + ? { label: m(msg("Close Window")), click: (_item, window) => window?.close() } : { role: "quit" }, ], }, { - label: "Edit", + label: m(msg("Edit", { $context: "menu bar title" })), submenu: [ { role: "undo" }, { role: "redo" }, @@ -259,7 +282,7 @@ export const make = Effect.gen(function* () { { role: "copy" }, { role: "paste" }, { - label: "Paste as Text", + label: m(msg("Paste as Text")), accelerator: "CmdOrCtrl+Shift+V", click: pasteAsTextClick, }, @@ -270,7 +293,7 @@ export const make = Effect.gen(function* () { ? [ { type: "separator" as const }, { - label: "Speech", + label: m(msg("Speech", { $context: "menu, text-to-speech" })), submenu: [{ role: "startSpeaking" as const }, { role: "stopSpeaking" as const }], }, ] @@ -278,25 +301,29 @@ export const make = Effect.gen(function* () { ], }, { - label: "View", + label: m(msg("View", { $context: "menu bar title" })), submenu: [ /* Native reload/DevTools/zoom roles target focused guests; these commands must target the app. */ - { label: "Reload", accelerator: "CmdOrCtrl+R", click: mainContentsClick("reload") }, { - label: "Force Reload", + label: m(msg("Reload")), + accelerator: "CmdOrCtrl+R", + click: mainContentsClick("reload"), + }, + { + label: m(msg("Force Reload")), accelerator: "Shift+CmdOrCtrl+R", click: mainContentsClick("forceReload"), }, { - label: "Toggle Developer Tools", + label: m(msg("Toggle Developer Tools")), accelerator: environment.platform === "darwin" ? "Alt+Command+I" : "Ctrl+Shift+I", click: mainContentsClick("toggleDevTools"), }, { type: "separator" }, - { label: "Actual Size", accelerator: "CmdOrCtrl+0", click: zoomClick("reset") }, - { label: "Zoom In", accelerator: "CmdOrCtrl+=", click: zoomClick("in") }, + { label: m(msg("Actual Size")), accelerator: "CmdOrCtrl+0", click: zoomClick("reset") }, + { label: m(msg("Zoom In")), accelerator: "CmdOrCtrl+=", click: zoomClick("in") }, { - label: "Zoom In", + label: m(msg("Zoom In")), accelerator: "CmdOrCtrl+Plus", visible: false, click: zoomClick("in"), @@ -304,29 +331,29 @@ export const make = Effect.gen(function* () { ...(environment.platform === "darwin" ? [ { - label: "Zoom In", + label: m(msg("Zoom In")), accelerator: "CmdOrCtrl+Shift+=", visible: false, click: zoomClick("in"), }, ] : []), - { label: "Zoom Out", accelerator: "CmdOrCtrl+-", click: zoomClick("out") }, + { label: m(msg("Zoom Out")), accelerator: "CmdOrCtrl+-", click: zoomClick("out") }, // Keypad codes do not match number-row accelerators. { - label: "Actual Size", + label: m(msg("Actual Size")), accelerator: "CmdOrCtrl+num0", visible: false, click: zoomClick("reset"), }, { - label: "Zoom In", + label: m(msg("Zoom In")), accelerator: "CmdOrCtrl+numadd", visible: false, click: zoomClick("in"), }, { - label: "Zoom Out", + label: m(msg("Zoom Out")), accelerator: "CmdOrCtrl+numsub", visible: false, click: zoomClick("out"), @@ -350,7 +377,7 @@ export const make = Effect.gen(function* () { role: "help", submenu: [ { - label: "Check for Updates...", + label: m(msg("Check for Updates...")), click: checkForUpdatesClick, }, ], @@ -360,8 +387,29 @@ export const make = Effect.gen(function* () { yield* electronMenu.setApplicationMenu(template); }).pipe(Effect.withSpan("desktop.menu.configure")); + // Load the saved language before the first build so the menu never starts in English. + const applySavedLanguage = Effect.gen(function* () { + if (Option.isNone(clientSettings)) return; + const saved = yield* clientSettings.value.get.pipe(Effect.orElseSucceed(() => Option.none())); + if (Option.isSome(saved)) { + yield* applyLanguage(saved.value.language).pipe( + Effect.provideService(ElectronApp.ElectronApp, electronApp), + ); + } + }); + + let rebuildsOnLocaleChange = false; return DesktopApplicationMenu.of({ - configure, + configure: applySavedLanguage.pipe( + Effect.andThen(configure), + Effect.tap(() => + Effect.sync(() => { + if (rebuildsOnLocaleChange) return; + rebuildsOnLocaleChange = true; + onLocaleChange(() => runFork(configure)); + }), + ), + ), }); }); diff --git a/apps/desktop/src/window/DesktopWindow.ts b/apps/desktop/src/window/DesktopWindow.ts index 4628be44d5ce..556853a6cc5f 100644 --- a/apps/desktop/src/window/DesktopWindow.ts +++ b/apps/desktop/src/window/DesktopWindow.ts @@ -9,6 +9,7 @@ import * as Schema from "effect/Schema"; import * as Semaphore from "effect/Semaphore"; import * as Electron from "electron"; +import { msg } from "gt-i18n"; import { type DesktopSnapShotEvent, DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts"; @@ -39,6 +40,7 @@ import * as PreviewPasskeys from "../preview/Passkeys.ts"; import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts"; import * as DesktopClientSettings from "../settings/DesktopClientSettings.ts"; import * as ElectronApp from "../electron/ElectronApp.ts"; +import { m } from "../i18n/messages.ts"; import * as DesktopRendererHistory from "../telemetry/DesktopRendererHistory.ts"; import { makeQuitShortcutHandler } from "./QuitHold.ts"; import { copyContextMenuImage } from "./ContextMenuImage.ts"; @@ -669,7 +671,7 @@ export const make = Effect.gen(function* () { }); } if (params.dictionarySuggestions.length === 0) { - menuTemplate.push({ label: "No suggestions", enabled: false }); + menuTemplate.push({ label: m(msg("No suggestions")), enabled: false }); } menuTemplate.push({ type: "separator" }); } @@ -677,7 +679,7 @@ export const make = Effect.gen(function* () { if (Option.isSome(ElectronShell.parseSafeExternalUrl(params.linkURL))) { menuTemplate.push( { - label: "Copy Link", + label: m(msg("Copy Link")), click: () => { void runPromise(electronShell.copyText(params.linkURL)); }, @@ -690,7 +692,7 @@ export const make = Effect.gen(function* () { if (Option.isSome(mailtoAddress)) { menuTemplate.push( { - label: "Copy Email Address", + label: m(msg("Copy Email Address")), click: () => { void runPromise(electronShell.copyText(mailtoAddress.value)); }, @@ -701,7 +703,7 @@ export const make = Effect.gen(function* () { if (params.mediaType === "image") { menuTemplate.push({ - label: "Copy Image", + label: m(msg("Copy Image")), click: () => { void runPromise( Effect.tryPromise({ diff --git a/apps/mobile/gt.config.json b/apps/mobile/gt.config.json index 707f56d736ce..2bd924f11922 100644 --- a/apps/mobile/gt.config.json +++ b/apps/mobile/gt.config.json @@ -1,6 +1,12 @@ { "defaultLocale": "en", - "locales": ["es", "zh", "pt-BR", "fr", "de", "ja", "ko", "ru"], + "locales": ["es", "zh", "pt-BR", "fr", "de", "ja", "ko", "ru", "sv"], + "src": [ + "src/**/*.{ts,tsx}", + "../../packages/client-runtime/src/**/*.{ts,tsx}", + "../../packages/shared/src/**/*.{ts,tsx}", + "!**/*.test.{ts,tsx}" + ], "files": { "gt": { "output": "src/i18n/translations/[locale].json" diff --git a/apps/mobile/package.json b/apps/mobile/package.json index 2ab0e38d89e2..d09a4972312d 100644 --- a/apps/mobile/package.json +++ b/apps/mobile/package.json @@ -63,6 +63,7 @@ "@formatjs/intl-displaynames": "6.8.13", "@formatjs/intl-getcanonicallocales": "2.5.6", "@formatjs/intl-locale": "4.2.13", + "@formatjs/intl-pluralrules": "5.4.6", "@legendapp/list": "catalog:", "@material/material-color-utilities": "0.3.0", "@pierre/diffs": "catalog:", diff --git a/apps/mobile/src/App.tsx b/apps/mobile/src/App.tsx index 84de2bf777cf..16a77b049efa 100644 --- a/apps/mobile/src/App.tsx +++ b/apps/mobile/src/App.tsx @@ -4,6 +4,7 @@ import { installThreadOutboxDelivery } from "./state/threadOutboxDelivery"; import * as Linking from "expo-linking"; import * as SplashScreen from "expo-splash-screen"; import { requireNativeModule } from "expo"; +import { useLocale } from "gt-react-native"; import { useEffect, useRef, useState } from "react"; import { Platform, StatusBar } from "react-native"; import { GestureHandlerRootView } from "react-native-gesture-handler"; @@ -39,6 +40,7 @@ import { } from "./features/agent-awareness/notificationNavigation"; import { installAppShortcuts, + republishAppShortcuts, recordAppShortcutNavigationState, } from "./features/shortcuts/appShortcutsRuntime"; import { @@ -47,6 +49,8 @@ import { useAppearancePreferences, } from "./features/settings/appearance/AppearancePreferencesProvider"; import { RootStack, rootPathnameFromState, workspaceLocationFromState } from "./Stack"; +import { I18nProvider } from "./i18n/I18nProvider"; +import { DEFAULT_LOCALE } from "./i18n/locales"; import { appAtomRegistry } from "./state/atom-registry"; import { subscribeComposerDraftModelReconciliation } from "./state/use-composer-drafts"; import { environmentThreadShells, threadEnvironment } from "./state/threads"; @@ -254,12 +258,27 @@ function SplashScreenCoordinator() { return null; } +function QuickActionsLanguage() { + const locale = useLocale(); + // Shortcuts published before the catalog loaded are English. + const publishedLocale = useRef(DEFAULT_LOCALE); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- the launcher keeps quick action titles from the last publish, so a language switch republishes them + useEffect(() => { + if (Platform.OS !== "android" || publishedLocale.current === locale) return; + publishedLocale.current = locale; + republishAppShortcuts(); + }, [locale]); + return null; +} + export default function App() { return ( - + + + @@ -281,6 +300,7 @@ function AppContent() { return ( <> + diff --git a/apps/mobile/src/Stack.tsx b/apps/mobile/src/Stack.tsx index 7b81d0880a40..ca77e1e641d7 100644 --- a/apps/mobile/src/Stack.tsx +++ b/apps/mobile/src/Stack.tsx @@ -12,6 +12,7 @@ import { useNavigation, } from "@react-navigation/native"; import { createNativeStackScreen } from "@react-navigation/native-stack"; +import { msg, T, useGT, useMessages } from "gt-react-native"; import type { ReactNode } from "react"; import { Platform, Pressable, ScrollView, StyleSheet, useWindowDimensions } from "react-native"; import { useResolveClassNames } from "uniwind"; @@ -152,7 +153,63 @@ import { useNativeLayoutMetrics } from "./native/native-layout-metrics"; import { isPresentedRoute } from "./native/workspace-stack-projection"; import { workspaceDetailRouter } from "./features/layout/workspace/workspace-detail-selection"; -const settingsPage = (title: string) => pageRoute({ title, itemStyle: "standard" }); +const settingsPage = () => pageRoute({ itemStyle: "standard" }); + +const { title: _compactBrandTitle, ...compactBrandHeaderOptions } = getCompactBrandHeaderOptions(); + +// Resolved in the rendered Navigator's screenOptions so each header title follows the UI language; +// route options stay plain objects because registerPresentedRoutes reads them at load. +const ROUTE_TITLES: Readonly> = { + Settings: msg("Settings"), + SettingsEnvironments: msg("Environments"), + SettingsEnvironmentDetail: msg("Environment"), + SettingsEnvironmentNewThreads: msg("Threads"), + SettingsEnvironmentSourceControl: msg("Source control & issues"), + SettingsSourceControlProvider: msg("Provider", { + $context: "settings page of one source control provider", + }), + SettingsIssueTracker: msg("Issue tracker"), + SettingsEnvironmentAgentBehavior: msg("Threads"), + SettingsWorktrees: msg("Worktrees"), + SettingsLabs: msg("Labs"), + SettingsProviderAccounts: msg("Providers"), + SettingsEnvironmentMaintenance: msg("Maintenance"), + SettingsNotifications: msg("Notifications"), + SettingsThreads: msg("Threads"), + SettingsAbout: msg("About"), + SettingsEnvironmentNew: msg("Add Environment"), + SettingsArchive: msg("Archive", { $context: "noun, settings page of archived threads" }), + SettingsNavigation: msg("Navigation tabs"), + SettingsAppearance: msg("Appearance"), + SettingsProjectGrouping: msg("General"), + SettingsOrganization: msg("General"), + SettingsLanguage: msg("Language"), + SettingsProjectOverview: msg("Projects"), + SettingsKeyboard: msg("Keyboard"), + SettingsVoice: msg("Voice"), + SettingsFollowUp: msg("Chat", { $context: "noun, settings page title" }), + SettingsScheduledTasks: msg("Scheduled tasks"), + SettingsScheduledTaskNew: msg("New scheduled task"), + SettingsScheduledTaskEdit: msg("Edit scheduled task"), + SettingsScheduledTaskBranch: msg("Base branch"), + SettingsScheduledTaskThread: msg("Destination"), + SettingsClientStorage: msg("Client Storage"), + SettingsDiagnostics: msg("Diagnostics"), + SettingsUsageAccount: msg("Account"), + SettingsOpenSourceLicenses: msg("Open source licenses"), + SettingsOpenSourceLicense: msg("License notice"), + SettingsUsage: msg("Usage"), + ComponentCatalog: msg("UI components"), + NewTaskProject: msg("Choose project"), + NewTaskEnvironment: msg("Environment"), + NewTaskBranch: msg("Branch"), + AddProject: msg("Add project"), + ThreadFiles: msg("Files"), + SettingsLegal: msg("Legal"), + ConnectOnboarding: msg("Set up {product}", { product: "T3 Connect" }), + Connections: msg("Environments"), + ConnectionsNew: msg("Add Environment"), +}; // Thread settings keep the Duo's vertical bar so cancel, search, filter and confirm sit in the // rail. The picker stack spans the sheet so its header reaches the rail, and insets its content. @@ -172,128 +229,128 @@ const SETTINGS_SCREENS = { screen: SettingsRouteScreen, linking: "settings", options: { - ...pageRoute({ title: "Settings", itemStyle: "standard", root: true }), + ...pageRoute({ itemStyle: "standard", root: true }), ...(Platform.OS === "android" ? { animation: "none" as const } : {}), }, }), SettingsEnvironments: createNativeStackScreen({ screen: SettingsEnvironmentsRouteScreen, linking: "settings/environments", - options: settingsPage("Environments"), + options: settingsPage(), }), SettingsEnvironmentDetail: createNativeStackScreen({ screen: SettingsEnvironmentDetailRouteScreen, linking: "settings/environments/:environmentId", - options: settingsPage("Environment"), + options: settingsPage(), }), // Old links to New threads and Agent behavior open Threads, which absorbed them. SettingsEnvironmentNewThreads: createNativeStackScreen({ screen: SettingsThreadsRouteScreen, linking: "settings/new-threads", - options: settingsPage("Threads"), + options: settingsPage(), }), SettingsEnvironmentSourceControl: createNativeStackScreen({ screen: SettingsEnvironmentSourceControlRouteScreen, linking: "settings/source-control", - options: settingsPage("Source control & issues"), + options: settingsPage(), }), SettingsSourceControlProvider: createNativeStackScreen({ screen: SettingsSourceControlProviderRouteScreen, - options: settingsPage("Provider"), + options: settingsPage(), }), SettingsIssueTracker: createNativeStackScreen({ screen: SettingsIssueTrackerRouteScreen, - options: settingsPage("Issue tracker"), + options: settingsPage(), }), SettingsEnvironmentAgentBehavior: createNativeStackScreen({ screen: SettingsThreadsRouteScreen, linking: "settings/agent-behavior", - options: settingsPage("Threads"), + options: settingsPage(), }), SettingsWorktrees: createNativeStackScreen({ screen: SettingsWorktreesRouteScreen, linking: "settings/worktrees", - options: settingsPage("Worktrees"), + options: settingsPage(), }), SettingsLabs: createNativeStackScreen({ screen: SettingsLabsRouteScreen, linking: "settings/labs", - options: settingsPage("Labs"), + options: settingsPage(), }), SettingsProviderAccounts: createNativeStackScreen({ screen: SettingsProviderAccountsRouteScreen, linking: "settings/provider-accounts", - options: settingsPage("Providers"), + options: settingsPage(), }), SettingsEnvironmentMaintenance: createNativeStackScreen({ screen: SettingsEnvironmentMaintenanceRouteScreen, linking: "settings/maintenance", - options: settingsPage("Maintenance"), + options: settingsPage(), }), SettingsNotifications: createNativeStackScreen({ screen: SettingsNotificationsRouteScreen, linking: "settings/notifications", - options: settingsPage("Notifications"), + options: settingsPage(), }), SettingsThreads: createNativeStackScreen({ screen: SettingsThreadsRouteScreen, linking: "settings/thread-preferences", - options: settingsPage("Threads"), + options: settingsPage(), }), SettingsAbout: createNativeStackScreen({ screen: SettingsAboutRouteScreen, linking: "settings/about", - options: settingsPage("About"), + options: settingsPage(), }), SettingsEnvironmentNew: createNativeStackScreen({ screen: ConnectionsNewRouteScreen, linking: "settings/environment-new", - options: settingsPage("Add Environment"), + options: settingsPage(), }), SettingsArchive: createNativeStackScreen({ screen: ArchivedThreadsRouteScreen, linking: "settings/archive", - options: settingsPage("Archive"), + options: settingsPage(), }), SettingsNavigation: createNativeStackScreen({ screen: SettingsNavigationRouteScreen, linking: "settings/navigation-tabs", - options: settingsPage("Navigation tabs"), + options: settingsPage(), }), SettingsAppearance: createNativeStackScreen({ screen: SettingsAppearanceRouteScreen, linking: "settings/appearance", - options: settingsPage("Appearance"), + options: settingsPage(), }), SettingsProjectGrouping: createNativeStackScreen({ screen: SettingsProjectGroupingRouteScreen, linking: "settings/project-grouping", - options: settingsPage("General"), + options: settingsPage(), }), SettingsOrganization: createNativeStackScreen({ screen: SettingsProjectGroupingRouteScreen, linking: "settings/organization", - options: settingsPage("General"), + options: settingsPage(), }), SettingsLanguage: createNativeStackScreen({ screen: SettingsLanguageRouteScreen, linking: "settings/language", - options: settingsPage("Language"), + options: settingsPage(), }), SettingsProjectOverview: createNativeStackScreen({ screen: SettingsProjectOverviewRouteScreen, linking: "settings/project", - options: settingsPage("Projects"), + options: settingsPage(), }), SettingsKeyboard: createNativeStackScreen({ screen: SettingsKeyboardRouteScreen, linking: "settings/keyboard", - options: settingsPage("Keyboard"), + options: settingsPage(), }), SettingsVoice: createNativeStackScreen({ screen: SettingsVoiceRouteScreen, linking: { path: "settings/voice", alias: ["settings/microphone"] }, - options: settingsPage("Voice"), + options: settingsPage(), }), SettingsVoiceModels: createNativeStackScreen({ screen: SettingsVoiceModelsRouteScreen, @@ -302,32 +359,32 @@ const SETTINGS_SCREENS = { SettingsFollowUp: createNativeStackScreen({ screen: SettingsFollowUpRouteScreen, linking: "settings/follow-ups", - options: settingsPage("Chat"), + options: settingsPage(), }), SettingsScheduledTasks: createNativeStackScreen({ screen: SettingsScheduledTasksRouteScreen, linking: "settings/scheduled-tasks", options: { - ...settingsPage("Scheduled tasks"), + ...settingsPage(), headerTitleStyle: { fontSize: 16, fontWeight: "800" }, }, }), SettingsScheduledTaskNew: createNativeStackScreen({ screen: SettingsScheduledTaskNewRouteScreen, linking: "settings/scheduled-tasks/new", - options: settingsPage("New scheduled task"), + options: settingsPage(), }), SettingsScheduledTaskEdit: createNativeStackScreen({ screen: SettingsScheduledTaskEditRouteScreen, - options: settingsPage("Edit scheduled task"), + options: settingsPage(), }), SettingsScheduledTaskBranch: createNativeStackScreen({ screen: ScheduledTaskBranchPickerRouteScreen, - options: settingsPage("Base branch"), + options: settingsPage(), }), SettingsScheduledTaskThread: createNativeStackScreen({ screen: ScheduledTaskThreadPickerRouteScreen, - options: settingsPage("Destination"), + options: settingsPage(), }), SettingsScheduledTaskModel: createNativeStackScreen({ screen: ScheduledTaskModelPickerRouteScreen, @@ -336,33 +393,33 @@ const SETTINGS_SCREENS = { SettingsClientStorage: createNativeStackScreen({ screen: SettingsClientStorageRouteScreen, linking: "settings/client-storage", - options: settingsPage("Client Storage"), + options: settingsPage(), }), SettingsDiagnostics: createNativeStackScreen({ screen: SettingsDiagnosticsRouteScreen, linking: "settings/diagnostics", - options: settingsPage("Diagnostics"), + options: settingsPage(), }), // These params snapshot the tap time, local filters, and freshly aggregated pools. // A linking path would round-trip them as URL query strings and preserve stale values. SettingsUsageAccount: createNativeStackScreen({ screen: UsageLimitAccountScreen, - options: settingsPage("Account"), + options: settingsPage(), }), SettingsOpenSourceLicenses: createNativeStackScreen({ screen: SettingsOpenSourceLicensesRouteScreen, linking: "settings/open-source-licenses", - options: settingsPage("Open source licenses"), + options: settingsPage(), }), SettingsOpenSourceLicense: createNativeStackScreen({ screen: SettingsOpenSourceLicenseRouteScreen, linking: "settings/open-source-licenses/:entryKey", - options: settingsPage("License notice"), + options: settingsPage(), }), SettingsUsage: createNativeStackScreen({ screen: UsageRouteScreen, linking: "settings/usage", - options: settingsPage("Usage"), + options: settingsPage(), }), SettingsAuth: createNativeStackScreen({ screen: SettingsAuthRouteScreen, @@ -477,13 +534,15 @@ function NotFoundScreen() { style={[{ flex: 1 }, screenBgStyle]} > - Route not found + Route not found navigation.dispatch(StackActions.replace("Home"))} > - Return home + + Return home + ); @@ -494,16 +553,13 @@ const RootStackConfig = createWorkspaceStackNavigator({ UNSTABLE_router: workspaceDetailRouter, // React Navigation calls layouts inline; compiled components would share the navigator's memo cache. layout: (props) => , - screenOptions: { - headerShown: false, - }, + screenOptions: { headerShown: false }, screens: { ...(__DEV__ ? { ComponentCatalog: createNativeStackScreen({ screen: ComponentCatalogScreen, linking: "dev/components", - options: { title: "UI components" }, }), } : {}), @@ -518,7 +574,7 @@ const RootStackConfig = createWorkspaceStackNavigator({ options: { ...pageRoute({ duoMinimize: "never", root: true }), contentStyle: { backgroundColor: "transparent" }, - ...getCompactBrandHeaderOptions(), + ...compactBrandHeaderOptions, }, }), PullRequest: createNativeStackScreen({ @@ -598,23 +654,23 @@ const RootStackConfig = createWorkspaceStackNavigator({ NewTaskProject: createNativeStackScreen({ screen: NewTaskRouteScreen, linking: { path: "new", alias: ["new/project"] }, - options: pageRoute({ title: "Choose project" }), + options: pageRoute(), }), NewTaskEnvironment: createNativeStackScreen({ linking: "new/draft/environment", screen: NewTaskEnvironmentPickerRouteScreen, - options: pageRoute({ title: "Environment" }), + options: pageRoute(), }), NewTaskBranch: createNativeStackScreen({ linking: "new/draft/branch", screen: NewTaskBranchPickerRouteScreen, - options: pageRoute({ title: "Branch" }), + options: pageRoute(), }), AddProject: createNativeStackScreen({ linking: "new/add-project", screen: AddProjectSourceRoute, - options: pageRoute({ title: "Add project" }), + options: pageRoute(), }), AddProjectRepository: createNativeStackScreen({ linking: "new/add-project/repository", @@ -688,7 +744,7 @@ const RootStackConfig = createWorkspaceStackNavigator({ ThreadFiles: createNativeStackScreen({ screen: ThreadFilesTreeScreen, linking: `${THREAD_LINKING_PREFIX}/files`, - options: pageRoute({ title: "Files" }), + options: pageRoute(), }), ThreadFile: createNativeStackScreen({ screen: ThreadFileScreen, @@ -750,13 +806,12 @@ const RootStackConfig = createWorkspaceStackNavigator({ SettingsLegal: createNativeStackScreen({ screen: SettingsLegalRouteScreen, linking: "settings/legal", - options: modalRoute({ header: "solid", title: "Legal" }), + options: modalRoute({ header: "solid" }), }), ConnectOnboarding: createNativeStackScreen({ screen: ConnectOnboardingRouteScreen, linking: "connect-onboarding", options: sheetRoute({ - title: "Set up T3 Connect", header: "solid", detent: 0.6, androidMaxDetent: 0.95, @@ -765,12 +820,12 @@ const RootStackConfig = createWorkspaceStackNavigator({ Connections: createNativeStackScreen({ screen: ConnectionsRouteScreen, linking: "connections", - options: sheetRoute({ title: "Environments", detent: 0.55, maxDetent: 0.7, android: "card" }), + options: sheetRoute({ detent: 0.55, maxDetent: 0.7, android: "card" }), }), ConnectionsNew: createNativeStackScreen({ screen: ConnectionsNewRouteScreen, linking: "connections/new", - options: sheetRoute({ title: "Add Environment", detent: 0.55, maxDetent: 0.7 }), + options: sheetRoute({ detent: 0.55, maxDetent: 0.7 }), }), NotFound: createNativeStackScreen({ screen: NotFoundScreen, @@ -797,15 +852,19 @@ function GuardedScreenLayout(props: { function ScreenRenderFallback(props: RenderFailureProps & { readonly routeName: string }) { const navigation = useNavigation(); + const gt = useGT(); const exit = navigation.canGoBack() - ? { label: "Go back", onPress: () => navigation.goBack() } + ? { label: gt("Go back"), onPress: () => navigation.goBack() } : props.routeName === "Home" ? // Home itself failed, and the Settings list renders inside it; open a Settings page. { - label: "Open settings", + label: gt("Open settings"), onPress: () => openSettings(navigation, DEFAULT_SETTINGS_PAGE), } - : { label: "Return home", onPress: () => navigation.dispatch(StackActions.replace("Home")) }; + : { + label: gt("Return home"), + onPress: () => navigation.dispatch(StackActions.replace("Home")), + }; return ; } @@ -821,22 +880,32 @@ export const RootStack = RootStackConfig.with(function AdaptiveRootStack({ Navig const { width, height } = useWindowDimensions(); const nativeMetrics = useNativeLayoutMetrics(); const usesSplitView = deriveLayout({ width, height, nativeMetrics }).usesSplitView; + const resolve = useMessages(); /* oxlint-disable react/no-unstable-nested-components -- React Navigation invokes screenLayout as a render callback. */ return ( } - screenOptions={({ route, navigation }) => - Platform.OS === "android" - ? { - animation: androidWorkspaceDestinationAnimation( - route, - navigation.getState().routes, - usesSplitView, - ), - } - : {} - } + screenOptions={({ route, navigation }) => { + const title = + route.name === "Home" + ? getCompactBrandHeaderOptions(undefined, resolve).title + : ROUTE_TITLES[route.name] === undefined + ? undefined + : resolve(ROUTE_TITLES[route.name]); + return { + ...(title === undefined ? {} : { title }), + ...(Platform.OS === "android" + ? { + animation: androidWorkspaceDestinationAnimation( + route, + navigation.getState().routes, + usesSplitView, + ), + } + : {}), + }; + }} /> ); diff --git a/apps/mobile/src/components/BrandMark.tsx b/apps/mobile/src/components/BrandMark.tsx index 28d71929bddb..b51d0b4a754b 100644 --- a/apps/mobile/src/components/BrandMark.tsx +++ b/apps/mobile/src/components/BrandMark.tsx @@ -1,5 +1,6 @@ import Constants from "expo-constants"; import { Image } from "expo-image"; +import { msg, T, useMessages } from "gt-react-native"; import { View } from "react-native"; import { AppText as Text } from "./ui/AppText"; @@ -7,12 +8,17 @@ import { T3_CODE_BRAND_MARK_SOURCE } from "./brandAssets"; const appVariant = Constants.expoConfig?.extra?.appVariant; const DEFAULT_STAGE_LABEL = - appVariant === "development" ? "Dev" : appVariant === "preview" ? "Preview" : "Beta"; + appVariant === "development" + ? msg("Dev", { $context: "app release stage badge" }) + : appVariant === "preview" + ? msg("Preview", { $context: "app release stage badge" }) + : msg("Beta", { $context: "app release stage badge" }); export function BrandMark(props: { readonly compact?: boolean; readonly stageLabel?: string }) { + const m = useMessages(); const compact = props.compact ?? false; const iconSize = compact ? 32 : 44; - const stageLabel = props.stageLabel ?? DEFAULT_STAGE_LABEL; + const stageLabel = props.stageLabel ?? m(DEFAULT_STAGE_LABEL); return ( @@ -36,7 +42,7 @@ export function BrandMark(props: { readonly compact?: boolean; readonly stageLab {!compact ? ( - Mobile control surface for your live coding environments + Mobile control surface for your live coding environments ) : null} diff --git a/apps/mobile/src/components/CompactBrandTitle.tsx b/apps/mobile/src/components/CompactBrandTitle.tsx index 222e536cf4b5..bf70682462bf 100644 --- a/apps/mobile/src/components/CompactBrandTitle.tsx +++ b/apps/mobile/src/components/CompactBrandTitle.tsx @@ -1,5 +1,6 @@ import { NATIVE_WORKSPACE_COLUMNS_SUPPORTED } from "../native/NativeWorkspaceColumns"; import Constants from "expo-constants"; +import { useGT } from "gt-react-native"; import { useState } from "react"; import { Platform, View } from "react-native"; @@ -10,6 +11,7 @@ import { resolveMobileStageLabel } from "../lib/mobileBranding"; import { useAndroidControlSizing } from "./ui/useAndroidControlSizing"; const BRAND_MAX_FONT_SCALE = 1.4; +const WORDMARK_SUFFIX = "Code"; export function brandTitleOffset(): number { if (Platform.OS !== "ios") return 0; @@ -24,6 +26,7 @@ export function CompactBrandTitle( readonly fit?: boolean; } = {}, ) { + const gt = useGT(); const stageLabel = resolveMobileStageLabel(Constants.expoConfig?.extra?.appVariant); const titleOffset = brandTitleOffset(); const { scale } = useAndroidControlSizing(); @@ -39,7 +42,7 @@ export function CompactBrandTitle( props.fit && showStage ? (event) => setFullWidth(event.nativeEvent.layout.width) : undefined } aria-level={1} - accessibilityLabel={props.accessibilityLabel ?? "T3 Code, Threads"} + accessibilityLabel={props.accessibilityLabel ?? gt("T3 Code, Threads")} accessible role="heading" className="flex-row items-center gap-1.5" @@ -57,7 +60,7 @@ export function CompactBrandTitle( className="font-t3-medium text-foreground-muted" style={{ fontSize: 21 * scale, letterSpacing: -0.5 * scale }} > - Code + {WORDMARK_SUFFIX} {showStage ? ( @@ -69,8 +71,11 @@ export function ComposerAttachmentThumbnail(props: ComposerAttachmentThumbnailPr accessibilityRole={upload.status === "failed" ? "button" : "text"} accessibilityLabel={ upload.status === "failed" - ? `Retry uploading ${props.attachment.name}` - : `Uploading ${props.attachment.name}, ${Math.floor(upload.progress * 100)}%` + ? gt("Retry uploading {name}", { name: props.attachment.name }) + : gt("Uploading {name}, {percent}%", { + name: props.attachment.name, + percent: Math.floor(upload.progress * 100), + }) } accessibilityHint={upload.status === "failed" ? upload.reason : undefined} disabled={upload.status !== "failed"} @@ -88,7 +93,7 @@ export function ComposerAttachmentThumbnail(props: ComposerAttachmentThumbnailPr /> {!props.compact ? ( - {upload.status === "failed" ? "Retry" : `${Math.floor(upload.progress * 100)}%`} + {upload.status === "failed" ? gt("Retry") : `${Math.floor(upload.progress * 100)}%`} ) : null} @@ -131,6 +136,7 @@ function useComposerImagePreviewUri(attachment: DraftComposerImageAttachment): s function ComposerImageAttachment( props: ComposerAttachmentThumbnailProps & { readonly attachment: DraftComposerImageAttachment }, ) { + const gt = useGT(); const { attachment } = props; const withGallery = useFilePreviewGallery(); const style = { width: props.size, height: props.size, borderRadius: props.borderRadius }; @@ -140,7 +146,7 @@ function ComposerImageAttachment( props.onPressPreview?.( @@ -203,6 +209,7 @@ function ComposerAttachmentContent(props: ComposerAttachmentThumbnailProps) { function ComposerFileAttachment( props: ComposerAttachmentThumbnailProps & { readonly attachment: DraftComposerFileAttachment }, ) { + const gt = useGT(); const { attachment } = props; const style = { width: props.size, height: props.size, borderRadius: props.borderRadius }; const canPreview = isPdfFile(attachment) && props.onPressPreview !== undefined; @@ -213,7 +220,7 @@ function ComposerFileAttachment( canPreview @@ -278,6 +285,7 @@ function ComposerVideoAttachment(props: { } export function ComposerAttachmentStrip(props: ComposerAttachmentStripProps) { + const gt = useGT(); const gallery = composerImageGallery(props.attachments); const size = props.imageSize ?? 72; const radius = props.imageBorderRadius ?? 16; @@ -317,7 +325,7 @@ export function ComposerAttachmentStrip(props: ComposerAttachmentStripProps) { /> setPreviewOpen(true)} > - {error ?? "Attachment unavailable. Reconnect and try again."} + {error ?? Attachment unavailable. Reconnect and try again.} ) : null}