From 2e3c01539f87a09855e8442b946d9c996f740ae7 Mon Sep 17 00:00:00 2001 From: Victor Date: Tue, 24 Nov 2026 17:34:03 -0600 Subject: [PATCH 001/880] fix(web): ArrowUp in a menu search field moves to the last item (#42470) Co-authored-by: Julius Marminge (cherry picked from commit 8f34bb193ac74f31c808cf04c6a07bba4c76cbef) --- apps/web/src/components/ui/menu.tsx | 4 +++- .../ui/search-input.browser.test.tsx | 23 +++++++++++++++++-- 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/apps/web/src/components/ui/menu.tsx b/apps/web/src/components/ui/menu.tsx index 7c699733bb1a5..d166ed38b385d 100644 --- a/apps/web/src/components/ui/menu.tsx +++ b/apps/web/src/components/ui/menu.tsx @@ -102,7 +102,9 @@ function MenuSearchInput({ unstyled onKeyDown={(event) => { // Menu typeahead would otherwise take the letters; arrows still reach the items. - if (event.key !== "ArrowDown" && event.key !== "Escape") event.stopPropagation(); + if (event.key !== "ArrowDown" && event.key !== "ArrowUp" && event.key !== "Escape") { + event.stopPropagation(); + } onKeyDown?.(event); }} /> diff --git a/apps/web/src/components/ui/search-input.browser.test.tsx b/apps/web/src/components/ui/search-input.browser.test.tsx index 098480550331f..3509495937c8d 100644 --- a/apps/web/src/components/ui/search-input.browser.test.tsx +++ b/apps/web/src/components/ui/search-input.browser.test.tsx @@ -1,9 +1,9 @@ import { expect, it } from "vite-plus/test"; -import { userEvent } from "vite-plus/test/browser"; +import { page, userEvent } from "vite-plus/test/browser"; import { render } from "../../../test/render"; import { Combobox, ComboboxSearchInput } from "./combobox"; -import { MenuSearchInput } from "./menu"; +import { Menu, MenuItem, MenuPopup, MenuSearchInput, MenuTrigger } from "./menu"; it.each(["combobox", "menu"] as const)( "focuses the %s search when clicking anywhere in its row", @@ -35,3 +35,22 @@ it.each(["combobox", "menu"] as const)( await expect.element(field).toHaveValue("project"); }, ); + +it("moves focus from MenuSearchInput to the last item on ArrowUp", async () => { + await using _screen = await render( + + Filter + + + Alpha + Gamma + + , + { router: false /* menu keyboard navigation does not involve routing */ }, + ); + + await userEvent.click(page.getByRole("textbox", { name: "Search options" })); + await userEvent.keyboard("{ArrowUp}"); + + await expect.element(page.getByRole("menuitem", { name: "Gamma" })).toHaveFocus(); +}); From 9b62f06bafab33841a07086951c0e22be9950ed7 Mon Sep 17 00:00:00 2001 From: Victor Date: Tue, 24 Nov 2026 17:49:24 -0600 Subject: [PATCH 002/880] fix(server): checkpoint reuse handles filenames starting with a colon (#42472) Co-authored-by: Julius Marminge (cherry picked from commit a49ccc1fcd5fb2ae7fe3e939c0facd7f69ed89b8) --- apps/server/src/vcs/GitVcsDriver.test.ts | 20 +++++++++++++++++-- .../src/vcs/checkpointUntrackedBlobs.ts | 7 +++++-- 2 files changed, 23 insertions(+), 4 deletions(-) diff --git a/apps/server/src/vcs/GitVcsDriver.test.ts b/apps/server/src/vcs/GitVcsDriver.test.ts index c0cee0bf8b430..fa67c2fd685d1 100644 --- a/apps/server/src/vcs/GitVcsDriver.test.ts +++ b/apps/server/src/vcs/GitVcsDriver.test.ts @@ -845,9 +845,25 @@ it.effect.each([ change: ({ git, checkpointRef }: UntrackedBlobChange) => git(["update-ref", "-d", checkpointRef]).pipe(Effect.andThen(git(["prune", "--expire=now"]))), }, + ...(HostProcess.Platform.defaultValue() === "win32" + ? [] + : [ + { + name: "it became ignored under a name that looks like a git pathspec", + file: ":large.txt", + reuses: false, + change: ({ write }: UntrackedBlobChange) => write(".gitignore", ":large.txt\n"), + }, + { + name: "its name looks like git pathspec magic", + file: ":(magic)", + reuses: true, + change: () => Effect.void, + }, + ]), ])( "checkpoint capture skips hashing an untracked file only while a fresh hash would match: $name", - ({ reuses, change, during }) => + ({ file = "nested/large.txt", reuses, change, during }) => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; @@ -875,7 +891,7 @@ it.effect.each([ const write = (relativePath: string, contents: string) => fs.writeFileString(path.join(cwd, relativePath), contents); yield* fs.makeDirectory(path.join(cwd, "nested")); - yield* write("nested/large.txt", "line\r\n".repeat(3 * 1024 * 1024)); + yield* write(file, "line\r\n".repeat(3 * 1024 * 1024)); // Only files left alone for a few seconds before a capture are remembered. yield* TestClock.adjust("36500 days"); yield* driver.checkpoints.captureCheckpoint({ cwd, checkpointRef }); diff --git a/apps/server/src/vcs/checkpointUntrackedBlobs.ts b/apps/server/src/vcs/checkpointUntrackedBlobs.ts index 675dba0121615..889d189e13cd1 100644 --- a/apps/server/src/vcs/checkpointUntrackedBlobs.ts +++ b/apps/server/src/vcs/checkpointUntrackedBlobs.ts @@ -253,7 +253,8 @@ export const make = ( const paths = [...blobs.map((blob) => blob.path), ...snapshot.pending]; if (paths.length === 0) return NOTHING; const unchecked = Effect.succeed({ exitCode: 1, stdout: "" }); - const stdin = `${blobs.map((blob) => `${blob.path}\0`).join("")}`; + // ./ avoids leading : pathspec magic; check-ignore rejects --literal-pathspecs. + const stdin = blobs.map((blob) => `./${blob.path}\0`).join(""); const [config, attributes, ignored, objects] = yield* Effect.all( [ readConfig(input.cwd), @@ -290,7 +291,9 @@ export const make = ( attributes: new Map(paths.map((entryPath, index) => [entryPath, attributes[index]])), }; if (config !== snapshot.config || ignored.exitCode > 1) return { reused: [], before }; - const ignoredPaths = new Set(ignored.stdout.split("\0")); + const ignoredPaths = new Set( + ignored.stdout.split("\0").map((entryPath) => entryPath.replace(/^\.\//, "")), + ); const present = new Set(objects.stdout.split("\n")); blobs = blobs.filter( (blob, index) => From 06db8a8550d583b5cf265f264852360919053e7a Mon Sep 17 00:00:00 2001 From: Hu Hongwei <46087189+jadelike-wine@users.noreply.github.com> Date: Wed, 25 Nov 2026 07:53:17 +0800 Subject: [PATCH 003/880] fix(chat): load HTML reports when the filename limit splits an emoji (#42478) Co-authored-by: Julius Marminge (cherry picked from commit eaa3f7da1318d3f098e8b814948d923f6591f338) --- packages/shared/src/htmlRender.test.ts | 10 ++++++++++ packages/shared/src/htmlRender.ts | 1 + 2 files changed, 11 insertions(+) diff --git a/packages/shared/src/htmlRender.test.ts b/packages/shared/src/htmlRender.test.ts index 04a89b538a560..958414e100c48 100644 --- a/packages/shared/src/htmlRender.test.ts +++ b/packages/shared/src/htmlRender.test.ts @@ -1,6 +1,7 @@ import { describe, expect, it } from "vite-plus/test"; import { + htmlRenderFileName, injectHtmlRenderBootstrap, readHtmlRenderImageRequest, readHtmlRenderLinkRequest, @@ -9,6 +10,15 @@ import { htmlRenderFromToolItem } from "./toolOutput.ts"; const reference = { attachmentId: "thread-abc-123.html", title: "Chart", height: 420 }; +describe("htmlRenderFileName", () => { + it("never ends on half of an emoji at the length limit", () => { + const fits = "a".repeat(118); + const crosses = "a".repeat(119); + expect(htmlRenderFileName(`${fits}🚀 report`)).toBe(`${fits}🚀.html`); + expect(htmlRenderFileName(`${crosses}🚀 report`)).toBe(`${crosses}.html`); + }); +}); + describe("injectHtmlRenderBootstrap", () => { it("puts the theme ahead of the page's own head content", () => { const html = diff --git a/packages/shared/src/htmlRender.ts b/packages/shared/src/htmlRender.ts index 166dabc50d8d5..0d98d05d23fb7 100644 --- a/packages/shared/src/htmlRender.ts +++ b/packages/shared/src/htmlRender.ts @@ -124,6 +124,7 @@ export function htmlRenderFileName(title: string) { .replace(/\s+/g, " ") .trim() .slice(0, 120) + .replace(/\p{Surrogate}$/u, "") .trim(); return `${name || "Page"}.html`; } From 9618bf87f2370a9f99ba6d95a2df44cd94d37b8d Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 24 Nov 2026 15:55:13 -0800 Subject: [PATCH 004/880] fix(web): pooled limit refill shows when it lands again (#42499) (cherry picked from commit 7380740efed40cf513ea975abdd14742be1c5167) --- .../src/components/usage/UsageLimitsPooled.browser.test.tsx | 1 + apps/web/src/components/usage/UsageLimitsPooled.tsx | 6 ++++-- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/apps/web/src/components/usage/UsageLimitsPooled.browser.test.tsx b/apps/web/src/components/usage/UsageLimitsPooled.browser.test.tsx index b6fe3e50c9d37..886dc684a10d7 100644 --- a/apps/web/src/components/usage/UsageLimitsPooled.browser.test.tsx +++ b/apps/web/src/components/usage/UsageLimitsPooled.browser.test.tsx @@ -95,6 +95,7 @@ describe("UsageLimitsPooled next refill", () => { , ); await expect.element(screen.getByText("↻ +30%", { exact: true })).toBeVisible(); + await expect.element(screen.getByText("↻ +30% in 30m")).toBeVisible(); await screen.rerender( , diff --git a/apps/web/src/components/usage/UsageLimitsPooled.tsx b/apps/web/src/components/usage/UsageLimitsPooled.tsx index bb7cc8cf1f114..e3cbdb5eccef1 100644 --- a/apps/web/src/components/usage/UsageLimitsPooled.tsx +++ b/apps/web/src/components/usage/UsageLimitsPooled.tsx @@ -605,6 +605,7 @@ function PoolWindowCard({ readonly label?: string | null | undefined; readonly description?: string | undefined; }) { + const m = useMessages(); const nextRefill = pool.resets.find((reset) => reset.at > now && reset.restoresPercent > 0); return (
@@ -624,8 +625,9 @@ function PoolWindowCard({ {nextRefill && pool.columns.length > 1 ? ( - - ↻ +{nextRefill.restoresPercent}% + + ↻ +{nextRefill.restoresPercent}%{" "} + {formatResetsIn(nextRefill.member.window, now, m, "in")} ) : null}
From 8c38edfdae4fb5be7dd37c813c726e81d4339021 Mon Sep 17 00:00:00 2001 From: ScaleLeanChris Date: Tue, 24 Nov 2026 17:03:13 -0700 Subject: [PATCH 005/880] fix(desktop): detect Chromium profiles for cookie import (#25698) Co-authored-by: maria-rcks Co-authored-by: Yash Singh (cherry picked from commit 5a156a2af8164004acf4aa96dc60edffdb3cbcbc) --- .../BrowserImport/BrowserImport.test.ts | 147 ++++++++++++++++++ .../src/preview/BrowserImport/Sources.test.ts | 20 ++- .../src/preview/BrowserImport/Sources.ts | 13 +- packages/contracts/src/browserImport.ts | 1 + 4 files changed, 174 insertions(+), 7 deletions(-) diff --git a/apps/desktop/src/preview/BrowserImport/BrowserImport.test.ts b/apps/desktop/src/preview/BrowserImport/BrowserImport.test.ts index 28099a0e74f50..720ba29e37a7b 100644 --- a/apps/desktop/src/preview/BrowserImport/BrowserImport.test.ts +++ b/apps/desktop/src/preview/BrowserImport/BrowserImport.test.ts @@ -1,18 +1,43 @@ +import * as NodeSqlite from "node:sqlite"; +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, describe, it } from "@effect/vitest"; +import { BrowserImportSource } from "@t3tools/contracts"; import * as HostProcess from "@t3tools/shared/HostProcess"; +import type { Session } from "electron"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; +import * as Schema from "effect/Schema"; +import * as Cipher from "effect/crypto/Cipher"; +import * as Digest from "effect/crypto/Digest"; +import * as Kdf from "effect/crypto/Kdf"; +import { vi } from "vite-plus/test"; import * as BrowserSession from "../BrowserSession.ts"; import { readManagedPolicyFile } from "@t3tools/shared/managedPolicyFile"; import * as DesktopManagedPolicy from "../../app/DesktopManagedPolicy.ts"; import * as BrowserImport from "./BrowserImport.ts"; +import { LinuxBrowserSecretPath } from "./LinuxBrowserSecret.ts"; import { BROWSER_IMPORT_SOURCES, sourcePathContext } from "./Sources.ts"; import { symlinksSupported } from "@t3tools/shared/testing/symlinks"; const helium = BROWSER_IMPORT_SOURCES.find((source) => source.id === "helium")!; +const decodeImportSource = Schema.decodeEffect(BrowserImportSource); +const chromiumKeychainSecret = "fixture-chromium-keychain-secret"; + +vi.mock("@napi-rs/keyring", () => ({ + AsyncEntry: class { + readonly getPassword: () => Promise; + + constructor(service: string, account: string) { + this.getPassword = async () => + service === "Chromium Safe Storage" && account === "Chromium" + ? chromiumKeychainSecret + : undefined; + } + }, +})); const cookie = { url: "https://rejected.example/path", @@ -67,6 +92,128 @@ const withImporter = Effect.fnUntraced(function* () { }); describe("BrowserImport.importCookies", () => { + it.effect.each([ + { platform: "linux", cookiePath: "Cookies" }, + { platform: "linux", cookiePath: "Network/Cookies" }, + { platform: "darwin", cookiePath: "Network/Cookies" }, + ] as const)( + "discovers and imports Chromium cookies on $platform from $cookiePath", + ({ platform, cookiePath }) => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const home = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-chromium-" }); + const root = + platform === "darwin" + ? `${home}/Library/Application Support/Chromium` + : `${home}/.config/chromium`; + yield* fileSystem.makeDirectory(`${root}/Default/Network`, { recursive: true }); + yield* fileSystem.writeFileString( + `${root}/Local State`, + JSON.stringify({ profile: { info_cache: { Default: { name: "Personal" } } } }), + ); + const kdf = yield* Kdf.Kdf; + const cipher = yield* Cipher.Cipher; + const keyBytes = yield* kdf.derive( + Kdf.pbkdf2({ hash: Digest.sha1, iterations: platform === "darwin" ? 1003 : 1 }), + Buffer.from(platform === "darwin" ? chromiumKeychainSecret : "peanuts"), + { salt: Buffer.from("saltysalt"), length: 16 }, + ); + const key = yield* Cipher.key(Cipher.aes128Cbc, keyBytes); + const ciphertext = yield* cipher.encrypt(key, Buffer.from("fixture-session"), { + iv: Buffer.alloc(16, 0x20), + }); + const value = Buffer.concat([Buffer.from("v10"), ciphertext]); + yield* Effect.sync(() => { + using database = new NodeSqlite.DatabaseSync(`${root}/Default/${cookiePath}`); + database.exec(` + create table meta (key text primary key, value text not null); + insert into meta values ('version', '23'); + create table cookies ( + host_key text, name text, value text, encrypted_value blob, path text, + expires_utc integer, is_secure integer, is_httponly integer, samesite integer, + top_frame_site_key text not null default '' + ); + `); + database + .prepare("insert into cookies values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)") + .run("chromium.example", "session", "", value, "/", 0, 1, 1, 1, ""); + }); + + const written: Electron.CookiesSetDetails[] = []; + let flushed = false; + const session = { + cookies: { + set: (cookie: Electron.CookiesSetDetails) => { + written.push(cookie); + return Promise.resolve(); + }, + flushStore: () => { + flushed = true; + return Promise.resolve(); + }, + }, + } as unknown as Session; + const importer = yield* BrowserImport.BrowserImport.pipe( + Effect.provide( + BrowserImport.layer.pipe( + Layer.provide( + Layer.succeed(BrowserSession.BrowserSession, { + getPartition: () => Effect.die("getPartition must not be reached"), + isPartition: () => false, + getSession: () => Effect.succeed(session), + clearCookies: () => Effect.die("clearCookies must not be reached"), + cookiesCleared: () => Effect.die("cookiesCleared must not be reached"), + clearCache: () => Effect.die("clearCache must not be reached"), + }), + ), + Layer.provide(DesktopManagedPolicy.layerTest()), + Layer.provide(Layer.succeed(HostProcess.Environment, { HOME: home })), + Layer.provide(Layer.succeed(HostProcess.Platform, platform)), + Layer.provide(Layer.succeed(HostProcess.ExecutablePath, "/fixture/t3code")), + Layer.provide(NodeServices.layer), + ), + ), + ); + const source = (yield* importer.listSources).find( + (candidate) => candidate.id === "chromium", + ); + assert.isDefined(source); + assert.deepEqual(yield* decodeImportSource(source!), { + id: "chromium", + name: "Chromium", + profiles: [{ directory: "Default", name: "Personal", cookieCount: 1 }], + }); + assert.deepEqual( + yield* importer.importCookies({ + input: { + sourceId: "chromium", + sourceProfileDirectory: "Default", + targetProfileId: "default", + }, + scope: "persist:t3code-preview-test", + persistent: true, + }), + { imported: 1, skipped: 0, skippedDomains: [] }, + ); + assert.deepEqual(written, [ + { + url: "https://chromium.example/", + name: "session", + value: "fixture-session", + path: "/", + secure: true, + httpOnly: true, + sameSite: "lax", + }, + ]); + assert.isTrue(flushed); + }).pipe( + Effect.provideService(LinuxBrowserSecretPath, undefined), + Effect.provide([NodeServices.layer, NodeCrypto.layerKdf, NodeCrypto.layerCipher]), + Effect.scoped, + ), + ); + it.effect("rejects a source profile the browser never reported", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; diff --git a/apps/desktop/src/preview/BrowserImport/Sources.test.ts b/apps/desktop/src/preview/BrowserImport/Sources.test.ts index 9b2c3cb26c8f7..54518f637c6c1 100644 --- a/apps/desktop/src/preview/BrowserImport/Sources.test.ts +++ b/apps/desktop/src/preview/BrowserImport/Sources.test.ts @@ -199,9 +199,17 @@ describe("chromiumProcessIsAlive", () => { }); describe("isSourceInstalled", () => { - it.effect.each([undefined, "", "relative-config", "relocated", "chrome-override"])( - "discovers Linux Chromium profiles with XDG_CONFIG_HOME=%s", - (configHome) => + it.effect.each([ + ["chrome", "google-chrome", undefined], + ["chrome", "google-chrome", ""], + ["chrome", "google-chrome", "relative-config"], + ["chrome", "google-chrome", "relocated"], + ["chrome", "google-chrome", "chrome-override"], + ["chromium", "chromium", "relocated"], + ["chromium", "chromium", "chrome-override"], + ] as const)( + "discovers Linux %s profiles in %s with config home %s", + ([sourceId, directory, configHome]) => run( Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; @@ -212,7 +220,7 @@ describe("isSourceInstalled", () => { ? path.join(home, "config") : configHome; const chromeConfigHome = - configHome === "chrome-override" ? path.join(home, ".config") : undefined; + configHome === "chrome-override" ? path.join(home, "chrome-config") : undefined; const context = yield* sourcePathContext.pipe( Effect.provideService(HostProcess.Environment, { HOME: home, @@ -224,8 +232,8 @@ describe("isSourceInstalled", () => { const configRoot = chromeConfigHome ?? (configHome === "relocated" ? path.join(home, "config") : path.join(home, ".config")); - const source = BROWSER_IMPORT_SOURCES.find((source) => source.id === "chrome")!; - const root = path.join(configRoot, "google-chrome"); + const source = BROWSER_IMPORT_SOURCES.find((source) => source.id === sourceId)!; + const root = path.join(configRoot, directory); const database = path.join(root, "Default", "Network", "Cookies"); assert.isFalse(yield* isSourceInstalled(source, context)); yield* fileSystem.makeDirectory(path.dirname(database), { recursive: true }); diff --git a/apps/desktop/src/preview/BrowserImport/Sources.ts b/apps/desktop/src/preview/BrowserImport/Sources.ts index 6ecd546a1ad57..b8fc14f578700 100644 --- a/apps/desktop/src/preview/BrowserImport/Sources.ts +++ b/apps/desktop/src/preview/BrowserImport/Sources.ts @@ -71,7 +71,9 @@ const chromiumSource = (input: { } return input.linuxSegments ? context.path.join( - input.id === "chrome" ? context.linuxChromeConfigHome : context.linuxConfigHome, + input.id === "chrome" || input.id === "chromium" + ? context.linuxChromeConfigHome + : context.linuxConfigHome, ...input.linuxSegments, ) : undefined; @@ -89,6 +91,15 @@ export const BROWSER_IMPORT_SOURCES: ReadonlyArray Date: Tue, 24 Nov 2026 18:07:51 -0600 Subject: [PATCH 006/880] fix(web,mobile): a 9.96-second workflow step reads 10s, not 10.0s (#42492) Co-authored-by: Julius Marminge (cherry picked from commit 89d9e74df45e4dbc5dcaa9bb57ba0480be03fbcd) --- packages/client-runtime/src/workflows.test.ts | 2 ++ packages/client-runtime/src/workflows.ts | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/packages/client-runtime/src/workflows.test.ts b/packages/client-runtime/src/workflows.test.ts index de96c219b74bb..d591fa75412d0 100644 --- a/packages/client-runtime/src/workflows.test.ts +++ b/packages/client-runtime/src/workflows.test.ts @@ -610,6 +610,8 @@ describe("workflowStepTime", () => { expect(workflowStepTime(9)).toBe("0.1s"); expect(workflowStepTime(342)).toBe("0.3s"); expect(workflowStepTime(9_700)).toBe("9.7s"); + expect(workflowStepTime(9_949)).toBe("9.9s"); + expect(workflowStepTime(9_950)).toBe("10s"); expect(workflowStepTime(4_000)).toBe("4s"); expect(workflowStepTime(12_400)).toBe("12s"); expect(workflowStepTime(59_499)).toBe("59s"); diff --git a/packages/client-runtime/src/workflows.ts b/packages/client-runtime/src/workflows.ts index 6dd2406a16d75..97b4af4d63ce4 100644 --- a/packages/client-runtime/src/workflows.ts +++ b/packages/client-runtime/src/workflows.ts @@ -848,7 +848,7 @@ export function workflowStepReferences( /** A step's time in one shape down a column: 0.3s, 9.7s, 12s, then minutes. */ export function workflowStepTime(ms: number): string { - if (ms < 10_000 && ms % 1000 !== 0) return `${(Math.max(ms, 100) / 1000).toFixed(1)}s`; + if (ms < 9_950 && ms % 1000 !== 0) return `${(Math.max(ms, 100) / 1000).toFixed(1)}s`; const seconds = Math.round(ms / 1000); if (seconds < 60) return `${seconds}s`; return formatDuration(ms); From a4e8e39c578a1fcc8fb265410fb3e30d5147439d Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 24 Nov 2026 16:25:01 -0800 Subject: [PATCH 007/880] ci(mobile): fork previews wait for an approval that names the commit (#42503) Co-authored-by: Claude Fable 5.2 (cherry picked from commit ceb20555b37b8ca6d1c6681e0d36fde076ebed58) --- .github/scripts/workflow-credentials.test.cjs | 126 +++++++++++- .github/workflows/mobile-eas-preview-fork.yml | 179 ++++++++++++++---- 2 files changed, 260 insertions(+), 45 deletions(-) diff --git a/.github/scripts/workflow-credentials.test.cjs b/.github/scripts/workflow-credentials.test.cjs index 35d0c5bf56e73..5bebcb5202b91 100644 --- a/.github/scripts/workflow-credentials.test.cjs +++ b/.github/scripts/workflow-credentials.test.cjs @@ -226,16 +226,122 @@ test("the Vite+ toolchain is cached before the job installs or runs project code assert.ok(names.every((step) => !step.uses.startsWith("actions/cache@"))); }); -const consumeScript = steps(jobs("workflows/mobile-eas-preview-fork.yml").preview) - .find((step) => step.startsWith("id: consume\n")) - .split(/^ {10}script: \|\n/m)[1] - .replace(/^ {12}/gm, ""); -const consume = new (Object.getPrototypeOf(async () => {}).constructor)( - "github", - "context", - "core", - consumeScript, -); +const forkPreview = jobs("workflows/mobile-eas-preview-fork.yml"); +const forkPreviewScript = (id) => + new (Object.getPrototypeOf(async () => {}).constructor)( + "github", + "context", + "core", + steps(forkPreview.request) + .find((step) => step.startsWith(`id: ${id}\n`)) + .split(/^ {10}script: \|\n/m)[1] + .split(/^ {0,11}\S/m)[0] + .replace(/^ {12}/gm, ""), + ); +const consume = forkPreviewScript("consume"); +const pin = forkPreviewScript("pin"); +const forkPreviewEnvironment = /^ {10}ENVIRONMENT: (\S+)$/m.exec(forkPreview.request)[1]; + +test("a fork preview is requested by a job that reads no secrets and checks out nothing", () => { + const { request } = forkPreview; + assert.doesNotMatch(request, /secrets\.|actions\/checkout|^ {4}environment:/m); + assert.ok(!runsProjectCode(request), "request runs project code"); + assert.match(request, /^ {6}sha: \$\{\{ steps\.pin\.outputs\.sha \}\}$/m); + const pinStep = steps(request).find((step) => step.startsWith("id: pin\n")); + assert.match(pinStep, /^ {8}if: steps\.consume\.outputs\.consumed == 'true'$/m); +}); + +test("every fork preview job that reads a secret or runs the PR's code waits in the environment and builds the requested commit", () => { + const { request: _request, comment, ...gated } = forkPreview; + assert.deepEqual(Object.keys(gated), ["preview", "android-build", "ios-build"]); + for (const [name, block] of Object.entries(gated)) { + assert.match(block, /^ {4}needs: (?:request|\[request, preview\])$/m, name); + assert.ok( + block.includes(`\n environment:\n name: ${forkPreviewEnvironment}\n`), + `${name} waits in ${forkPreviewEnvironment}`, + ); + assert.doesNotMatch(block, /github\.event\.pull_request\.head/, name); + const refs = Array.from(block.matchAll(/^ {10}ref: (.+)$/gm), (match) => match[1]); + assert.deepEqual(refs, ["${{ needs.request.outputs.sha }}"], name); + const jobSteps = steps(block); + assert.match(jobSteps[0], /^name: Confirm the PR is still open\n/, name); + assert.ok(jobSteps.findIndex((step) => /secrets\.|actions\/checkout/.test(step)) > 0, name); + } + assert.match(gated.preview, /^ {4}if: needs\.request\.outputs\.sha != ''$/m); + assert.doesNotMatch(comment, /secrets\.|^ +ref: |github\.event\.pull_request\.head/m); +}); + +async function runPin(environment, sha = "a".repeat(40)) { + const outputs = {}; + const written = { comments: [], summary: "", failed: "" }; + await pin( + { + async request(route, params) { + assert.equal(route, "GET /repos/{owner}/{repo}/environments/{environment_name}"); + assert.equal(params.environment_name, forkPreviewEnvironment); + if (!environment) throw Object.assign(new Error("missing"), { status: 404 }); + return { data: environment }; + }, + rest: { issues: { createComment: async ({ body }) => written.comments.push(body) } }, + }, + { + repo: { owner: "example", repo: "app" }, + serverUrl: "https://github.example", + runId: 99, + payload: { sender: { login: "labeler" }, pull_request: { number: 7, head: { sha } } }, + }, + { + setFailed: (message) => (written.failed = message), + setOutput: (name, value) => (outputs[name] = value), + summary: { + addRaw(text) { + written.summary += text; + return this; + }, + async write() {}, + }, + }, + ); + return { outputs, ...written }; +} + +test("a fork preview request names the commit where the reviewer reads it", async () => { + process.env.ENVIRONMENT = forkPreviewEnvironment; + const sha = "a".repeat(40); + const reviewers = { type: "required_reviewers", reviewers: [{ type: "Team" }] }; + const named = await runPin({ protection_rules: [{ type: "branch_policy" }, reviewers] }); + assert.deepEqual(named.outputs, { sha }); + assert.equal(named.failed, ""); + assert.deepEqual(named.comments, [named.summary]); + assert.ok(named.summary.includes(`https://github.example/example/app/pull/7/commits/${sha}`)); + assert.ok(named.summary.includes("https://github.example/example/app/actions/runs/99")); + // Quoted, or YAML would end the title at the " #". + assert.match( + read("workflows/mobile-eas-preview-fork.yml"), + /^run-name: "\$\{\{ .*format\('Mobile preview of #\{0\} at \{1\}', github\.event\.pull_request\.number, github\.event\.pull_request\.head\.sha\) \|\| '' \}\}"$/m, + ); +}); + +test("a fork preview request builds nothing unless the environment has required reviewers", async () => { + process.env.ENVIRONMENT = forkPreviewEnvironment; + for (const environment of [ + undefined, + {}, + { protection_rules: [] }, + { protection_rules: [{ type: "branch_policy" }, { type: "wait_timer", wait_timer: 5 }] }, + { protection_rules: [{ type: "required_reviewers", reviewers: [] }] }, + ]) { + const refused = await runPin(environment); + assert.deepEqual([refused.outputs, refused.comments, refused.summary], [{}, [], ""]); + assert.match(refused.failed, /no required reviewers/); + } + const noCommit = await runPin( + { protection_rules: [{ type: "required_reviewers", reviewers: [{ type: "User" }] }] }, + "main", + ); + assert.deepEqual([noCommit.outputs, noCommit.comments], [{}, []]); + assert.match(noCommit.failed, /no head commit/); +}); async function runConsume(permission, removeStatus, removed = []) { const outputs = {}; diff --git a/.github/workflows/mobile-eas-preview-fork.yml b/.github/workflows/mobile-eas-preview-fork.yml index 2953ac50b06bb..a32d2bd98fbf4 100644 --- a/.github/workflows/mobile-eas-preview-fork.yml +++ b/.github/workflows/mobile-eas-preview-fork.yml @@ -1,11 +1,18 @@ name: Mobile EAS Preview (Fork) +run-name: "${{ github.event.label.name == '🚀 Mobile Continuous Deployment' && github.event.pull_request.head.repo.full_name != github.repository && format('Mobile preview of #{0} at {1}', github.event.pull_request.number, github.event.pull_request.head.sha) || '' }}" # EAS previews for fork PRs. This runs the PR's code with an Expo token: the -# app config and plugins run on this runner; both clients build on Blacksmith -# with preview signing credentials. The label is the maintainer's sign-off -# that they reviewed that code, so it covers exactly the commit it was applied -# to: this pins that commit and consumes the label before running anything. A -# later push deploys nothing until the label is applied again. +# app config and plugins run on a runner; both clients build on Blacksmith +# with preview signing credentials. So every job that does waits for an +# approval in the `mobile-preview-fork` environment on every run. +# +# The label only requests a build, and counts only from someone with write +# access. The `request` job consumes it, pins the PR's head commit from the +# label event, and names that commit in the run title, the job summary and a +# PR comment. It reads no secrets and checks out nothing. The approval is the +# sign-off that the named commit was reviewed: the jobs after it build that +# commit and no other. A later push deploys nothing until the label is applied +# again and that run is approved. # # Same-repo PRs deploy on every push while labeled, via mobile-eas-preview.yml. @@ -17,31 +24,17 @@ permissions: contents: read jobs: - preview: - name: EAS Preview + request: + name: Preview request if: >- github.event.pull_request.head.repo.full_name != github.repository && github.event.label.name == '🚀 Mobile Continuous Deployment' - runs-on: blacksmith-8vcpu-ubuntu-2404 - concurrency: - group: mobile-eas-preview-fork-${{ github.event.pull_request.number }} - cancel-in-progress: true + runs-on: blacksmith-2vcpu-ubuntu-2404 permissions: contents: read pull-requests: write outputs: - ios_group: ${{ steps.ios_update.outputs.group }} - ios_client: ${{ steps.ios_client.outputs.link }} - group: ${{ steps.update.outputs.group }} - client: ${{ steps.client.outputs.link }} - ios_build: ${{ steps.ios_client.outputs.build }} - ios_fingerprint: ${{ steps.ios_client.outputs.fingerprint }} - build: ${{ steps.client.outputs.build }} - fingerprint: ${{ steps.client.outputs.fingerprint }} - env: - APP_VARIANT: preview - NODE_OPTIONS: --max-old-space-size=8192 - MOBILE_VERSION_POLICY: fingerprint + sha: ${{ steps.pin.outputs.sha }} steps: # The label counts only from someone with write access, who could push a # same-repo branch and get this build anyway. If a maintainer removed the @@ -76,9 +69,96 @@ jobs: } core.setOutput("consumed", String(authorized)); + # The review screen of a pull_request_target run shows the base branch, + # so the commit is named here, where the reviewer reads it before + # approving. The jobs below take it from this job's output. Nothing is + # requested unless the environment exists with required reviewers: a + # workflow that names a missing environment creates it without any. + - id: pin + name: Name the commit to build + if: steps.consume.outputs.consumed == 'true' + uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0 + env: + ENVIRONMENT: mobile-preview-fork + with: + script: | + const name = process.env.ENVIRONMENT; + let rules = []; + try { + const { data } = await github.request("GET /repos/{owner}/{repo}/environments/{environment_name}", { + owner: context.repo.owner, + repo: context.repo.repo, + environment_name: name, + }); + rules = data.protection_rules ?? []; + } catch (error) { + if (error.status !== 404) throw error; + } + if (!rules.some((rule) => rule.type === "required_reviewers" && rule.reviewers?.length > 0)) { + core.setFailed(`The ${name} environment has no required reviewers. Nothing built.`); + return; + } + const pull = context.payload.pull_request; + const sha = pull.head.sha; + if (!/^[0-9a-f]{40}$/.test(sha)) { + core.setFailed("The label event carries no head commit. Nothing built."); + return; + } + const repository = `${context.serverUrl}/${context.repo.owner}/${context.repo.repo}`; + const body = [ + `Mobile preview requested by ${context.payload.sender.login} for commit [\`${sha}\`](${repository}/pull/${pull.number}/commits/${sha}).`, + "", + `It builds after an approval in the \`${name}\` environment: [review this run](${repository}/actions/runs/${context.runId}). Approving builds exactly this commit; a later push needs the label again.`, + ].join("\n"); + await core.summary.addRaw(body, true).write(); + await github.rest.issues.createComment({ + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: pull.number, + body, + }); + core.setOutput("sha", sha); + + preview: + name: EAS Preview + needs: request + if: needs.request.outputs.sha != '' + runs-on: blacksmith-8vcpu-ubuntu-2404 + environment: + name: mobile-preview-fork + concurrency: + group: mobile-eas-preview-fork-${{ github.event.pull_request.number }} + cancel-in-progress: true + permissions: + contents: read + pull-requests: read + outputs: + ios_group: ${{ steps.ios_update.outputs.group }} + ios_client: ${{ steps.ios_client.outputs.link }} + group: ${{ steps.update.outputs.group }} + client: ${{ steps.client.outputs.link }} + ios_build: ${{ steps.ios_client.outputs.build }} + ios_fingerprint: ${{ steps.ios_client.outputs.fingerprint }} + build: ${{ steps.client.outputs.build }} + fingerprint: ${{ steps.client.outputs.fingerprint }} + env: + APP_VARIANT: preview + NODE_OPTIONS: --max-old-space-size=8192 + MOBILE_VERSION_POLICY: fingerprint + steps: + - name: Confirm the PR is still open + uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0 + with: + script: | + const { data: pull } = await github.rest.pulls.get({ + owner: context.repo.owner, + repo: context.repo.repo, + pull_number: context.payload.pull_request.number, + }); + if (pull.state !== "open") core.setFailed(`PR #${pull.number} is no longer open; not building.`); + - id: expo-token name: Check for EXPO_PREVIEW_TOKEN - if: steps.consume.outputs.consumed == 'true' env: EXPO_TOKEN: ${{ secrets.EXPO_PREVIEW_TOKEN }} run: | @@ -89,14 +169,14 @@ jobs: echo "EXPO_PREVIEW_TOKEN is not set; skipping EAS preview." fi - # The head SHA from the label event, not the branch, so a push after the - # label cannot swap in unreviewed code. No credentials stay in .git for - # the PR's scripts to read. + # The commit the request job named, not the branch, so a push after the + # label builds nothing. No credentials stay in .git for the PR's scripts + # to read. - name: Checkout reviewed commit if: steps.expo-token.outputs.present == 'true' uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: - ref: ${{ github.event.pull_request.head.sha }} + ref: ${{ needs.request.outputs.sha }} fetch-depth: 0 # No sparse-checkout: see mobile-eas-preview.yml. @@ -233,17 +313,21 @@ jobs: group="$(eas update --auto --branch "pr-$PR" --platform android --environment preview --non-interactive --json | sed -n '/^\[/,$p' | jq -er '.[0].group')" echo "group=$group" >> "$GITHUB_OUTPUT" - # The reviewed commit's Android client, built cold: no sticky disk, because PR + # Each client job waits for its own approval in the environment, once the + # preview job has finished. The reviewed commit's Android client, built cold: no sticky disk, because PR # code could leave Gradle or ccache state that trusted builds would restore, and # no build record tag, so nobody else is served an APK a fork's code built. android-build: name: Android preview client - needs: preview + needs: [request, preview] if: needs.preview.outputs.build == 'true' runs-on: blacksmith-32vcpu-ubuntu-2404 timeout-minutes: 60 + environment: + name: mobile-preview-fork permissions: contents: read + pull-requests: read outputs: client: ${{ steps.build.outputs.link }} env: @@ -254,10 +338,21 @@ jobs: # Phones only: emulators use the development client from the native-client cache. ORG_GRADLE_PROJECT_reactNativeArchitectures: armeabi-v7a,arm64-v8a steps: + - name: Confirm the PR is still open + uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0 + with: + script: | + const { data: pull } = await github.rest.pulls.get({ + owner: context.repo.owner, + repo: context.repo.repo, + pull_number: context.payload.pull_request.number, + }); + if (pull.state !== "open") core.setFailed(`PR #${pull.number} is no longer open; not building.`); + - name: Checkout reviewed commit uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: - ref: ${{ github.event.pull_request.head.sha }} + ref: ${{ needs.request.outputs.sha }} fetch-depth: 0 # Scripts and actions come from main, not from the PR. @@ -301,12 +396,15 @@ jobs: ios-build: name: iOS preview client - needs: preview + needs: [request, preview] if: needs.preview.outputs.ios_build == 'true' runs-on: blacksmith-12vcpu-macos-27 timeout-minutes: 60 + environment: + name: mobile-preview-fork permissions: contents: read + pull-requests: read outputs: client: ${{ steps.build.outputs.link }} env: @@ -315,10 +413,21 @@ jobs: MOBILE_VERSION_POLICY: fingerprint FINGERPRINT: ${{ needs.preview.outputs.ios_fingerprint }} steps: + - name: Confirm the PR is still open + uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0 + with: + script: | + const { data: pull } = await github.rest.pulls.get({ + owner: context.repo.owner, + repo: context.repo.repo, + pull_number: context.payload.pull_request.number, + }); + if (pull.state !== "open") core.setFailed(`PR #${pull.number} is no longer open; not building.`); + - name: Checkout reviewed commit uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: - ref: ${{ github.event.pull_request.head.sha }} + ref: ${{ needs.request.outputs.sha }} fetch-depth: 0 # Scripts and actions come from main, not from the PR. @@ -362,7 +471,7 @@ jobs: comment: name: Mobile preview comment - needs: [preview, android-build, ios-build] + needs: [request, preview, android-build, ios-build] if: always() && !cancelled() && needs.preview.result == 'success' runs-on: blacksmith-2vcpu-ubuntu-2404 concurrency: @@ -381,7 +490,7 @@ jobs: env: GH_TOKEN: ${{ github.token }} PR: ${{ github.event.pull_request.number }} - PR_HEAD_SHA: ${{ github.event.pull_request.head.sha }} + PR_HEAD_SHA: ${{ needs.request.outputs.sha }} ANDROID_FINGERPRINT: ${{ needs.preview.outputs.fingerprint }} ANDROID_GROUP: ${{ needs.preview.outputs.group }} ANDROID_CLIENT: ${{ needs.android-build.outputs.client || needs.preview.outputs.client }} From 6eed08d0c0ed4a314868645404c2aedc18b2bf2e Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 24 Nov 2026 16:25:22 -0800 Subject: [PATCH 008/880] fix(server): Needs you lists every open workflow question, however old its run (#42501) (cherry picked from commit 34ca872cbb615e45df639160070f7b86ea05058b) --- .../src/workflows/WorkflowStore.test.ts | 42 +++++++++++++++++++ apps/server/src/workflows/WorkflowStore.ts | 9 +++- 2 files changed, 50 insertions(+), 1 deletion(-) diff --git a/apps/server/src/workflows/WorkflowStore.test.ts b/apps/server/src/workflows/WorkflowStore.test.ts index 6ff8dd1d2fc16..6b6137345de63 100644 --- a/apps/server/src/workflows/WorkflowStore.test.ts +++ b/apps/server/src/workflows/WorkflowStore.test.ts @@ -772,3 +772,45 @@ it.effect("reads that run on every change or sweep do not read every run", () => }), ), ); + +it.effect("a run waiting on a question is listed however many runs started after it", () => + withStore( + Effect.gen(function* () { + const store = yield* WorkflowStore.WorkflowStore; + const start = (runId: string) => + store.runStarted({ + runId, + workflow: "ask", + version: 1, + engineTag: "ask@1", + idempotencyKey: runId, + input: {}, + }); + yield* start("old"); + yield* store.runStatus("old", "waiting", "waiting on you"); + yield* store.waitOpened({ + runId: "old", + name: "approve", + workflow: "ask", + key: undefined, + token: "t", + schemaJson: "{}", + requestJson: '{"title":"Ship it?"}', + watchJson: null, + deadline: null, + }); + for (let index = 0; index < 500; index++) { + yield* TestClock.adjust("1 second"); + yield* start(`new-${index}`); + yield* store.runEnded(`new-${index}`, "completed", null, null); + } + assert.deepStrictEqual( + (yield* store.requests).map((wait) => wait.run_id), + ["old"], + ); + // Needs you lists the open questions of the runs it is sent; one it is not sent is lost. + const listed = new Set((yield* store.runs(undefined)).map((run) => run.run_id)); + assert.isTrue(listed.has("old")); + }), + ), +); diff --git a/apps/server/src/workflows/WorkflowStore.ts b/apps/server/src/workflows/WorkflowStore.ts index b63037936e8c6..01ef1f28964dd 100644 --- a/apps/server/src/workflows/WorkflowStore.ts +++ b/apps/server/src/workflows/WorkflowStore.ts @@ -1108,7 +1108,8 @@ export const make = Effect.gen(function* () { return yield* ( status === undefined ? // Skipped runs are counted apart, so a trigger that skips most of what it brings does - // not push the runs that did something out of the list. + // not push the runs that did something out of the list. A run with a question open is + // listed however old, since what waits on a person is built from this list. sql` SELECT ${summaryColumns} FROM ( SELECT ${summaryColumns} FROM workflow_runs @@ -1121,6 +1122,12 @@ export const make = Effect.gen(function* () { WHERE status = 'skipped' AND parent_run_id IS NULL ORDER BY started_at DESC LIMIT 500 ) + UNION + SELECT ${summaryColumns} FROM workflow_runs + WHERE run_id IN ( + SELECT run_id FROM workflow_waits + WHERE request_json IS NOT NULL AND signalled_at IS NULL + ) ORDER BY started_at DESC ` : sql` From 43679f78abbc8e377b3ea080e2625527edacf8e1 Mon Sep 17 00:00:00 2001 From: Victor Date: Tue, 24 Nov 2026 18:33:57 -0600 Subject: [PATCH 009/880] fix(web): device host limit fields stay empty when cleared (#42500) Co-authored-by: Julius Marminge (cherry picked from commit 622f96785a9b0a4acd49ac199838e66aaf4338ab) --- .../EasDeviceHostEditor.browser.test.tsx | 49 +++++++++++++++++ .../settings/EasDeviceHostEditor.tsx | 4 +- .../SimlockDeviceHostEditor.browser.test.tsx | 53 +++++++++++++++++++ .../settings/SimlockDeviceHostEditor.tsx | 4 +- 4 files changed, 106 insertions(+), 4 deletions(-) create mode 100644 apps/web/src/components/settings/EasDeviceHostEditor.browser.test.tsx create mode 100644 apps/web/src/components/settings/SimlockDeviceHostEditor.browser.test.tsx diff --git a/apps/web/src/components/settings/EasDeviceHostEditor.browser.test.tsx b/apps/web/src/components/settings/EasDeviceHostEditor.browser.test.tsx new file mode 100644 index 0000000000000..b2a1db2875bc3 --- /dev/null +++ b/apps/web/src/components/settings/EasDeviceHostEditor.browser.test.tsx @@ -0,0 +1,49 @@ +import { EnvironmentId } from "@t3tools/contracts"; +import { describe, expect, it, vi } from "vite-plus/test"; +import { page, userEvent } from "vite-plus/test/browser"; + +import "~/index.css"; +import { render } from "../../../test/render"; +import { newEasDeviceHost } from "./easDeviceHostsSettings.logic"; + +vi.mock(import("../../state/device"), async () => { + const { AsyncResult, Atom } = await import("effect/reactivity"); + const accountAtom = Atom.make(AsyncResult.initial()); + return { + deviceEasAccountCheck: (() => accountAtom) as never, + deviceEnvironment: { easAccount: { label: "easAccount" } } as never, + }; +}); +vi.mock(import("./SecretSourceInput"), () => ({ + useSecretSources: () => [], + SecretSourceInput: (() => ) as never, +})); + +import { EasDeviceHostEditor } from "./EasDeviceHostEditor"; + +describe("EasDeviceHostEditor", () => { + it("leaves a cleared limit field empty and keeps Save off until a number is entered", async () => { + await using _screen = await render( + {}} + onClose={() => {}} + />, + ); + + const saveButton = page.getByRole("button", { name: "Save host" }); + await expect.element(saveButton).not.toBeDisabled(); + + const input = page.getByLabelText("Sessions at once"); + await userEvent.clear(input); + await expect.element(input).toHaveDisplayValue(""); + await expect.element(saveButton).toBeDisabled(); + + await userEvent.type(input, "5"); + await expect.element(input).toHaveDisplayValue("5"); + await expect.element(saveButton).not.toBeDisabled(); + }); +}); diff --git a/apps/web/src/components/settings/EasDeviceHostEditor.tsx b/apps/web/src/components/settings/EasDeviceHostEditor.tsx index 7c85fc9de43a5..12faa9539d0b5 100644 --- a/apps/web/src/components/settings/EasDeviceHostEditor.tsx +++ b/apps/web/src/components/settings/EasDeviceHostEditor.tsx @@ -155,10 +155,10 @@ export function EasDeviceHostEditor(props: { type="number" min={1} max={max} - value={draft[field]} + value={Number.isNaN(draft[field]) ? "" : draft[field]} disabled={props.busy} onChange={(event) => { - const value = Number(event.target.value); + const value = event.target.valueAsNumber; setDraft((current) => ({ ...current, [field]: value })); }} /> diff --git a/apps/web/src/components/settings/SimlockDeviceHostEditor.browser.test.tsx b/apps/web/src/components/settings/SimlockDeviceHostEditor.browser.test.tsx new file mode 100644 index 0000000000000..3d3d84d265082 --- /dev/null +++ b/apps/web/src/components/settings/SimlockDeviceHostEditor.browser.test.tsx @@ -0,0 +1,53 @@ +import { EnvironmentId } from "@t3tools/contracts"; +import { describe, expect, it, vi } from "vite-plus/test"; +import { page, userEvent } from "vite-plus/test/browser"; + +import "~/index.css"; +import { render } from "../../../test/render"; +import { newSimlockDeviceHost } from "./simlockDeviceHostsSettings.logic"; + +vi.mock(import("../../state/device"), async () => { + const { AsyncResult, Atom } = await import("effect/reactivity"); + const identityAtom = Atom.make(AsyncResult.initial()); + return { + deviceSimlockIdentityCheck: (() => identityAtom) as never, + }; +}); +vi.mock(import("./SecretSourceInput"), () => ({ + useSecretSources: () => [], + SecretSourceInput: (() => ) as never, +})); + +import { SimlockDeviceHostEditor } from "./SimlockDeviceHostEditor"; + +describe("SimlockDeviceHostEditor", () => { + it("leaves a cleared limit field empty and keeps Save off until a number is entered", async () => { + await using _screen = await render( + {}} + onClose={() => {}} + />, + ); + + const saveButton = page.getByRole("button", { name: "Save host" }); + await expect.element(saveButton).not.toBeDisabled(); + + const input = page.getByLabelText("Devices at once"); + await userEvent.clear(input); + await expect.element(input).toHaveDisplayValue(""); + await expect.element(saveButton).toBeDisabled(); + + await userEvent.type(input, "5"); + await expect.element(input).toHaveDisplayValue("5"); + await expect.element(saveButton).not.toBeDisabled(); + }); +}); diff --git a/apps/web/src/components/settings/SimlockDeviceHostEditor.tsx b/apps/web/src/components/settings/SimlockDeviceHostEditor.tsx index 30e0a1da64590..210180545740f 100644 --- a/apps/web/src/components/settings/SimlockDeviceHostEditor.tsx +++ b/apps/web/src/components/settings/SimlockDeviceHostEditor.tsx @@ -118,10 +118,10 @@ export function SimlockDeviceHostEditor(props: { type="number" min={min} max={max} - value={draft[field]} + value={Number.isNaN(draft[field]) ? "" : draft[field]} disabled={props.busy} onChange={(event) => { - const value = Number(event.target.value); + const value = event.target.valueAsNumber; setDraft((current) => ({ ...current, [field]: value })); }} /> From 40ece0e3935a6181a02a49282748e436a18ae320 Mon Sep 17 00:00:00 2001 From: Stephen Belanger Date: Wed, 25 Nov 2026 08:45:33 +0800 Subject: [PATCH 010/880] fix(github): approve workflows on same-repository PRs (#26561) Co-authored-by: maria-rcks (cherry picked from commit 2210f2d733f89f12ee52e48a76d0d0855c9d39e4) --- .../src/server/GitHubPullRequestApi.test.ts | 318 ++++++++++++------ .../src/server/GitHubPullRequestApi.ts | 31 +- .../server/GitHubPullRequestProvider.test.ts | 64 +++- .../src/server/GitHubPullRequestProvider.ts | 4 +- .../src/server/gitHubConditionalChecks.ts | 25 +- .../src/server/gitHubPullRequestJson.ts | 4 + 6 files changed, 312 insertions(+), 134 deletions(-) diff --git a/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts b/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts index 76b3b8cf1908b..76342f65c8910 100644 --- a/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts +++ b/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts @@ -21,7 +21,7 @@ import * as SourceControlRateLimit from "@t3tools/source-control-core/server/Sou import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost"; import * as GitHubPullRequestApi from "./GitHubPullRequestApi.ts"; import * as GitHubPullRequestProvider from "./GitHubPullRequestProvider.ts"; -import { KnownWorkflowRuns } from "./gitHubConditionalChecks.ts"; +import { KnownWorkflowRuns, makeChecksRevalidator } from "./gitHubConditionalChecks.ts"; import * as GitHubAppAccess from "./GitHubAppAccess.ts"; import * as GitHubAppSignIn from "./GitHubAppSignIn.ts"; @@ -587,15 +587,15 @@ const checkContextsPage = ( const pullRequestRefs = encodeJson({ base: { sha: "a1b2c3d" }, head: { sha: "b1c2d3e" } }); const pullRequestMergeBase = encodeJson({ merge_base_commit: { sha: "c1d2e3f" } }); -const crossRepositoryDetail = (headRefOid = "abc123") => +const workflowApprovalDetail = (headRefOid = "abc123", isCrossRepository = true) => coreResponse({ headRefName: "feat/page", headRefOid, - isCrossRepository: true, - headRepositoryOwner: { __typename: "User", login: "octocat" }, + isCrossRepository, + headRepositoryOwner: { __typename: "User", login: isCrossRepository ? "octocat" : "acme" }, }); -const heads = (numbers: ReadonlyArray) => ({ +const heads = (numbers: ReadonlyArray, isCrossRepository = true) => ({ data: { repository: { pullRequests: { @@ -603,8 +603,11 @@ const heads = (numbers: ReadonlyArray) => ({ nodes: numbers.map((number) => ({ number, headRefOid: "abc123", - isCrossRepository: true, - headRepositoryOwner: { __typename: "User", login: "octocat" }, + isCrossRepository, + headRepositoryOwner: { + __typename: "User", + login: isCrossRepository ? "octocat" : "acme", + }, })), }, }, @@ -616,6 +619,7 @@ const workflowRuns = (ids: ReadonlyArray) => ({ id, name: id === 10 ? "build" : `run ${id}`, html_url: `https://example.com/${id}`, + pull_requests: [{ number: id === 12 ? 8 : 7 }], })), }); @@ -3020,47 +3024,92 @@ layer("GitHubPullRequestApi.layer", (it) => { }), ); - it.effect("does not approve action-required runs for a same-repository pull request", () => + it.effect.each([true, false])( + "finds and approves waiting workflows (fork: %s)", + (isCrossRepository) => + Effect.gen(function* () { + workflowApprovalRoutes( + () => workflowApprovalDetail("abc123", isCrossRepository), + heads([7], isCrossRepository), + workflowRuns([10, 11, 12]), + ); + const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi; + + yield* cli.runPullRequestAction({ + cwd: "/w", + repository: "acme/web", + host: "github.com", + number: 7, + action: "approve-workflows", + }); + + expect(variablesOf("PullRequestHeads")[0]).toEqual({ + owner: "acme", + name: "web", + head: "feat/page", + }); + expect(restCallsTo("actions/runs?")[0]?.path).toBe( + "repos/acme/web/actions/runs?head_sha=abc123&branch=feat%2Fpage&event=pull_request&status=action_required&per_page=100&page=1", + ); + expect(restCallsTo("/approve").map((call) => [call.method, call.path])).toEqual([ + ["POST", "repos/acme/web/actions/runs/10/approve"], + ["POST", "repos/acme/web/actions/runs/11/approve"], + ]); + assert.strictEqual(restCallsTo("actions/runs?").length, 3); + }), + ); + + it.effect.each([ + { label: "empty fork", pullRequests: [], isCrossRepository: true }, + { label: "empty same repository", pullRequests: [], isCrossRepository: false }, + { label: "missing fork", pullRequests: undefined, isCrossRepository: true }, + { label: "missing same repository", pullRequests: undefined, isCrossRepository: false }, + ])("handles $label workflow PR associations", ({ pullRequests, isCrossRepository }) => Effect.gen(function* () { - mockedExecute.mockReturnValueOnce( - Effect.succeed( - output( - encodeJson( - coreResponse({ - number: 7, - title: "Pull request 7", - url: "https://github.com/acme/web/pull/7", - headRefName: "feat/page", - headRefOid: "abc123", - isCrossRepository: false, - headRepositoryOwner: { __typename: "Organization", login: "acme" }, - baseRefName: "main", - createdAt: "2026-07-01T00:00:00Z", - updatedAt: "2026-07-02T00:00:00Z", - }), - ), - ), - ), + workflowApprovalRoutes( + () => workflowApprovalDetail("abc123", isCrossRepository), + heads([7], isCrossRepository), + { + workflow_runs: [{ ...workflowRuns([10]).workflow_runs[0], pull_requests: pullRequests }], + }, ); const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi; - - yield* cli.runPullRequestAction({ - cwd: "/w", - repository: "acme/web", - host: "github.com", - number: 7, - action: "approve-workflows", - }); - - expect(mockedExecute).toHaveBeenCalledTimes(1); + const result = yield* Effect.result( + cli.runPullRequestAction({ + cwd: "/w", + repository: "acme/web", + host: "github.com", + number: 7, + action: "approve-workflows", + }), + ); + expect(result._tag).toBe(isCrossRepository ? "Success" : "Failure"); + expect(restCallsTo("/approve").map((call) => call.path)).toEqual( + isCrossRepository ? ["repos/acme/web/actions/runs/10/approve"] : [], + ); }), ); - it.effect("finds and approves every workflow waiting on a maintainer", () => + it.effect("rechecks workflow PR association before approving", () => Effect.gen(function* () { - workflowApprovalRoutes(() => crossRepositoryDetail(), heads([7]), workflowRuns([10, 11])); + let runReads = 0; + mockedExecute.mockImplementation((call) => { + const answer = + call.kind === "rest" + ? { + workflow_runs: [ + { + ...workflowRuns([10]).workflow_runs[0], + pull_requests: [{ number: ++runReads === 1 ? 7 : 8 }], + }, + ], + } + : call.operationName === "PullRequestHeads" + ? heads([7]) + : workflowApprovalDetail(); + return Effect.succeed(output(encodeJson(answer))); + }); const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi; - yield* cli.runPullRequestAction({ cwd: "/w", repository: "acme/web", @@ -3068,26 +3117,60 @@ layer("GitHubPullRequestApi.layer", (it) => { number: 7, action: "approve-workflows", }); + expect(runReads).toBe(2); + expect(restCallsTo("/approve")).toEqual([]); + }), + ); - expect(variablesOf("PullRequestHeads")[0]).toEqual({ - owner: "acme", - name: "web", - head: "feat/page", + it.effect("revalidates same-repository workflow changes without a new head", () => + Effect.gen(function* () { + const sha = "a".repeat(40); + let runsChanged = false; + let reads = 0; + mockedExecute.mockImplementation((call) => { + if (call.kind !== "rest") return Effect.die("Expected REST"); + const isRuns = call.path.includes("actions/runs?"); + const changed = isRuns && runsChanged; + if (call.ifNoneMatch && !changed) return Effect.succeed(output("", false, false, {}, 304)); + const body = call.path.endsWith("/pulls/7") + ? { head: { sha, repo: { id: 1 } }, base: { repo: { id: 1 } } } + : isRuns + ? { workflow_runs: changed ? workflowRuns([10]).workflow_runs : [] } + : {}; + return Effect.succeed( + output(encodeJson(body), false, false, { etag: changed ? "new" : "old" }), + ); }); - expect(restCallsTo("actions/runs?")[0]?.path).toBe( - "repos/acme/web/actions/runs?head_sha=abc123&branch=feat%2Fpage&event=pull_request&status=action_required&per_page=100&page=1", - ); - expect(restCallsTo("/approve").map((call) => [call.method, call.path])).toEqual([ - ["POST", "repos/acme/web/actions/runs/10/approve"], - ["POST", "repos/acme/web/actions/runs/11/approve"], - ]); - assert.strictEqual(restCallsTo("actions/runs?").length, 3); - }), + const revalidate = yield* makeChecksRevalidator; + const read = Effect.gen(function* () { + reads++; + const known = yield* KnownWorkflowRuns; + expect(known?.runs.length ?? 0).toBe(runsChanged ? 1 : 0); + return { + state: "open" as const, + checks: [], + headSha: sha, + workflowApprovalsRequired: known?.runs.length ?? 0, + }; + }); + yield* revalidate(pullRequestInput, read); + yield* revalidate(pullRequestInput, read); + expect(reads).toBe(1); + runsChanged = true; + yield* revalidate(pullRequestInput, read); + expect(reads).toBe(2); + }).pipe( + Effect.provideService(GitHubRequestPolicy.PinnedGitHubCredential, { + host: "github.com", + token: Redacted.make("token"), + credentialFingerprint: "same-repository-cache", + }), + ), ); it.effect("counts revalidated runs that wait on a maintainer as GitHub reports them", () => Effect.gen(function* () { - workflowApprovalRoutes(() => crossRepositoryDetail(), heads([7]), workflowRuns([])); + workflowApprovalRoutes(() => workflowApprovalDetail(), heads([7]), workflowRuns([])); const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi; const runs = yield* cli @@ -3110,6 +3193,14 @@ layer("GitHubPullRequestApi.layer", (it) => { status: "completed", conclusion: "action_required", head_branch: "feat/page", + pull_requests: [{ number: 7 }], + }, + { + id: 12, + status: "completed", + conclusion: "action_required", + head_branch: "feat/page", + pull_requests: [{ number: 8 }], }, { id: 11, status: "completed", conclusion: "success", head_branch: "feat/page" }, ], @@ -3121,33 +3212,36 @@ layer("GitHubPullRequestApi.layer", (it) => { }), ); - it.effect("refuses a stale workflow approval after the pull request head changes", () => - Effect.gen(function* () { - let detailReads = 0; - workflowApprovalRoutes( - () => crossRepositoryDetail(++detailReads === 1 ? "abc123" : "def456"), - heads([7]), - workflowRuns([10]), - ); - const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi; + it.effect.each([true, false])( + "refuses a stale workflow approval after the head changes (fork: %s)", + (isCrossRepository) => + Effect.gen(function* () { + let detailReads = 0; + workflowApprovalRoutes( + () => + workflowApprovalDetail(++detailReads === 1 ? "abc123" : "def456", isCrossRepository), + heads([7], isCrossRepository), + workflowRuns([10]), + ); + const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi; - const error = yield* Effect.flip( - cli.runPullRequestAction({ - cwd: "/w", - repository: "acme/web", - host: "github.com", - number: 7, - action: "approve-workflows", - }), - ); + const error = yield* Effect.flip( + cli.runPullRequestAction({ + cwd: "/w", + repository: "acme/web", + host: "github.com", + number: 7, + action: "approve-workflows", + }), + ); - expect(error).toMatchObject({ - _tag: "GitHubWorkflowApprovalHeadChangedError", - number: 7, - }); - assert.strictEqual(detailReads, 2); - expect(restCallsTo("/approve")).toEqual([]); - }), + expect(error).toMatchObject({ + _tag: "GitHubWorkflowApprovalHeadChangedError", + number: 7, + }); + assert.strictEqual(detailReads, 2); + expect(restCallsTo("/approve")).toEqual([]); + }), ); it.effect("reads workflow runs and their pull request scope concurrently", () => @@ -3178,7 +3272,9 @@ layer("GitHubPullRequestApi.layer", (it) => { isCrossRepository: true, }); - expect(runs).toEqual([{ id: 10, name: "build", url: "https://example.com/10" }]); + expect(runs).toEqual([ + { pullRequestNumbers: [7], id: 10, name: "build", url: "https://example.com/10" }, + ]); }), ); @@ -3208,39 +3304,45 @@ layer("GitHubPullRequestApi.layer", (it) => { "repos/acme/web/actions/runs?head_sha=abc123&per_page=100", ); expect(runs).toEqual([ - { id: 0, name: "queued", url: null }, - { id: 1, name: "in_progress", url: null }, + { pullRequestNumbers: [], id: 0, name: "queued", url: null }, + { pullRequestNumbers: [], id: 1, name: "in_progress", url: null }, ]); }), ); - it.effect("refuses workflow approval when one head belongs to several pull requests", () => - Effect.gen(function* () { - workflowApprovalRoutes(() => crossRepositoryDetail(), heads([7, 8]), workflowRuns([])); - const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi; + it.effect.each([true, false])( + "refuses ambiguous workflow approval (fork: %s)", + (isCrossRepository) => + Effect.gen(function* () { + workflowApprovalRoutes( + () => workflowApprovalDetail("abc123", isCrossRepository), + heads([7, 8], isCrossRepository), + workflowRuns([]), + ); + const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi; - const error = yield* Effect.flip( - cli.listWorkflowRunsRequiringApproval({ - cwd: "/w", - repository: "acme/web", - host: "github.com", - number: 7, - headSha: "abc123", - headBranch: "feat/page", - headRepositoryOwner: "octocat", - isCrossRepository: true, - }), - ); + const error = yield* Effect.flip( + cli.listWorkflowRunsRequiringApproval({ + cwd: "/w", + repository: "acme/web", + host: "github.com", + number: 7, + headSha: "abc123", + headBranch: "feat/page", + headRepositoryOwner: isCrossRepository ? "octocat" : "acme", + isCrossRepository, + }), + ); - expect(error).toMatchObject({ - _tag: "GitHubWorkflowApprovalRefusedError", - reason: "head-not-unique", - number: 7, - observedCount: 2, - limit: 1_000, - }); - expect(error.message).toContain("instead of uniquely matching #7"); - }), + expect(error).toMatchObject({ + _tag: "GitHubWorkflowApprovalRefusedError", + reason: "head-not-unique", + number: 7, + observedCount: 2, + limit: 1_000, + }); + expect(error.message).toContain("instead of uniquely matching #7"); + }), ); it.effect("refuses workflow approval when the head list stops before its end", () => @@ -3250,7 +3352,7 @@ layer("GitHubPullRequestApi.layer", (it) => { hasNextPage: true, endCursor: "same", } as never; - workflowApprovalRoutes(() => crossRepositoryDetail(), repeating, workflowRuns([])); + workflowApprovalRoutes(() => workflowApprovalDetail(), repeating, workflowRuns([])); const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi; const error = yield* Effect.flip( diff --git a/packages/source-control-github/src/server/GitHubPullRequestApi.ts b/packages/source-control-github/src/server/GitHubPullRequestApi.ts index 567415248ba9d..870ff56eb21dd 100644 --- a/packages/source-control-github/src/server/GitHubPullRequestApi.ts +++ b/packages/source-control-github/src/server/GitHubPullRequestApi.ts @@ -601,7 +601,7 @@ export class GitHubPullRequestApi extends Context.Service< readonly headSha: string; readonly headBranch: string; readonly headRepositoryOwner: string; - readonly isCrossRepository: true; + readonly isCrossRepository: boolean; }) => Effect.Effect, GitHubPullRequestApiError>; /** The head's workflow runs that have not finished, the latest 100. */ @@ -1730,6 +1730,7 @@ export const make = Effect.gen(function* () { run.head_branch === input.headBranch ? [ { + pullRequestNumbers: run.pull_requests?.map((pr) => pr.number) ?? [], id: run.id, name: run.name?.trim() || `Workflow run ${run.id}`, url: run.html_url?.trim() || null, @@ -1771,7 +1772,7 @@ export const make = Effect.gen(function* () { const exactHeads = heads.filter( (pullRequest) => pullRequest.headSha === input.headSha && - pullRequest.isCrossRepository === true && + pullRequest.isCrossRepository === input.isCrossRepository && pullRequest.headRepositoryOwner?.toLowerCase() === input.headRepositoryOwner.toLowerCase(), ); @@ -1816,7 +1817,24 @@ export const make = Effect.gen(function* () { ), ], { concurrency: 2 }, - ).pipe(Effect.map(([, runs]) => runs)); + ).pipe( + Effect.flatMap(([, runs]) => + !input.isCrossRepository && runs.some((run) => run.pullRequestNumbers.length === 0) + ? Effect.fail( + workflowApprovalReadError( + input.cwd, + new Error("GitHub omitted workflow run pull-request associations."), + ), + ) + : Effect.succeed( + runs.filter((run) => + run.pullRequestNumbers.length === 0 + ? input.isCrossRepository + : run.pullRequestNumbers.includes(input.number), + ), + ), + ), + ); const simpleActionMutations = { "disable-auto-merge": (pullRequestId: string) => @@ -2819,7 +2837,6 @@ export const make = Effect.gen(function* () { const { owner, name } = parseRepositorySelector(input.repository); return getPullRequestDetail(input).pipe( Effect.flatMap((detail) => { - if (detail.isCrossRepository !== true) return Effect.void; if (detail.headSha == null || detail.headRepositoryOwner == null) { return Effect.fail( new GitHubWorkflowApprovalHeadUnavailableError({ @@ -2836,7 +2853,7 @@ export const make = Effect.gen(function* () { headSha: expectedHeadSha, headBranch: expectedHeadBranch, headRepositoryOwner: expectedHeadRepositoryOwner, - isCrossRepository: true, + isCrossRepository: detail.isCrossRepository === true, }).pipe( Effect.flatMap((runs) => Effect.forEach( @@ -2853,7 +2870,7 @@ export const make = Effect.gen(function* () { ); } if ( - current.isCrossRepository !== true || + current.isCrossRepository !== detail.isCrossRepository || current.headSha !== expectedHeadSha || current.headBranch !== expectedHeadBranch || current.headRepositoryOwner.toLowerCase() !== @@ -2871,7 +2888,7 @@ export const make = Effect.gen(function* () { headSha: current.headSha, headBranch: current.headBranch, headRepositoryOwner: current.headRepositoryOwner, - isCrossRepository: true, + isCrossRepository: detail.isCrossRepository === true, }); }), Effect.flatMap((currentRuns) => diff --git a/packages/source-control-github/src/server/GitHubPullRequestProvider.test.ts b/packages/source-control-github/src/server/GitHubPullRequestProvider.test.ts index 5911bd3c3a117..065a6d46078b6 100644 --- a/packages/source-control-github/src/server/GitHubPullRequestProvider.test.ts +++ b/packages/source-control-github/src/server/GitHubPullRequestProvider.test.ts @@ -419,6 +419,7 @@ describe("gitHubViewerPermissions", () => { listWorkflowRunsRequiringApproval: () => Effect.succeed([ { + pullRequestNumbers: [7], id: 123, name: "contributor tests", url: "https://github.com/acme/web/actions/runs/123", @@ -510,11 +511,68 @@ it.effect("adds unstarted same-repository workflow runs as pending, not as appro // Run 201 is represented by its running job; run 202 is queued before any job exists. listUnfinishedWorkflowRuns: () => Effect.succeed([ - { id: 201, name: "Lint", url: "https://github.com/acme/web/actions/runs/201" }, - { id: 202, name: "CI", url: "https://github.com/acme/web/actions/runs/202" }, + { + pullRequestNumbers: [], + id: 201, + name: "Lint", + url: "https://github.com/acme/web/actions/runs/201", + }, + { + pullRequestNumbers: [], + id: 202, + name: "CI", + url: "https://github.com/acme/web/actions/runs/202", + }, ]), + listWorkflowRunsRequiringApproval: () => Effect.succeed([]), + getViewerAccess: () => + Effect.succeed({ + canWrite: true, + canTriage: true, + canUpdate: true, + didAuthor: false, + mergeCapabilities: { merge: true, squash: true, rebase: true }, + autoMergeAllowed: true, + }), + }), + ), + ), +); + +it.effect("discovers workflow approval for a same-repository bot pull request", () => + Effect.gen(function* () { + const provider = yield* make; + const detail = yield* provider.getChangeRequest({ + cwd: "/w", + repository: "acme/web", + host: "github.com", + number: 7, + }); + + expect(detail.workflowApprovalsRequired).toBe(1); + expect(detail.checks).toEqual([ + { + name: "bot tests", + status: "action-required", + description: "A maintainer must approve this workflow before it can run.", + url: "https://github.com/acme/web/actions/runs/123", + }, + ]); + }).pipe( + Effect.provide( + Layer.mock(GitHubPullRequestApi.GitHubPullRequestApi)({ + revalidateChecks: (_input, read) => read, + getPullRequestDetail: () => Effect.succeed({ ...openDetail, isCrossRepository: false }), + listUnfinishedWorkflowRuns: () => Effect.succeed([]), listWorkflowRunsRequiringApproval: () => - Effect.die("same-repository pull requests must not probe fork workflow approvals"), + Effect.succeed([ + { + pullRequestNumbers: [7], + id: 123, + name: "bot tests", + url: "https://github.com/acme/web/actions/runs/123", + }, + ]), getViewerAccess: () => Effect.succeed({ canWrite: true, diff --git a/packages/source-control-github/src/server/GitHubPullRequestProvider.ts b/packages/source-control-github/src/server/GitHubPullRequestProvider.ts index e05724a6e4d67..f026735fa525c 100644 --- a/packages/source-control-github/src/server/GitHubPullRequestProvider.ts +++ b/packages/source-control-github/src/server/GitHubPullRequestProvider.ts @@ -335,7 +335,7 @@ export const make = Effect.gen(function* () { const readChecks = (input: ProviderRepositoryRef & { readonly number: number }) => cli.getPullRequestDetail(input).pipe( Effect.flatMap((pullRequest) => - (pullRequest.state !== "open" || pullRequest.isCrossRepository !== true + (pullRequest.state !== "open" ? Effect.succeed({ runs: [] as ReadonlyArray, unavailable: false, @@ -351,7 +351,7 @@ export const make = Effect.gen(function* () { headSha: pullRequest.headSha, headBranch: pullRequest.headBranch, headRepositoryOwner: pullRequest.headRepositoryOwner, - isCrossRepository: true, + isCrossRepository: pullRequest.isCrossRepository === true, }) .pipe( Effect.matchEffect({ diff --git a/packages/source-control-github/src/server/gitHubConditionalChecks.ts b/packages/source-control-github/src/server/gitHubConditionalChecks.ts index e41747b15a2f6..3708745ebdebd 100644 --- a/packages/source-control-github/src/server/gitHubConditionalChecks.ts +++ b/packages/source-control-github/src/server/gitHubConditionalChecks.ts @@ -26,6 +26,7 @@ const decodeHead = Schema.decodeUnknownEffect(Schema.fromJsonString(HeadSchema)) class ChecksUnavailable extends Schema.TaggedError()("ChecksUnavailable", {}) {} const WorkflowRunSchema = Schema.Struct({ + pull_requests: Schema.optional(Schema.Array(Schema.Struct({ number: Schema.Int }))), id: Schema.Int, name: Schema.optional(Schema.NullOr(Schema.String)), html_url: Schema.optional(Schema.NullOr(Schema.String)), @@ -141,14 +142,11 @@ export const makeChecksRevalidator = Effect.gen(function* () { if ((yield* get(`${root}/pulls/${input.number}`, true)) === null) return yield* read; const head = entry.head; if (head === null) return yield* fail(200); - const runsEndpoint = - head.head.repo?.id !== head.base.repo.id - ? `${root}/actions/runs?head_sha=${head.head.sha}&event=pull_request` - : null; + const runsEndpoint = `${root}/actions/runs?head_sha=${head.head.sha}&event=pull_request`; const endpoints = [ `${root}/commits/${head.head.sha}/check-runs?filter=all`, `${root}/commits/${head.head.sha}/status`, - ...(runsEndpoint === null ? [] : [runsEndpoint]), + runsEndpoint, ]; const runPages: Array = []; // Each endpoint has its own cursor; only pages within one endpoint depend on each other. @@ -176,15 +174,14 @@ export const makeChecksRevalidator = Effect.gen(function* () { const pages = runPages.map((endpoint) => decodeWorkflowRuns(entry.validators.get(endpoint)?.body ?? ""), ); - const known = - runsEndpoint !== null && pages.every(Option.isSome) - ? { - headSha: head.head.sha, - runs: pages.flatMap((page) => - Option.isSome(page) ? page.value.workflow_runs : [], - ), - } - : null; + const known = pages.every(Option.isSome) + ? { + headSha: head.head.sha, + runs: pages.flatMap((page) => + Option.isSome(page) ? page.value.workflow_runs : [], + ), + } + : null; const fresh = yield* read.pipe(Effect.provideService(KnownWorkflowRuns, known)); const value = { state: fresh.state, diff --git a/packages/source-control-github/src/server/gitHubPullRequestJson.ts b/packages/source-control-github/src/server/gitHubPullRequestJson.ts index da150603f9be2..0251db8976220 100644 --- a/packages/source-control-github/src/server/gitHubPullRequestJson.ts +++ b/packages/source-control-github/src/server/gitHubPullRequestJson.ts @@ -227,6 +227,7 @@ const RawWorkflowRunsSchema = Schema.Struct({ workflow_runs: Schema.Array( Schema.Struct({ id: Schema.Int, + pull_requests: Schema.optional(Schema.Array(Schema.Struct({ number: Schema.Int }))), name: Schema.optional(Schema.NullOr(Schema.String)), html_url: Schema.optional(Schema.NullOr(Schema.String)), status: Schema.optional(Schema.NullOr(Schema.String)), @@ -388,6 +389,7 @@ export interface GitHubPullRequestDetail extends GitHubPullRequestListItem { } export interface GitHubWorkflowRunApproval { + readonly pullRequestNumbers: ReadonlyArray; readonly id: number; readonly name: string; readonly url: string | null; @@ -1175,6 +1177,7 @@ export function decodeWorkflowRunsJson( if (!Result.isSuccess(decoded)) return Result.fail(decoded.failure); return Result.succeed({ runs: decoded.success.workflow_runs.map((run) => ({ + pullRequestNumbers: run.pull_requests?.map((pr) => pr.number) ?? [], id: run.id, name: trimmed(run.name) ?? `Workflow run ${run.id}`, url: trimmed(run.html_url), @@ -1202,6 +1205,7 @@ export function decodeUnfinishedWorkflowRunsJson( decoded.success.workflow_runs .filter((run) => UNFINISHED_WORKFLOW_RUN_STATUSES.has(run.status ?? "")) .map((run) => ({ + pullRequestNumbers: run.pull_requests?.map((pr) => pr.number) ?? [], id: run.id, name: trimmed(run.name) ?? `Workflow run ${run.id}`, url: trimmed(run.html_url), From 55bca4875cd316e5f7b16b78e7d04124050d8871 Mon Sep 17 00:00:00 2001 From: Victor Date: Tue, 24 Nov 2026 18:56:12 -0600 Subject: [PATCH 011/880] fix(server): detect new repos in folders named like ..cache right away (#42507) Co-authored-by: Julius Marminge (cherry picked from commit 622d65faaf4cf737a89aa4347bc18f184f6b7ca2) --- apps/server/src/vcs/VcsDriverRegistry.test.ts | 20 +++++++++++-------- apps/server/src/vcs/VcsDriverRegistry.ts | 4 +++- 2 files changed, 15 insertions(+), 9 deletions(-) diff --git a/apps/server/src/vcs/VcsDriverRegistry.test.ts b/apps/server/src/vcs/VcsDriverRegistry.test.ts index 6fee790bc4bda..dc75b2ab41b3c 100644 --- a/apps/server/src/vcs/VcsDriverRegistry.test.ts +++ b/apps/server/src/vcs/VcsDriverRegistry.test.ts @@ -92,21 +92,25 @@ describe("VcsDriverRegistry", () => { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; const parentDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-vcs-registry-" }); - const projectDir = path.join(parentDir, "project"); yield* fs.makeDirectory(path.join(parentDir, ".git")); - yield* fs.makeDirectory(projectDir); const calls: string[] = []; yield* Effect.gen(function* () { const registry = yield* VcsDriverRegistry.VcsDriverRegistry; - assert.equal((yield* registry.detect({ cwd: projectDir }))?.repository.rootPath, parentDir); + for (const [repoRel, cwdRel] of [ + ["project", "project"], + ["..cache", path.join("..cache", "sub")], + ] as const) { + const nestedRepoDir = path.join(parentDir, repoRel); + const cwd = path.join(parentDir, cwdRel); + yield* fs.makeDirectory(cwd, { recursive: true }); - yield* fs.makeDirectory(path.join(projectDir, ".git")); + assert.equal((yield* registry.detect({ cwd }))?.repository.rootPath, parentDir); - assert.equal( - (yield* registry.detect({ cwd: projectDir }))?.repository.rootPath, - projectDir, - ); + yield* fs.makeDirectory(path.join(nestedRepoDir, ".git")); + + assert.equal((yield* registry.detect({ cwd }))?.repository.rootPath, nestedRepoDir); + } }).pipe(Effect.provide(makeDiskBackedLayer(parentDir, calls))); }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); diff --git a/apps/server/src/vcs/VcsDriverRegistry.ts b/apps/server/src/vcs/VcsDriverRegistry.ts index 5bf7263ebe834..c91d794e3b751 100644 --- a/apps/server/src/vcs/VcsDriverRegistry.ts +++ b/apps/server/src/vcs/VcsDriverRegistry.ts @@ -122,7 +122,9 @@ export const make = Effect.gen(function* () { // Symlinks can put cwd outside root; then inspect cwd alone. const foldersBelowRoot = (cwd: string, rootPath: string) => { const relative = path.relative(path.resolve(rootPath), path.resolve(cwd)); - if (relative.startsWith("..") || path.isAbsolute(relative)) return [cwd]; + if (relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) { + return [cwd]; + } return Array.from({ length: relative.split(path.sep).length }, (_, levelsUp) => path.resolve(cwd, ...Array(levelsUp).fill("..")), ); From b56d0fb3879f6f7d1e0fd4375e6eee07fb6570c2 Mon Sep 17 00:00:00 2001 From: Yash Singh Date: Tue, 24 Nov 2026 19:05:33 -0600 Subject: [PATCH 012/880] fix(pr): keep CI approval in sync with running checks (#42523) (cherry picked from commit 2514a5ce5eda2851c79e039138d41274fa4aa4bd) --- .../pullRequest/PullRequestService.test.ts | 11 +++- .../src/pullRequest/PullRequestService.ts | 3 ++ .../pullRequest/pullRequestDetail.logic.ts | 2 +- .../src/pullRequestChecks.test.ts | 22 ++++++-- .../client-runtime/src/pullRequestChecks.ts | 21 +++++--- .../src/state/pullRequests.test.ts | 54 +++++++++++++++++++ .../client-runtime/src/state/pullRequests.ts | 36 +++++++++---- packages/contracts/src/pullRequest.ts | 1 + .../src/server/PullRequestProvider.ts | 2 +- .../src/server/GitHubPullRequestApi.ts | 1 + .../server/GitHubPullRequestProvider.test.ts | 2 +- .../src/server/GitHubPullRequestProvider.ts | 6 ++- .../src/server/GitHubRest.test.ts | 23 ++++++++ .../src/server/GitHubRest.ts | 31 +++++++---- .../src/server/gitHubConditionalChecks.ts | 3 ++ 15 files changed, 182 insertions(+), 36 deletions(-) diff --git a/apps/server/src/pullRequest/PullRequestService.test.ts b/apps/server/src/pullRequest/PullRequestService.test.ts index aa05cceee3557..1ec6988fe6c15 100644 --- a/apps/server/src/pullRequest/PullRequestService.test.ts +++ b/apps/server/src/pullRequest/PullRequestService.test.ts @@ -3877,7 +3877,15 @@ it.effect.each(["github", "azure-devops"])( getChangeRequest: () => Effect.succeed({ ...hostedChangeRequest("Description"), - checks: [{ name: "build", status: "success", description: null, url: null }], + checks: [ + { + name: "build", + status: provider === "github" ? "action-required" : "success", + description: null, + url: null, + }, + ], + ...(provider === "github" ? { workflowApprovalsRequired: 1 } : {}), }), getChangeRequestChecks: () => Effect.sync(() => { @@ -3893,6 +3901,7 @@ it.effect.each(["github", "azure-devops"])( state: detail.state, checks: detail.checks, observedAt: detail.observedAt, + ...(provider === "github" ? { workflowApprovalsRequired: 1 } : {}), }); expect(reads).toBe(0); yield* TestClock.adjust("16 seconds"); diff --git a/apps/server/src/pullRequest/PullRequestService.ts b/apps/server/src/pullRequest/PullRequestService.ts index f3ac5cbe0d3d0..b6e4bf716ecca 100644 --- a/apps/server/src/pullRequest/PullRequestService.ts +++ b/apps/server/src/pullRequest/PullRequestService.ts @@ -3434,6 +3434,9 @@ export const make = Effect.gen(function* () { state: value.state, checks: value.checks, observedAt: value.observedAt, + ...(value.workflowApprovalsRequired === undefined + ? {} + : { workflowApprovalsRequired: value.workflowApprovalsRequired }), }); } recordStats( diff --git a/apps/web/src/components/pullRequest/pullRequestDetail.logic.ts b/apps/web/src/components/pullRequest/pullRequestDetail.logic.ts index e69fd93773e89..b0d2c8e22232d 100644 --- a/apps/web/src/components/pullRequest/pullRequestDetail.logic.ts +++ b/apps/web/src/components/pullRequest/pullRequestDetail.logic.ts @@ -1626,7 +1626,7 @@ const ACTION_NEEDS_HOST_REFRESH: Record = { "disable-auto-merge": false, revert: false, "delete-branch": false, - "approve-workflows": true, + "approve-workflows": false, }; export function pullRequestActionNeedsHostRefresh(action: PullRequestAction): boolean { diff --git a/packages/client-runtime/src/pullRequestChecks.test.ts b/packages/client-runtime/src/pullRequestChecks.test.ts index 8b9f46451d980..03423297e896b 100644 --- a/packages/client-runtime/src/pullRequestChecks.test.ts +++ b/packages/client-runtime/src/pullRequestChecks.test.ts @@ -35,19 +35,35 @@ describe("resolvePullRequestDetailChecks", () => { url: null, description: null, }; - const cached = detail({ observedAt: 1_000, checks: [pending] }); + const cached = detail({ observedAt: 1_000, checks: [pending], workflowApprovalsRequired: 1 }); const checks = { state: "open" as const, checks: [{ ...pending, status: "success" as const }], observedAt: 2_000, + workflowApprovalsRequired: 0, }; const resolved = resolvePullRequestDetailChecks(cached, checks, false); expect(resolved?.checks).toEqual(checks.checks); + expect(resolved?.workflowApprovalsRequired).toBe(0); + expect( + resolvePullRequestDetailChecks(cached, { ...checks, workflowApprovalsRequired: 2 }, false) + ?.workflowApprovalsRequired, + ).toBe(2); expect(resolved?.observedAt).toBe(1_000); expect( resolvePullRequestDetailChecks(cached, { state: checks.state, checks: checks.checks }, true) - ?.checks, - ).toEqual(checks.checks); + ?.workflowApprovalsRequired, + ).toBe(0); + expect( + resolvePullRequestDetailChecks( + cached, + { + state: checks.state, + checks: [{ ...pending, status: "action-required", placeholder: true }], + }, + true, + )?.workflowApprovalsRequired, + ).toBe(1); const refreshed = detail({ observedAt: 3_000, checks: [pending] }); expect(resolvePullRequestDetailChecks(refreshed, checks, true)).toBe(refreshed); }); diff --git a/packages/client-runtime/src/pullRequestChecks.ts b/packages/client-runtime/src/pullRequestChecks.ts index 11191ffb2379e..0bb8c045eeeb1 100644 --- a/packages/client-runtime/src/pullRequestChecks.ts +++ b/packages/client-runtime/src/pullRequestChecks.ts @@ -10,13 +10,20 @@ export function resolvePullRequestDetailChecks( detail.observedAt !== undefined && checks.observedAt !== undefined ? checks.observedAt >= detail.observedAt : checksAreNewer; - return newer - ? { - ...detail, - state: detail.state === "merged" ? "merged" : checks.state, - checks: checks.checks, - } - : detail; + if (!newer) return detail; + // Older servers omit the count. Their check rows can still confirm that nothing needs approval. + const workflowApprovalsRequired = + checks.workflowApprovalsRequired ?? + (detail.workflowApprovalsRequired !== undefined && + !checks.checks.some((check) => check.status === "action-required") + ? 0 + : detail.workflowApprovalsRequired); + return { + ...detail, + state: detail.state === "merged" ? "merged" : checks.state, + checks: checks.checks, + ...(workflowApprovalsRequired === undefined ? {} : { workflowApprovalsRequired }), + }; } /** Checks still running are worth a tighter poll than a settled head. */ diff --git a/packages/client-runtime/src/state/pullRequests.test.ts b/packages/client-runtime/src/state/pullRequests.test.ts index 3044463eb0e2b..0408b8412e298 100644 --- a/packages/client-runtime/src/state/pullRequests.test.ts +++ b/packages/client-runtime/src/state/pullRequests.test.ts @@ -1185,6 +1185,60 @@ function actionReplyClient(overrides: Record = {}) { } as unknown as WsRpcProtocolClient; } +it.effect("waits for a fresh check status before clearing a workflow approval", () => + Effect.gen(function* () { + const afterApproval = yield* Deferred.make(); + const checksStarted = yield* Deferred.make(); + const staleReadStarted = yield* Deferred.make(); + const approvalStarted = yield* Deferred.make(); + const commitApproval = yield* Deferred.make(); + let reads = 0; + let approved = false; + const client = actionReplyClient({ + [WS_METHODS.pullRequestsRunAction]: () => + Effect.gen(function* () { + yield* Deferred.succeed(approvalStarted, undefined); + yield* Deferred.await(commitApproval); + approved = true; + }), + [WS_METHODS.pullRequestsChecks]: () => + Effect.gen(function* () { + if (++reads === 1) return { state: "open", checks: [], workflowApprovalsRequired: 1 }; + if (!approved) { + yield* Deferred.succeed(staleReadStarted, undefined); + return yield* Effect.never; + } + yield* Deferred.succeed(checksStarted, undefined); + yield* Deferred.await(afterApproval); + return { state: "open", checks: [], workflowApprovalsRequired: 0 }; + }), + }); + const { atoms, registry } = yield* makeTestRuntime(client); + const target = { environmentId: TARGET.environmentId, input: actionReference }; + const checks = atoms.checks(target); + yield* AtomRegistry.mount(registry, checks); + yield* AtomRegistry.getResult(registry, checks); + const action = yield* atoms.runAction + .run(registry, { ...target, input: { ...actionReference, action: "approve-workflows" } }) + .pipe(Effect.forkChild); + yield* Deferred.await(approvalStarted); + registry.refresh(checks); + yield* Deferred.await(staleReadStarted); + yield* Deferred.succeed(commitApproval, undefined); + yield* Effect.raceFirst( + Deferred.await(checksStarted), + Fiber.join(action).pipe( + Effect.andThen(Effect.die("Approval finished before refreshing the checks")), + ), + ); + yield* Deferred.succeed(afterApproval, undefined); + yield* Fiber.join(action); + expect(Option.getOrThrow(AsyncResult.value(registry.get(checks)))).toMatchObject({ + workflowApprovalsRequired: 0, + }); + }), +); + it.effect("shows an action's reply in loaded readers and moves list rows without reads", () => Effect.gen(function* () { const reads: string[] = []; diff --git a/packages/client-runtime/src/state/pullRequests.ts b/packages/client-runtime/src/state/pullRequests.ts index 01fb80d817645..c91f9d92d8af7 100644 --- a/packages/client-runtime/src/state/pullRequests.ts +++ b/packages/client-runtime/src/state/pullRequests.ts @@ -42,6 +42,7 @@ import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity"; import { type AtomCommand, + awaitAtomResult, createAtomCommandScheduler, createEnvironmentRpcCommand, createEnvironmentRpcQueryAtomFamily, @@ -1373,21 +1374,34 @@ export function createPullRequestEnvironmentAtoms( execute: runAction, onStart: (_target, registry) => readsInFlight(registry), // Loaded readers show the reply, or re-read when the host's reply lacked the pull request. - onSuccess: ({ environmentId, input }, registry, reply, readsBeforeSend) => - applyActionReply( + onSuccess: Effect.fnUntraced(function* ( + { environmentId, input }, + registry, + reply, + readsBeforeSend: ReadonlySet | undefined, + ) { + const reference = pullRequestReference(input); + yield* applyActionReply( registry, environmentId, - pullRequestReference(input), + reference, reply, readsBeforeSend ?? new Set(), - ).pipe( - // The re-read a bare reply starts would otherwise show the old state until it answers. - Effect.andThen( - reply === undefined - ? acceptEdit(registry, environmentId, actionEdit(input), true) - : Effect.void, - ), - ), + ); + // The re-read a bare reply starts would otherwise show the old state until it answers. + if (reply === undefined) + yield* acceptEdit(registry, environmentId, actionEdit(input), true); + if (input.action !== "approve-workflows") return; + const query = checks({ environmentId, input: reference }); + if (!registry.getNodes().get(query)?.listeners.size) return; + if ( + Option.getOrUndefined(loadedValue(registry, query)) === null + ) + return; + // A pending read may have started before GitHub applied the approval. + if (registry.get(query).waiting) registry.refresh(query); + yield* awaitAtomResult(registry, query, { refresh: true }).pipe(Effect.ignore); + }), scheduler: commandScheduler, concurrency: serialPerEnvironment, }), diff --git a/packages/contracts/src/pullRequest.ts b/packages/contracts/src/pullRequest.ts index 61e0b671589ff..96c8727ef4e8e 100644 --- a/packages/contracts/src/pullRequest.ts +++ b/packages/contracts/src/pullRequest.ts @@ -702,6 +702,7 @@ export const PullRequestChecks = Schema.Struct({ observedAt: Schema.optional(Schema.Finite), state: PullRequestState, checks: Schema.Array(PullRequestCheck), + workflowApprovalsRequired: Schema.optional(NonNegativeInt), }); export type PullRequestChecks = typeof PullRequestChecks.Type; diff --git a/packages/source-control-core/src/server/PullRequestProvider.ts b/packages/source-control-core/src/server/PullRequestProvider.ts index ec6ae07b5d5d6..4e452e440d444 100644 --- a/packages/source-control-core/src/server/PullRequestProvider.ts +++ b/packages/source-control-core/src/server/PullRequestProvider.ts @@ -438,7 +438,7 @@ export interface PullRequestProviderApi { readonly getChangeRequestChecks?: ( input: ProviderRepositoryRef & { readonly number: number }, - ) => Effect.Effect, PullRequestProviderError>; + ) => Effect.Effect, PullRequestProviderError>; readonly getChangeRequest: ( input: ProviderRepositoryRef & { readonly number: number }, diff --git a/packages/source-control-github/src/server/GitHubPullRequestApi.ts b/packages/source-control-github/src/server/GitHubPullRequestApi.ts index 870ff56eb21dd..c77af7fffbab9 100644 --- a/packages/source-control-github/src/server/GitHubPullRequestApi.ts +++ b/packages/source-control-github/src/server/GitHubPullRequestApi.ts @@ -2899,6 +2899,7 @@ export const make = Effect.gen(function* () { operation: "approveWorkflowRun", method: "POST", path: `repos/${owner}/${name}/actions/runs/${run.id}/approve`, + discardSuccessBody: true, }) .pipe(Effect.asVoid) : Effect.void, diff --git a/packages/source-control-github/src/server/GitHubPullRequestProvider.test.ts b/packages/source-control-github/src/server/GitHubPullRequestProvider.test.ts index 065a6d46078b6..7d305ac4b7873 100644 --- a/packages/source-control-github/src/server/GitHubPullRequestProvider.test.ts +++ b/packages/source-control-github/src/server/GitHubPullRequestProvider.test.ts @@ -349,7 +349,7 @@ describe("gitHubViewerPermissions", () => { if (readChecks === undefined) return yield* Effect.die("checks read missing"); expect( yield* readChecks({ cwd: "/w", repository: "acme/web", host: "github.com", number: 7 }), - ).toEqual({ state: detail.state, checks: detail.checks }); + ).toEqual({ state: detail.state, checks: detail.checks, workflowApprovalsRequired: 1 }); expect(detail.workflowApprovalsRequired).toBe(1); expect(detail.checks).toEqual([ { diff --git a/packages/source-control-github/src/server/GitHubPullRequestProvider.ts b/packages/source-control-github/src/server/GitHubPullRequestProvider.ts index f026735fa525c..88dcc1aea2ed9 100644 --- a/packages/source-control-github/src/server/GitHubPullRequestProvider.ts +++ b/packages/source-control-github/src/server/GitHubPullRequestProvider.ts @@ -503,7 +503,11 @@ export const make = Effect.gen(function* () { getChangeRequestChecks: (input) => cli.revalidateChecks(input, readChecks(input)).pipe( - Effect.map(({ state, checks }) => ({ state, checks })), + Effect.map(({ state, checks, workflowApprovalsRequired }) => ({ + state, + checks, + ...(workflowApprovalsRequired === undefined ? {} : { workflowApprovalsRequired }), + })), Effect.mapError(fail("getChangeRequestChecks")), ), diff --git a/packages/source-control-github/src/server/GitHubRest.test.ts b/packages/source-control-github/src/server/GitHubRest.test.ts index 9d82bee19752c..4458a8a3981db 100644 --- a/packages/source-control-github/src/server/GitHubRest.test.ts +++ b/packages/source-control-github/src/server/GitHubRest.test.ts @@ -114,6 +114,29 @@ describe("environmentToken", () => { }); describe("GitHubRest", () => { + it.effect("acknowledges workflow approval without waiting for an unused body", () => { + const { layer } = harness( + () => + new Response( + new ReadableStream({ + start: (controller) => controller.error(new Error("Response body interrupted")), + }), + { status: 201 }, + ), + ); + return Effect.gen(function* () { + const api = yield* GitHubRest.GitHubRest; + const response = yield* api.rest({ + host: "github.com", + operation: "approveWorkflowRun", + method: "POST", + path: "repos/acme/web/actions/runs/10/approve", + discardSuccessBody: true, + }); + expect(response).toMatchObject({ status: 201, body: "" }); + }).pipe(Effect.provide(layer)); + }); + it.live("routes REST and GraphQL through gh's plain HTTP Unix socket", () => Effect.gen(function* () { const directory = yield* Effect.acquireRelease( diff --git a/packages/source-control-github/src/server/GitHubRest.ts b/packages/source-control-github/src/server/GitHubRest.ts index 35bdfb39cc5c2..b437662be9e6d 100644 --- a/packages/source-control-github/src/server/GitHubRest.ts +++ b/packages/source-control-github/src/server/GitHubRest.ts @@ -39,6 +39,8 @@ export interface GitHubRestInput { /** Revalidate cached answers; 304 returns successfully without spending quota. */ readonly ifNoneMatch?: string; readonly maxResponseBytes?: number; + /** Use the status and headers for a success, but still read error bodies. */ + readonly discardSuccessBody?: boolean; /** Defaults to 30 seconds; a whole pull request's patch may need longer. */ readonly timeout?: Duration.Input; /** Overrides `SourceControlRateLimit.Interactive` for this one request. */ @@ -114,6 +116,7 @@ function classify(input: { /** @public */ export const make = Effect.gen(function* () { const httpClient = yield* HttpClient.HttpClient; + const scopedClient = HttpClient.withScope(httpClient); const policy = yield* GitHubRequestPolicy.GitHubRequestPolicy; const send = Effect.fn("GitHubRest.send")(function* (input: { @@ -124,6 +127,7 @@ export const make = Effect.gen(function* () { readonly timeout?: Duration.Input | undefined; readonly allowReserve: boolean; readonly acceptNotModified: boolean; + readonly discardSuccessBody: boolean; }) { const host = normalizeHost(input.host); // Query strings can expose SHAs or branches in traces. @@ -143,22 +147,27 @@ export const make = Effect.gen(function* () { }, (headers) => Effect.gen(function* () { - const response: HttpClientResponse.HttpClientResponse = yield* httpClient + const client = input.discardSuccessBody ? scopedClient : httpClient; + const response: HttpClientResponse.HttpClientResponse = yield* client .execute(input.request.pipe(HttpClientRequest.setHeaders(headers))) .pipe( // Client spans expose SHAs and branches through url.full/url.query. Effect.provideService(HttpClient.TracerDisabledWhen, () => true), ); - const collected = yield* collectUint8StreamText({ - stream: response.stream, - maxBytes: input.maxResponseBytes, - }).pipe( - Effect.catchIf( - (error) => error.reason._tag === "EmptyBodyError", - () => Effect.succeed({ text: "", truncated: false, invalidUtf8: false }), - ), - ); const { status, headers: responseHeaders } = response; + const emptyBody = { text: "", truncated: false, invalidUtf8: false }; + const collected = + input.discardSuccessBody && status >= 200 && status < 300 + ? emptyBody + : yield* collectUint8StreamText({ + stream: response.stream, + maxBytes: input.maxResponseBytes, + }).pipe( + Effect.catchIf( + (error) => error.reason._tag === "EmptyBodyError", + () => Effect.succeed(emptyBody), + ), + ); const answer = { status, headers: responseHeaders, @@ -168,6 +177,7 @@ export const make = Effect.gen(function* () { }; return classify({ answer, acceptNotModified: input.acceptNotModified }); }).pipe( + Effect.scoped, Effect.mapError( (cause) => new GitHubRequestPolicy.GitHubApiRequestError({ @@ -203,6 +213,7 @@ export const make = Effect.gen(function* () { timeout: input.timeout, allowReserve: input.allowReserve ?? interactive, acceptNotModified: input.ifNoneMatch !== undefined, + discardSuccessBody: input.discardSuccessBody === true, }), ), ); diff --git a/packages/source-control-github/src/server/gitHubConditionalChecks.ts b/packages/source-control-github/src/server/gitHubConditionalChecks.ts index 3708745ebdebd..12b695f109e59 100644 --- a/packages/source-control-github/src/server/gitHubConditionalChecks.ts +++ b/packages/source-control-github/src/server/gitHubConditionalChecks.ts @@ -186,6 +186,9 @@ export const makeChecksRevalidator = Effect.gen(function* () { const value = { state: fresh.state, checks: fresh.checks, + ...(fresh.workflowApprovalsRequired === undefined + ? {} + : { workflowApprovalsRequired: fresh.workflowApprovalsRequired }), }; entry.value = fresh.workflowApprovalsRequired !== undefined && fresh.headSha === head.head.sha From 288a02770a24420811599569e21e4ce0f9a18b3c Mon Sep 17 00:00:00 2001 From: bruno Date: Wed, 25 Nov 2026 01:08:29 +0000 Subject: [PATCH 013/880] fix(i18n): i18n:check no longer fails on Windows (#42510) Co-authored-by: Julius Marminge (cherry picked from commit c621d5fe683ea4491e985e4047513aa089318a7f) --- scripts/i18n-check.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/scripts/i18n-check.ts b/scripts/i18n-check.ts index f0b8e668e22bb..82ae0e6d237c9 100644 --- a/scripts/i18n-check.ts +++ b/scripts/i18n-check.ts @@ -8,9 +8,10 @@ import * as NodeOS from "node:os"; import * as NodePath from "node:path"; // Desktop only depends on gt-i18n, so the gt CLI hides `generate` there; its script adds it back. +// The gt CLI runs through Node because the `.bin/gt` shim is a shell script Windows cannot spawn. const GENERATE: Record = { - "apps/web": ["node_modules/.bin/gt", "generate"], - "apps/mobile": ["node_modules/.bin/gt", "generate"], + "apps/web": [process.execPath, "node_modules/gt/bin/main.js", "generate"], + "apps/mobile": [process.execPath, "node_modules/gt/bin/main.js", "generate"], "apps/desktop": [process.execPath, "scripts/i18n-generate.mjs"], }; const APPS = Object.keys(GENERATE); From e3f1a8e21bb42d68b0b66a348841cebbc38f47eb Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 24 Nov 2026 17:20:42 -0800 Subject: [PATCH 014/880] fix(server): workflow watchers get what changed, not the whole list (#42522) (cherry picked from commit adb6064469df8095896a616d6856dea2909ddbf4) --- apps/server/src/workflows/WorkflowEngine.ts | 48 +++++++++++- .../src/workflows/WorkflowRuntime.test.ts | 14 ++-- apps/server/src/workflows/WorkflowRuntime.ts | 3 +- apps/server/src/workflows/Workflows.test.ts | 74 ++++++++++++++++++- apps/server/src/workflows/Workflows.ts | 18 ++++- apps/server/src/ws.ts | 3 +- evals/workflow-authoring/grade.ts | 5 +- packages/client-runtime/src/state/server.ts | 16 +++- packages/client-runtime/src/workflows.test.ts | 35 +++++++-- packages/contracts/src/rpc.ts | 4 +- packages/contracts/src/workflow.test.ts | 20 +++++ packages/contracts/src/workflow.ts | 70 +++++++++++++++++- 12 files changed, 281 insertions(+), 29 deletions(-) create mode 100644 packages/contracts/src/workflow.test.ts diff --git a/apps/server/src/workflows/WorkflowEngine.ts b/apps/server/src/workflows/WorkflowEngine.ts index 290973e03334a..c440510e970fe 100644 --- a/apps/server/src/workflows/WorkflowEngine.ts +++ b/apps/server/src/workflows/WorkflowEngine.ts @@ -26,7 +26,11 @@ import * as Scope from "effect/Scope"; import * as SqlClient from "effect/sql/SqlClient"; import * as Stream from "effect/Stream"; import { DurableDeferred, WorkflowEngine } from "effect/workflow"; -import { DEFAULT_WORKFLOW_SKIPPED_RUNS_KEPT } from "@t3tools/contracts"; +import { + DEFAULT_WORKFLOW_SKIPPED_RUNS_KEPT, + type WorkflowRunsUpdate, + workflowQuestionKey, +} from "@t3tools/contracts"; import { checkOutput, rejectionText } from "../orchestration-v2/runOutput.ts"; import * as ServerSettings from "../serverSettings.ts"; @@ -75,6 +79,11 @@ const DEFAULT_SIGNAL_TTL = Duration.days(7); const RESUME_LOOK_EVERY = Duration.millis(25); const RESUME_LOOKS = 80; const WATCH_SETTLE = Duration.millis(100); +// What a watcher was last sent, as text to compare against, by run and by question. +interface Sent { + readonly runs: Map; + readonly questions: Map; +} const END_TRIES = 5; // How long a cancelled run's cleanup rests after each failed try before the sweep tries again. const END_AFTER = ["5 minutes", "20 minutes", "80 minutes", "5 hours"] as const; @@ -179,7 +188,7 @@ const make = Effect.fn("WorkflowEngine.make")(function* ( resumesAt: resumes, parentRunId: row.parent_run_id, parentStep: row.parent_wait, - // Left out of a run with none: most have none, and every run is sent on every change. + // Left out of a run with none: most have none, and every run is in each whole list sent. ...(row.tags_json === "[]" ? {} : { tags: WorkflowStore.jsonValue(row.tags_json) as ReadonlyArray }), @@ -870,6 +879,41 @@ const make = Effect.fn("WorkflowEngine.make")(function* ( Stream.debounce(WATCH_SETTLE), Stream.mapEffect(() => snapshot), ), + ).pipe( + // Each list is told as what differs from the one before, which this watcher already has. + // A list with no difference is still sent: a client reads an open run's steps again on it. + Stream.mapAccum( + () => undefined as Sent | undefined, + (sent, next) => { + const now: Sent = { + runs: new Map(next.runs.map((run) => [run.runId, JSON.stringify(run)])), + questions: new Map( + next.questions.map((question) => [ + workflowQuestionKey(question), + { runId: question.runId, name: question.name, text: JSON.stringify(question) }, + ]), + ), + }; + const update: WorkflowRunsUpdate = + sent === undefined + ? next + : { + _tag: "changed", + runs: next.runs.filter( + (run) => sent.runs.get(run.runId) !== now.runs.get(run.runId), + ), + removed: [...sent.runs.keys()].filter((runId) => !now.runs.has(runId)), + questions: next.questions.filter((question) => { + const key = workflowQuestionKey(question); + return sent.questions.get(key)?.text !== now.questions.get(key)?.text; + }), + closed: [...sent.questions] + .filter(([key]) => !now.questions.has(key)) + .map(([, { runId, name }]) => ({ runId, name })), + }; + return [now, [update]] as const; + }, + ), ); }), ); diff --git a/apps/server/src/workflows/WorkflowRuntime.test.ts b/apps/server/src/workflows/WorkflowRuntime.test.ts index 60e364e7248a9..b0028863c3a33 100644 --- a/apps/server/src/workflows/WorkflowRuntime.test.ts +++ b/apps/server/src/workflows/WorkflowRuntime.test.ts @@ -145,7 +145,7 @@ it.effect( // The same change made outside the app is refused as a whole: the file still reads as the // version that runs, until it is put back. const told = (wanted: boolean) => - workflows.watch.pipe( + Workflows.wholeLists(workflows.watch).pipe( Stream.filter((snapshot) => (snapshot.definition?.problem != null) === wanted), Stream.runHead, ); @@ -199,7 +199,7 @@ it.effect( // Someone breaks a file outside the app: its last good version keeps running, and the // other files go on changing. const problem = (wanted: boolean) => - workflows.watch.pipe( + Workflows.wholeLists(workflows.watch).pipe( Stream.filter((snapshot) => (snapshot.definition?.problem != null) === wanted), Stream.runHead, ); @@ -287,7 +287,7 @@ it.effect( const workflows = yield* Workflows.Workflows; const definitions = yield* WorkflowRuntime.WorkflowDefinitions; const revision = Effect.map( - Stream.runHead(workflows.watch), + Stream.runHead(Workflows.wholeLists(workflows.watch)), (snapshot) => Option.getOrThrow(snapshot).definition?.revision ?? 0, ); refuse = true; @@ -300,7 +300,7 @@ it.effect( const before = yield* revision; refuse = false; yield* TestClock.adjust("30 seconds"); - yield* workflows.watch.pipe( + yield* Workflows.wholeLists(workflows.watch).pipe( Stream.filter((snapshot) => (snapshot.definition?.revision ?? 0) > before), Stream.runHead, ); @@ -319,8 +319,8 @@ it.effect( ["greet@1", "hold@1"], ]); assert.include( - (yield* Stream.runHead(workflows.watch)).pipe(Option.getOrThrow).definition?.problem ?? - "", + (yield* Stream.runHead(Workflows.wholeLists(workflows.watch))).pipe(Option.getOrThrow) + .definition?.problem ?? "", "did not start", ); }).pipe(Effect.provide(runtime), Effect.scoped); @@ -439,7 +439,7 @@ it.effect("a change held back by a run goes in once that run ends, with no furth const held = yield* workflows.start("hold", {}, { idempotencyKey: "h" }); yield* workflows.waitFor(held.runId, (run) => run.status === "waiting"); const problem = (wanted: boolean) => - workflows.watch.pipe( + Workflows.wholeLists(workflows.watch).pipe( Stream.filter((snapshot) => (snapshot.definition?.problem != null) === wanted), Stream.runHead, ); diff --git a/apps/server/src/workflows/WorkflowRuntime.ts b/apps/server/src/workflows/WorkflowRuntime.ts index d77e945308c67..5af8ffe9d5a41 100644 --- a/apps/server/src/workflows/WorkflowRuntime.ts +++ b/apps/server/src/workflows/WorkflowRuntime.ts @@ -650,8 +650,9 @@ export const make = Effect.fn("WorkflowRuntime.make")(function* ( storeDelete: Effect.fn("Workflows.storeDelete")(function* (...input) { return yield* (yield* current).storeDelete(...input); }), + // Every reload starts a watcher over on a whole list, which is where the definition rides. watch: followed((live) => live.watch).pipe( - Stream.map(([snapshot, at]) => ({ ...snapshot, definition: at })), + Stream.map(([update, at]) => ("_tag" in update ? update : { ...update, definition: at })), ), counts: followed((live) => live.counts).pipe(Stream.map(([counts]) => counts)), sweep: Effect.flatMap(current, (live) => live.sweep), diff --git a/apps/server/src/workflows/Workflows.test.ts b/apps/server/src/workflows/Workflows.test.ts index d4cc5fe75cde9..a4ce996a38a9b 100644 --- a/apps/server/src/workflows/Workflows.test.ts +++ b/apps/server/src/workflows/Workflows.test.ts @@ -1876,7 +1876,9 @@ it.effect("a watcher is sent the runs again when one changes", () => yield* boot( Effect.gen(function* () { const workflows = yield* Workflows.Workflows; - const first = Option.getOrThrow(yield* Stream.runHead(workflows.watch)); + const first = Option.getOrThrow( + yield* Stream.runHead(Workflows.wholeLists(workflows.watch)), + ); assert.deepStrictEqual([first.runs, first.questions], [[], []]); // What exists is listed before anything has run, with what starts it. assert.deepInclude(first.workflows, { @@ -1889,7 +1891,7 @@ it.effect("a watcher is sent the runs again when one changes", () => { change: "c9", timeout: "1 hour" }, { idempotencyKey: "c9" }, ); - const seen = yield* workflows.watch.pipe( + const seen = yield* Workflows.wholeLists(workflows.watch).pipe( Stream.filter((snapshot) => snapshot.runs.some((run) => run.status === "waiting")), Stream.runHead, ); @@ -2282,7 +2284,9 @@ it.effect("questions carry their kind and runs their tags, and both can be filte for (const run of [feature, intended, plain]) { yield* workflows.waitFor(run.runId, status("waiting")); } - const snapshot = Option.getOrThrow(yield* Stream.runHead(workflows.watch)); + const snapshot = Option.getOrThrow( + yield* Stream.runHead(Workflows.wholeLists(workflows.watch)), + ); // The page reads the labels and their order from what the workflow declares. assert.deepStrictEqual( snapshot.workflows.find((workflow) => workflow.name === "sorter")?.asks, @@ -2330,7 +2334,9 @@ it.effect("questions carry their kind and runs their tags, and both can be filte // A kind the workflow does not declare is asked all the same, and kept as it was written. const typo = yield* sort("d", [], "feture"); yield* workflows.waitFor(typo.runId, status("waiting")); - const after = Option.getOrThrow(yield* Stream.runHead(workflows.watch)); + const after = Option.getOrThrow( + yield* Stream.runHead(Workflows.wholeLists(workflows.watch)), + ); assert.equal( after.questions.find((question) => question.runId === typo.runId)?.kind, "feture", @@ -2502,3 +2508,63 @@ it("error text cuts at 2,000 units without leaving half an emoji", () => { `outer: ${"a".repeat(1_992)}`, ); }); + +it.effect("one run moving sends a watcher an update about that run, not the whole list", () => + Effect.gen(function* () { + const { boot } = yield* harness(); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + // Half the other runs wait at a gate, half wait on a question to a person. + const park = (from: number, to: number) => + Effect.forEach( + Array.from({ length: to - from }, (_, i) => from + i), + (i) => + i % 2 === 0 + ? workflows.start("gate", { gate: "south" }, { idempotencyKey: `visit/${i}` }) + : workflows.start("sorter", { tags: [] }, { idempotencyKey: `asked/${i}` }), + { discard: true }, + ); + // The size of the first update a watcher gets after `mover` ends, let through a gate or + // by its question being answered. + const updateWhen = Effect.fnUntraced(function* (mover: string, by: "signal" | "answer") { + const { runId } = + by === "signal" + ? yield* workflows.start("gate", { gate: mover }, { idempotencyKey: mover }) + : yield* workflows.start("sorter", { tags: [] }, { idempotencyKey: mover }); + yield* workflows.waitFor(runId, status("waiting")); + const subscribed = yield* Deferred.make(); + const update = yield* workflows.watch.pipe( + Stream.tap(() => Deferred.succeed(subscribed, undefined)), + Stream.drop(1), + Stream.map((sent) => JSON.stringify(sent)), + Stream.filter((text) => text.includes(runId) && text.includes('"completed"')), + Stream.map((text) => text.length), + Stream.runHead, + Effect.forkScoped, + ); + yield* Deferred.await(subscribed); + yield* by === "signal" + ? workflows.signal({ runId, wait: "through" }, "go on", { id: mover }) + : Effect.asVoid(workflows.answer(runId, "sort", { choice: "No" })); + return Option.getOrThrow(yield* Fiber.join(update)); + }); + + yield* park(0, 10); + const fewOthers = [ + yield* updateWhen("north-1", "signal"), + yield* updateWhen("asked-1", "answer"), + ]; + yield* park(10, 300); + const manyOthers = [ + yield* updateWhen("north-2", "signal"), + yield* updateWhen("asked-2", "answer"), + ]; + for (const [index, few] of fewOthers.entries()) { + const many = manyOthers[index] ?? 0; + assert.isBelow(many, few * 2, `${few} bytes beside 10 runs, ${many} beside 300`); + } + }).pipe(Effect.scoped), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); diff --git a/apps/server/src/workflows/Workflows.ts b/apps/server/src/workflows/Workflows.ts index e29d7027ee3e1..6467cc527a087 100644 --- a/apps/server/src/workflows/Workflows.ts +++ b/apps/server/src/workflows/Workflows.ts @@ -3,7 +3,9 @@ import { type WorkflowHook, WorkflowQuestion, type WorkflowRunReference, + applyWorkflowRunsUpdate, type WorkflowRunsSnapshot, + type WorkflowRunsUpdate, } from "@t3tools/contracts"; import * as Context from "effect/Context"; import type * as Duration from "effect/Duration"; @@ -155,8 +157,8 @@ export class Workflows extends Context.Service< /** Set a key of the store from outside a run, as a person flipping a switch does. */ readonly storeSet: (key: string, value: Schema.Json) => Effect.Effect; readonly storeDelete: (key: string) => Effect.Effect; - /** Recent runs and open questions, now and again after every change. */ - readonly watch: Stream.Stream; + /** Recent runs and open questions now, then what changed of them after every change. */ + readonly watch: Stream.Stream; /** How much is going on, now and again whenever a count changes. */ readonly counts: Stream.Stream; /** @@ -207,6 +209,18 @@ export const disabled = Workflows.of({ }); export const layerDisabled = Layer.succeed(Workflows, disabled); +/** What `watch` sends, as the whole list every time: for a client that did not ask for changes. */ +export const wholeLists = (updates: Stream.Stream) => + updates.pipe( + Stream.mapAccum( + (): WorkflowRunsSnapshot | undefined => undefined, + (list, update) => { + const next = applyWorkflowRunsUpdate(list, update); + return [next, [next]] as const; + }, + ), + ); + export const OFF = 'Workflows are off on this server. Turn them on in its Settings → Labs → Workflows, or without a desktop, set "workflowsEnabled": true in userdata/settings.json in its T3 home (~/.t3 by default).'; diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index faf953e1d10f0..925b04a321fb9 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -2317,7 +2317,8 @@ export const layerWsRpc = ( ), [ORCHESTRATION_V2_WS_METHODS.subscribePromptSuggestion]: (input) => providerSessionManager.subscribePromptSuggestion(input.threadId), - [WS_METHODS.workflowsSubscribe]: (_input) => workflows.watch, + [WS_METHODS.workflowsSubscribe]: (input) => + input.changes === true ? workflows.watch : Workflows.wholeLists(workflows.watch), [WS_METHODS.workflowsCounts]: (_input) => workflows.counts, [WS_METHODS.workflowsGet]: (input) => workflows.get(input.runId).pipe(Effect.mapError(toWorkflowRequestError)), diff --git a/evals/workflow-authoring/grade.ts b/evals/workflow-authoring/grade.ts index 50ef5e5a745a4..7a564b0d9bcb9 100644 --- a/evals/workflow-authoring/grade.ts +++ b/evals/workflow-authoring/grade.ts @@ -126,8 +126,9 @@ const world = Effect.fn("gradeWorkflow.world")(function* ( .pipe(Effect.timeoutOption("10 seconds")), asks: (workflows, runId) => workflows.watch.pipe( - Stream.filterMap((snapshot) => { - const question = snapshot.questions.find((asked) => asked.runId === runId); + // A question comes in the first list, or in the update where it is asked. + Stream.filterMap((update) => { + const question = update.questions.find((asked) => asked.runId === runId); return question === undefined ? Result.failVoid : Result.succeed(question.name); }), Stream.runHead, diff --git a/packages/client-runtime/src/state/server.ts b/packages/client-runtime/src/state/server.ts index a793d73125886..dc8d97949861d 100644 --- a/packages/client-runtime/src/state/server.ts +++ b/packages/client-runtime/src/state/server.ts @@ -17,10 +17,12 @@ import { type ServerLifecycleStreamReadyEvent, type ServerProviderWorkspaceSnapshot, ServerSelfUpdateError, + applyWorkflowRunsUpdate, type ServerSelfUpdateProgressEvent, type ServerSelfUpdateResult, shouldRecommendDatabaseCompaction, type UsageSummary, + type WorkflowRunsSnapshot, WS_METHODS, } from "@t3tools/contracts"; import * as Cause from "effect/Cause"; @@ -1473,9 +1475,19 @@ export function createServerEnvironmentAtoms( ), ); }); - const workflowsLive = createEnvironmentRpcSubscriptionAtomFamily(runtime, { + const workflowsLive = createEnvironmentSubscriptionAtomFamily(runtime, { label: "environment-data:server:workflows:live", - tag: WS_METHODS.workflowsSubscribe, + // Asks for what changed after the first list; a server older than that sends whole lists. + subscribe: (input: EnvironmentRpcInput) => + subscribe(WS_METHODS.workflowsSubscribe, { ...input, changes: true }).pipe( + Stream.mapAccum( + (): WorkflowRunsSnapshot | undefined => undefined, + (snapshot, update) => { + const next = applyWorkflowRunsUpdate(snapshot, update); + return [next, [next]] as const; + }, + ), + ), }); const liveWorkflowSnapshot = (environmentId: EnvironmentId) => { const live = workflowsLive({ environmentId, input: {} }); diff --git a/packages/client-runtime/src/workflows.test.ts b/packages/client-runtime/src/workflows.test.ts index d591fa75412d0..359d3326ebbbf 100644 --- a/packages/client-runtime/src/workflows.test.ts +++ b/packages/client-runtime/src/workflows.test.ts @@ -1,8 +1,9 @@ -import type { - WorkflowQuestion, - WorkflowRun, - WorkflowRunReference, - WorkflowStep, +import { + applyWorkflowRunsUpdate, + type WorkflowQuestion, + type WorkflowRun, + type WorkflowRunReference, + type WorkflowStep, } from "@t3tools/contracts"; import { describe, expect, it } from "vite-plus/test"; @@ -352,6 +353,30 @@ describe("the list of runs", () => { }); }); +describe("applyWorkflowRunsUpdate", () => { + it("keeps the list a fresh snapshot would show, newest run and oldest question first", () => { + const first = applyWorkflowRunsUpdate(undefined, { + workflows: [], + runs: [run("c", { startedAt: at(3) }), run("b", { startedAt: at(2) }), run("a")], + questions: [question("b"), question("c")], + }); + const later = { ...question("d"), askedAt: at(2) }; + const next = applyWorkflowRunsUpdate(first, { + _tag: "changed", + runs: [run("b", { startedAt: at(2), status: "completed" }), run("d", { startedAt: at(4) })], + removed: ["a"], + questions: [later, question("c", { title: "Ship now?" })], + closed: [{ runId: "b", name: "approve" }], + }); + expect(next.runs.map((entry) => [entry.runId, entry.status])).toEqual([ + ["d", "running"], + ["c", "running"], + ["b", "completed"], + ]); + expect(next.questions).toEqual([question("c", { title: "Ship now?" }), later]); + }); +}); + describe("workflowRunRefreshKey", () => { it("reads an ended run again only when it changes, and one under way on any change", () => { const snapshot = (runs: ReadonlyArray) => ({ workflows: [], runs, questions: [] }); diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts index b84d2dc467845..72353d9968868 100644 --- a/packages/contracts/src/rpc.ts +++ b/packages/contracts/src/rpc.ts @@ -457,7 +457,7 @@ import { WorkflowRunGetInput, WorkflowRunResumeInput, WorkflowCounts, - WorkflowRunsSnapshot, + WorkflowRunsUpdate, WorkflowRunsSubscribeInput, } from "./workflow.ts"; import { @@ -2410,7 +2410,7 @@ const WsSubscribeServerLifecycleRpc = Rpc.make(WS_METHODS.subscribeServerLifecyc const WsWorkflowsSubscribeRpc = Rpc.make(WS_METHODS.workflowsSubscribe, { payload: WorkflowRunsSubscribeInput, - success: WorkflowRunsSnapshot, + success: WorkflowRunsUpdate, error: EnvironmentAuthorizationError, stream: true, }); diff --git a/packages/contracts/src/workflow.test.ts b/packages/contracts/src/workflow.test.ts new file mode 100644 index 0000000000000..6b156f265db8a --- /dev/null +++ b/packages/contracts/src/workflow.test.ts @@ -0,0 +1,20 @@ +import { describe, expect, it } from "@effect/vitest"; +import * as Schema from "effect/Schema"; + +import { WorkflowRunsSubscribeInput, WorkflowRunsUpdate } from "./workflow.ts"; + +const decodeUpdate = Schema.decodeUnknownSync(WorkflowRunsUpdate); +const encodeInput = Schema.encodeSync(WorkflowRunsSubscribeInput); +// The input of a server from before `changes`. +const decodeOlderInput = Schema.decodeUnknownSync(Schema.Struct({})); + +describe("workflows.subscribe across versions", () => { + it("reads a whole list from a server that does not send changes", () => { + const list = { workflows: [], runs: [], questions: [] }; + expect(decodeUpdate(list)).toEqual(list); + }); + + it("asks for changes in a way an older server ignores", () => { + expect(() => decodeOlderInput(encodeInput({ changes: true }))).not.toThrow(); + }); +}); diff --git a/packages/contracts/src/workflow.ts b/packages/contracts/src/workflow.ts index 3f5ddf12a1ce4..90585b0372e3c 100644 --- a/packages/contracts/src/workflow.ts +++ b/packages/contracts/src/workflow.ts @@ -171,7 +171,75 @@ export const WorkflowCounts = Schema.Struct({ export type WorkflowCounts = typeof WorkflowCounts.Type; export type WorkflowRunsSnapshot = typeof WorkflowRunsSnapshot.Type; -export const WorkflowRunsSubscribeInput = Schema.Struct({}); +/** What changed in the runs list since the last frame a watcher was sent. */ +export const WorkflowRunsChange = Schema.TaggedStruct("changed", { + /** Runs new to the list or different from what was last sent. */ + runs: Schema.Array(WorkflowRun), + /** Runs that left the list. */ + removed: Schema.Array(Schema.String), + /** Questions newly asked or different from what was last sent. */ + questions: Schema.Array(WorkflowQuestion), + /** Questions no longer open, by run and question name. */ + closed: Schema.Array(Schema.Struct({ runId: Schema.String, name: Schema.String })), +}); + +/** + * A frame of `workflows.subscribe`: the whole list, or with `changes` asked for, what changed + * since the last frame. A server older than `changes` ignores it and sends whole lists. + */ +export const WorkflowRunsUpdate = Schema.Union([WorkflowRunsSnapshot, WorkflowRunsChange]); +export type WorkflowRunsUpdate = typeof WorkflowRunsUpdate.Type; + +/** The list once `update` is applied, in the order the server lists runs: newest first. */ +export function applyWorkflowRunsUpdate( + snapshot: WorkflowRunsSnapshot | undefined, + update: WorkflowRunsUpdate, +): WorkflowRunsSnapshot { + if (!("_tag" in update)) return update; + const base = snapshot ?? { workflows: [], runs: [], questions: [] }; + // Stable sorts, so entries of the same moment keep the order they were sent in. + const runs = merged(base.runs, update.runs, update.removed, (run) => run.runId).sort( + (left, right) => + left.startedAt === right.startedAt ? 0 : left.startedAt < right.startedAt ? 1 : -1, + ); + const questions = merged( + base.questions, + update.questions, + update.closed.map(workflowQuestionKey), + workflowQuestionKey, + ).sort((left, right) => + left.askedAt === right.askedAt ? 0 : left.askedAt < right.askedAt ? -1 : 1, + ); + return { ...base, runs, questions }; +} + +/** What names an open question: one run asks one question of a name at a time. */ +export const workflowQuestionKey = (question: { readonly runId: string; readonly name: string }) => + JSON.stringify([question.runId, question.name]); + +/** `held` with `changed` put in place of their earlier versions and `gone` left out. */ +function merged( + held: ReadonlyArray, + changed: ReadonlyArray, + gone: ReadonlyArray, + key: (entry: A) => string, +): Array { + const fresh = new Map(changed.map((entry) => [key(entry), entry])); + const left = new Set(gone); + const kept = held.flatMap((entry) => { + const id = key(entry); + if (left.has(id)) return []; + const next = fresh.get(id); + fresh.delete(id); + return [next ?? entry]; + }); + return [...fresh.values(), ...kept]; +} + +export const WorkflowRunsSubscribeInput = Schema.Struct({ + /** Send what changed after the first list instead of the whole list every time. */ + changes: Schema.optionalKey(Schema.Boolean), +}); export const WorkflowRunGetInput = Schema.Struct({ runId: Schema.String }); From c9bf5663744c37645c13713963a2b9956df439a1 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 24 Nov 2026 17:24:16 -0800 Subject: [PATCH 015/880] fix(desktop): typing with both Shift keys no longer fires the macOS SnapShot shortcut (#42474) (cherry picked from commit 6e597243d4c88816fddde9f0f3a67b6750c9d16f) --- .../src/snapShot/GlobalShiftShortcutWorker.ts | 114 +++++++++++++++++- .../MacModifierPairShortcutProcess.ts | 10 +- 2 files changed, 120 insertions(+), 4 deletions(-) diff --git a/apps/desktop/src/snapShot/GlobalShiftShortcutWorker.ts b/apps/desktop/src/snapShot/GlobalShiftShortcutWorker.ts index 78f41968ba636..9874e823e31aa 100644 --- a/apps/desktop/src/snapShot/GlobalShiftShortcutWorker.ts +++ b/apps/desktop/src/snapShot/GlobalShiftShortcutWorker.ts @@ -11,19 +11,129 @@ if (!(SNAP_SHOT_MODIFIERS as readonly string[]).includes(requested ?? "")) { process.exit(1); } const [left, right] = WINDOWS_MODIFIER_PAIR_VIRTUAL_KEYS[requested as SnapShotModifier]; +const MODIFIER_VIRTUAL_KEYS = new Set([ + 0x10, + 0x11, + 0x12, + 0xff, + ...Object.values(WINDOWS_MODIFIER_PAIR_VIRTUAL_KEYS).flat(), +]); + +const HWND_MESSAGE = -3n; +const RIDEV_INPUTSINK = 0x100; +const WM_INPUT = 0x00ff; +const PM_REMOVE = 1; +const RID_INPUT = 0x10000003; +const RIM_TYPEKEYBOARD = 1; +const RI_KEY_BREAK = 1; +// x64/arm64 layouts: MSG is 48 bytes (lParam at 24), RAWINPUTHEADER is 24, RAWKEYBOARD follows it. +const MSG_SIZE = 48; +const RAW_INPUT_HEADER_SIZE = 24; + +// Raw Input queues every key event, so a keystroke between two polls is still seen. +async function openKeyboardActivity(): Promise<() => boolean> { + const { DataType, load, open } = await import("ffi-rs"); + const library = "t3-user32-raw-input"; + open({ library, path: "user32.dll" }); + const className = Buffer.from("STATIC\0", "utf16le"); + const window = load({ + library, + funcName: "CreateWindowExW", + retType: DataType.BigInt, + paramsType: [ + DataType.U32, + DataType.U8Array, + DataType.BigInt, + DataType.U32, + DataType.I32, + DataType.I32, + DataType.I32, + DataType.I32, + DataType.BigInt, + DataType.BigInt, + DataType.BigInt, + DataType.BigInt, + ], + paramsValue: [0, className, 0n, 0, 0, 0, 0, 0, HWND_MESSAGE, 0n, 0n, 0n], + }) as bigint; + if (window === 0n) throw new Error("CreateWindowExW failed"); + const device = Buffer.alloc(16); + device.writeUInt16LE(0x01, 0); + device.writeUInt16LE(0x06, 2); + device.writeUInt32LE(RIDEV_INPUTSINK, 4); + device.writeBigUInt64LE(window, 8); + const registered = load({ + library, + funcName: "RegisterRawInputDevices", + retType: DataType.Boolean, + paramsType: [DataType.U8Array, DataType.U32, DataType.U32], + paramsValue: [device, 1, device.byteLength], + }); + if (!registered) throw new Error("RegisterRawInputDevices failed"); + + const message = Buffer.alloc(MSG_SIZE); + const input = Buffer.alloc(64); + const inputSize = Buffer.alloc(4); + return () => { + let typed = false; + while ( + load({ + library, + funcName: "PeekMessageW", + retType: DataType.Boolean, + paramsType: [DataType.U8Array, DataType.BigInt, DataType.U32, DataType.U32, DataType.U32], + paramsValue: [message, window, WM_INPUT, WM_INPUT, PM_REMOVE], + }) + ) { + inputSize.writeUInt32LE(input.byteLength, 0); + const read = load({ + library, + funcName: "GetRawInputData", + retType: DataType.U32, + paramsType: [ + DataType.BigInt, + DataType.U32, + DataType.U8Array, + DataType.U8Array, + DataType.U32, + ], + paramsValue: [ + message.readBigUInt64LE(24), + RID_INPUT, + input, + inputSize, + RAW_INPUT_HEADER_SIZE, + ], + }); + if (read === 0xffffffff || input.readUInt32LE(0) !== RIM_TYPEKEYBOARD) continue; + const flags = input.readUInt16LE(RAW_INPUT_HEADER_SIZE + 2); + const virtualKey = input.readUInt16LE(RAW_INPUT_HEADER_SIZE + 6); + if ((flags & RI_KEY_BREAK) === 0 && !MODIFIER_VIRTUAL_KEYS.has(virtualKey)) typed = true; + } + return typed; + }; +} async function poll() { const api = await loadWindowsForegroundApi(); + const drainTyping = await openKeyboardActivity(); let active = false; + // A key typed since the pair was last fully up means the overlap came from typing (rolled + // Shifts for consecutive capitals), not a deliberate press, so it does not trigger. + let typed = false; process.send?.("ready"); const timer = setInterval(() => { - const pressed = api.isKeyDown(left) && api.isKeyDown(right); - if (pressed && !active) { + if (drainTyping()) typed = true; + const leftDown = api.isKeyDown(left); + const rightDown = api.isKeyDown(right); + const pressed = leftDown && rightDown; + if (pressed && !active && !typed) { try { process.send?.("trigger"); } catch {} } active = pressed; + if (!leftDown && !rightDown) typed = false; }, POLL_INTERVAL_MS); const shutdown = () => { clearInterval(timer); diff --git a/apps/desktop/src/snapShot/MacModifierPairShortcutProcess.ts b/apps/desktop/src/snapShot/MacModifierPairShortcutProcess.ts index 117ffa652566b..0b4d7b569b887 100644 --- a/apps/desktop/src/snapShot/MacModifierPairShortcutProcess.ts +++ b/apps/desktop/src/snapShot/MacModifierPairShortcutProcess.ts @@ -12,6 +12,8 @@ const MAC_MODIFIER_PAIR_DEVICE_MASKS: Record $.CGEventSourceCounterForEventType(0, $.kCGEventKeyDown); let active = false; + let idleKeyDowns = keyDowns(); console.log("ready"); while ($.getppid() !== 1) { - const pressed = ($.CGEventSourceFlagsState(0) & both) === both; - if (pressed && !active) console.log("trigger"); + const flags = $.CGEventSourceFlagsState(0); + const pressed = (flags & both) === both; + if (pressed && !active && keyDowns() === idleKeyDowns) console.log("trigger"); active = pressed; + if ((flags & both) === 0) idleKeyDowns = keyDowns(); delay(0.05); } return "orphaned"; From 6883b77f3668f3813c2a7e01fe248a3d9c86ddbe Mon Sep 17 00:00:00 2001 From: Pranav Bansal <55818107+prnvbn@users.noreply.github.com> Date: Wed, 25 Nov 2026 06:59:18 +0530 Subject: [PATCH 016/880] feat(terminal): Add keybindings for cycling through terminals (#30664) Co-authored-by: Yash Singh (cherry picked from commit b6869fad67eade8a1396d446870ee9d48f33d82b) --- apps/server/src/keybindings.test.ts | 27 +++--- .../src/components/ThreadTerminalDrawer.tsx | 2 + .../chat/useChatShortcuts.browser.test.tsx | 59 ++++++++++++ .../src/components/chat/useChatShortcuts.ts | 11 ++- .../components/chat/useChatTerminalActions.ts | 9 ++ apps/web/src/keybindings.test.ts | 60 ++++++++++-- apps/web/src/keybindings.ts | 10 ++ apps/web/src/lib/cycleThreadTerminal.test.ts | 93 +++++++++++++++++++ apps/web/src/lib/cycleThreadTerminal.ts | 54 +++++++++++ docs/user/terminal.md | 5 + packages/contracts/src/keybindings.ts | 2 + packages/shared/src/keybindings.ts | 4 + 12 files changed, 313 insertions(+), 23 deletions(-) create mode 100644 apps/web/src/lib/cycleThreadTerminal.test.ts create mode 100644 apps/web/src/lib/cycleThreadTerminal.ts diff --git a/apps/server/src/keybindings.test.ts b/apps/server/src/keybindings.test.ts index 44048330c3ae2..c17cd98c61b50 100644 --- a/apps/server/src/keybindings.test.ts +++ b/apps/server/src/keybindings.test.ts @@ -52,6 +52,17 @@ const readKeybindingsConfig = (configPath: string) => return yield* decodeKeybindingsConfigJson(rawConfig); }); +function scriptBindingsAtChatNewCutoff(hiddenChatNewBindings: 0 | 1) { + const defaults = SharedKeybindings.DEFAULT_RESOLVED_KEYBINDINGS; + const firstChatNew = defaults.findIndex((binding) => binding.command === "chat.new"); + assert.isAtLeast(firstChatNew, 0); + const visibleDefaults = defaults.length - firstChatNew - hiddenChatNewBindings; + return Array.from({ length: MAX_KEYBINDINGS_COUNT - visibleDefaults }, (_, index) => ({ + key: "mod+alt+f1", + command: `script.filler-${index}.run` as const, + })); +} + it.layer(NodeServices.layer)("keybindings", (it) => { it.effect("parses shortcuts including plus key", () => Effect.sync(() => { @@ -533,13 +544,7 @@ it.layer(NodeServices.layer)("keybindings", (it) => { Effect.gen(function* () { const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig; const keybindings = yield* Keybindings.Keybindings; - yield* writeKeybindingsConfig( - keybindingsConfigPath, - Array.from({ length: 210 }, (_, index) => ({ - key: "mod+alt+f1", - command: `script.filler-${index}.run` as const, - })), - ); + yield* writeKeybindingsConfig(keybindingsConfigPath, scriptBindingsAtChatNewCutoff(1)); const target = { key: "mod+shift+o", command: "chat.new", when: "!terminalFocus" } as const; const local = { ...target, key: "mod+shift+n", command: "chat.newLocal" } as const; @@ -566,13 +571,7 @@ it.layer(NodeServices.layer)("keybindings", (it) => { Effect.gen(function* () { const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig; const keybindings = yield* Keybindings.Keybindings; - yield* writeKeybindingsConfig( - keybindingsConfigPath, - Array.from({ length: 209 }, (_, index) => ({ - key: "mod+alt+f1", - command: `script.filler-${index}.run` as const, - })), - ); + yield* writeKeybindingsConfig(keybindingsConfigPath, scriptBindingsAtChatNewCutoff(0)); const target = { key: "mod+n", command: "chat.new", when: "!terminalFocus" } as const; const sibling = { ...target, key: "mod+shift+o" }; diff --git a/apps/web/src/components/ThreadTerminalDrawer.tsx b/apps/web/src/components/ThreadTerminalDrawer.tsx index d6781eabc3ed1..a4ad1586a3e67 100644 --- a/apps/web/src/components/ThreadTerminalDrawer.tsx +++ b/apps/web/src/components/ThreadTerminalDrawer.tsx @@ -66,6 +66,7 @@ import { isDiffToggleShortcut, isTerminalClearShortcut, isTerminalNewShortcut, + isTerminalCycleShortcut, isTerminalSplitShortcut, isTerminalSplitVerticalShortcut, isTerminalToggleShortcut, @@ -1033,6 +1034,7 @@ function TerminalSessionViewport({ isTerminalSplitShortcut(event, currentKeybindings, options) || isTerminalSplitVerticalShortcut(event, currentKeybindings, options) || isTerminalNewShortcut(event, currentKeybindings, options) || + isTerminalCycleShortcut(event, currentKeybindings, options) || isDiffToggleShortcut(event, currentKeybindings, options) || // Match Sidebar's context, or a key it will reject skips the shell. isThreadNavigationShortcut(event, currentKeybindings, { diff --git a/apps/web/src/components/chat/useChatShortcuts.browser.test.tsx b/apps/web/src/components/chat/useChatShortcuts.browser.test.tsx index d3d1b06871e98..472bc009ed344 100644 --- a/apps/web/src/components/chat/useChatShortcuts.browser.test.tsx +++ b/apps/web/src/components/chat/useChatShortcuts.browser.test.tsx @@ -145,6 +145,65 @@ it.each([ expect(received).toEqual(launcher); }); +function UnavailableTerminalCommand({ + command, + owner, +}: { + command: KeybindingCommand; + owner: "drawer" | "right-panel" | null; +}) { + useChatShortcuts({ + enabled: true, + keybindings: compileResolvedKeybindingsConfig([ + { key: command === "terminal.previous" ? "cmd+shift+[" : "cmd+shift+]", command }, + ]), + scriptKeybindings: [], + getShortcutContext: () => ({ ...shortcutContext, terminalFocus: owner !== null }), + threadFindActive: false, + composerRef: { current: null }, + branchToolbarRef: { current: null }, + closeThreadFind: () => {}, + commands: { [command]: () => false }, + fallback: () => undefined, + }); + return ( +
+ +
+ ); +} + +it.each([ + ["terminal.previous", "drawer", true], + ["terminal.next", "drawer", true], + ["terminal.new", "drawer", false], + ["terminal.previous", "right-panel", true], + ["terminal.next", "right-panel", true], + ["terminal.previous", null, false], + ["terminal.next", null, false], +] as const)("handles unavailable %s with focus owner %s", async (command, owner, prevented) => { + await using screen = await render( + , + options, + ); + const input = screen.container.querySelector("input")!; + const received: string[] = []; + input.addEventListener("keydown", (event) => received.push(event.key)); + const previous = command === "terminal.previous"; + const key = previous ? "{" : "}"; + const event = new KeyboardEvent("keydown", { + key, + code: previous ? "BracketLeft" : "BracketRight", + shiftKey: true, + metaKey: true, + bubbles: true, + cancelable: true, + }); + input.dispatchEvent(event); + expect(event.defaultPrevented).toBe(prevented); + expect(received).toEqual(prevented ? [] : [key]); +}); + const sideChatKeybindings: ResolvedKeybindingsConfig = [ ctrl("m", "modelPicker.toggle", true), ctrl("x", "thread.stop", true), diff --git a/apps/web/src/components/chat/useChatShortcuts.ts b/apps/web/src/components/chat/useChatShortcuts.ts index 00cb5eb78d77d..e8805b6c91809 100644 --- a/apps/web/src/components/chat/useChatShortcuts.ts +++ b/apps/web/src/components/chat/useChatShortcuts.ts @@ -14,7 +14,7 @@ import type { BranchToolbarHandle } from "../BranchToolbar"; import { shouldTypeToFocusComposer } from "./composerFocusRedirect"; import { composerShortcutCommands } from "./composerShortcuts"; -/** Returning false lets the key event through untouched. */ +/** Returning false lets the key through, except for cycling while a terminal owns focus. */ type ChatShortcutHandler = (context: { readonly event: KeyboardEvent; readonly terminalFocusOwner: TerminalFocusOwner | null; @@ -98,7 +98,14 @@ export function useChatShortcuts(input: ChatShortcutsInput) { input.commands[command] ?? composerShortcutCommands(input.composerRef, input.branchToolbarRef)[command] ?? input.fallback(command); - if (!run || run({ event, terminalFocusOwner }) === false) return; + if (!run) return; + const handled = run({ event, terminalFocusOwner }); + if ( + handled === false && + (terminalFocusOwner === null || + (command !== "terminal.previous" && command !== "terminal.next")) + ) + return; event.preventDefault(); event.stopPropagation(); }); diff --git a/apps/web/src/components/chat/useChatTerminalActions.ts b/apps/web/src/components/chat/useChatTerminalActions.ts index 6b48d3f19e459..3c83fd02bfd81 100644 --- a/apps/web/src/components/chat/useChatTerminalActions.ts +++ b/apps/web/src/components/chat/useChatTerminalActions.ts @@ -35,6 +35,7 @@ import { openUrlInPreview } from "../../browser/openFileInPreview"; import { isPreviewAvailableFor } from "../../browser/previewRuntime"; import { resolveDiscoveredServerUrl } from "../../browser/browserTargetResolver"; import { stackedThreadToast, toastManager } from "../ui/toast"; +import { cycleThreadTerminal } from "../../lib/cycleThreadTerminal"; import { confirmTerminalClose } from "../../lib/terminalCloseConfirm"; import { findReusableProjectScriptTerminal } from "../../lib/projectScriptTerminal"; import { closingTerminalIds } from "../terminal/closingTerminals"; @@ -426,6 +427,14 @@ export function useChatTerminalActions(input: ChatTerminalActionsInput) { return false; toggleTerminalVisibility(); }, + "terminal.previous": ({ terminalFocusOwner }) => { + if (!activeThreadRef || !terminalFocusOwner) return false; + return cycleThreadTerminal(activeThreadRef, terminalFocusOwner, "previous"); + }, + "terminal.next": ({ terminalFocusOwner }) => { + if (!activeThreadRef || !terminalFocusOwner) return false; + return cycleThreadTerminal(activeThreadRef, terminalFocusOwner, "next"); + }, "terminal.split": ({ terminalFocusOwner }) => { if (!hasTerminalWriteAccess()) return false; if (terminalFocusOwner === "right-panel") return void splitPanelTerminal(); diff --git a/apps/web/src/keybindings.test.ts b/apps/web/src/keybindings.test.ts index 84463efc3abfd..8371b71e74645 100644 --- a/apps/web/src/keybindings.test.ts +++ b/apps/web/src/keybindings.test.ts @@ -645,7 +645,7 @@ describe("resolveShortcutCommand", () => { ); }); - it("navigates history with mod+[ and mod+] outside the terminal", () => { + it("uses terminal cycling shortcuts without changing bracket history shortcuts", () => { const back = event({ key: "[", code: "BracketLeft", metaKey: true }); const forward = event({ key: "]", code: "BracketRight", ctrlKey: true }); assert.strictEqual( @@ -656,12 +656,58 @@ describe("resolveShortcutCommand", () => { resolveShortcutCommand(forward, DEFAULT_RESOLVED_KEYBINDINGS, { platform: "Linux" }), "navigation.forward", ); - assert.isNull( - resolveShortcutCommand(back, DEFAULT_RESOLVED_KEYBINDINGS, { - platform: "MacIntel", - context: { terminalFocus: true }, - }), - ); + for (const platform of ["MacIntel", "Win32", "Linux"]) { + const mac = platform === "MacIntel"; + for (const [key, shiftedKey, code, direction] of [ + ["[", "{", "BracketLeft", "previous"], + ["]", "}", "BracketRight", "next"], + ] as const) { + const shortcut = event({ + key: mac ? shiftedKey : key, + code, + metaKey: mac, + ctrlKey: !mac, + altKey: !mac, + shiftKey: mac, + }); + assert.strictEqual( + resolveShortcutCommand(shortcut, DEFAULT_RESOLVED_KEYBINDINGS, { + platform, + context: { terminalFocus: true }, + }), + `terminal.${direction}`, + ); + if (mac) { + assert.strictEqual( + resolveShortcutCommand(shortcut, DEFAULT_RESOLVED_KEYBINDINGS, { + platform, + context: { terminalFocus: false }, + }), + `thread.${direction}`, + ); + } + } + if (mac) { + for (const key of ["[", "]"]) { + const command = resolveShortcutCommand( + event({ key, metaKey: true }), + DEFAULT_RESOLVED_KEYBINDINGS, + { + platform, + context: { terminalFocus: true }, + }, + ); + assert.notStrictEqual(command, "terminal.previous"); + assert.notStrictEqual(command, "terminal.next"); + } + } + assert.isNull( + resolveShortcutCommand(event({ key: "[", ctrlKey: true }), DEFAULT_RESOLVED_KEYBINDINGS, { + platform, + context: { terminalFocus: true }, + }), + ); + } }); it("matches punctuation shortcuts by physical key across keyboard layouts", () => { diff --git a/apps/web/src/keybindings.ts b/apps/web/src/keybindings.ts index 117847faa95bb..3361faa3e54f7 100644 --- a/apps/web/src/keybindings.ts +++ b/apps/web/src/keybindings.ts @@ -79,6 +79,7 @@ function resolveContext(options: ShortcutMatchOptions | undefined): ShortcutMatc isWeb: !isElectron, isDesktop: isElectron, editableFocus: false, + isMac: isMacPlatform(resolvePlatform(options)), ...options?.context, }; } @@ -386,6 +387,15 @@ export function isTerminalNewShortcut( return matchesCommandShortcut(event, keybindings, "terminal.new", options); } +export function isTerminalCycleShortcut( + event: ShortcutEventLike, + keybindings: ResolvedKeybindingsConfig, + options?: ShortcutMatchOptions, +): boolean { + const command = resolveShortcutCommand(event, keybindings, options); + return command === "terminal.previous" || command === "terminal.next"; +} + export function isTerminalCloseShortcut( event: ShortcutEventLike, keybindings: ResolvedKeybindingsConfig, diff --git a/apps/web/src/lib/cycleThreadTerminal.test.ts b/apps/web/src/lib/cycleThreadTerminal.test.ts new file mode 100644 index 0000000000000..eec8a83da0a86 --- /dev/null +++ b/apps/web/src/lib/cycleThreadTerminal.test.ts @@ -0,0 +1,93 @@ +import { scopeThreadRef } from "@t3tools/client-runtime/environment"; +import { EnvironmentId, ThreadId } from "@t3tools/contracts"; +import { expect, it } from "vite-plus/test"; + +import { selectThreadRightPanelState, useRightPanelStore } from "../rightPanelStore"; +import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore"; +import { cycleThreadTerminal } from "./cycleThreadTerminal"; +import { registerTerminalFocusTarget } from "./terminalFocus"; + +function setup() { + useTerminalUiStateStore.setState({ + terminalUiStateByThreadKey: {}, + suppressedTerminalIdsByThreadKey: {}, + serverObservationsByThreadKey: {}, + }); + useRightPanelStore.setState({ byThreadKey: {} }); + return scopeThreadRef(EnvironmentId.make("local"), ThreadId.make("cycle")); +} + +it("cycles drawer tabs and split panes in display order, wraps both ways, and focuses the target", () => { + const ref = setup(); + const drawer = useTerminalUiStateStore.getState(); + drawer.newTerminal(ref, "a"); + drawer.newTerminal(ref, "b"); + drawer.setActiveTerminal(ref, "a"); + drawer.splitTerminal(ref, "c"); + drawer.newTerminal(ref, "z"); + drawer.reconcileTerminalIds(ref, ["z", "c", "b", "a"]); + let focused: string | null = null; + const unregister = ["a", "c", "b", "z"].map((terminalId) => + registerTerminalFocusTarget({ + threadRef: ref, + terminalId, + focus: () => { + focused = terminalId; + return true; + }, + }), + ); + try { + drawer.setActiveTerminal(ref, "a"); + for (const expected of ["c", "b", "z", "a"]) { + expect(cycleThreadTerminal(ref, "drawer", "next")).toBe(true); + expect( + selectThreadTerminalUiState( + useTerminalUiStateStore.getState().terminalUiStateByThreadKey, + ref, + ).activeTerminalId, + ).toBe(expected); + expect(focused).toBe(expected); + } + cycleThreadTerminal(ref, "drawer", "previous"); + expect(focused).toBe("z"); + const remoteRef = scopeThreadRef(EnvironmentId.make("remote"), ref.threadId); + expect(cycleThreadTerminal(remoteRef, "drawer", "next")).toBe(false); + drawer.setTerminalOpen(ref, false); + expect(cycleThreadTerminal(ref, "drawer", "next")).toBe(false); + } finally { + for (const dispose of unregister) dispose(); + } +}); + +it("cycles panel terminal surfaces and splits without changing the drawer", () => { + const ref = setup(); + const drawer = useTerminalUiStateStore.getState(); + drawer.newTerminal(ref, "drawer"); + const panels = useRightPanelStore.getState(); + panels.openTerminal(ref, "a"); + const firstSurfaceId = selectThreadRightPanelState( + useRightPanelStore.getState().byThreadKey, + ref, + ).activeSurfaceId!; + panels.splitTerminal(ref, firstSurfaceId, "b"); + panels.openFile(ref, "notes.md"); + expect(cycleThreadTerminal(ref, "right-panel", "next")).toBe(false); + panels.openTerminal(ref, "c"); + for (const [direction, expected] of [ + ["next", "a"], + ["previous", "c"], + ["previous", "b"], + ] as const) { + expect(cycleThreadTerminal(ref, "right-panel", direction)).toBe(true); + const state = selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, ref); + const active = state.surfaces.find((surface) => surface.id === state.activeSurfaceId); + expect(active).toMatchObject({ kind: "terminal", activeTerminalId: expected }); + } + expect( + selectThreadTerminalUiState(useTerminalUiStateStore.getState().terminalUiStateByThreadKey, ref) + .activeTerminalId, + ).toBe("drawer"); + panels.close(ref); + expect(cycleThreadTerminal(ref, "right-panel", "next")).toBe(false); +}); diff --git a/apps/web/src/lib/cycleThreadTerminal.ts b/apps/web/src/lib/cycleThreadTerminal.ts new file mode 100644 index 0000000000000..0ad20eb23eb8a --- /dev/null +++ b/apps/web/src/lib/cycleThreadTerminal.ts @@ -0,0 +1,54 @@ +import type { ScopedThreadRef } from "@t3tools/contracts"; + +import { selectThreadRightPanelState, useRightPanelStore } from "../rightPanelStore"; +import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore"; +import { focusTerminal, type TerminalFocusOwner } from "./terminalFocus"; + +export function cycleThreadTerminal( + threadRef: ScopedThreadRef, + owner: TerminalFocusOwner, + direction: "previous" | "next", +): boolean { + const drawer = useTerminalUiStateStore.getState(); + const panels = useRightPanelStore.getState(); + const drawerState = selectThreadTerminalUiState(drawer.terminalUiStateByThreadKey, threadRef); + const panelState = selectThreadRightPanelState(panels.byThreadKey, threadRef); + const activeSurface = panelState.surfaces.find( + (surface) => surface.id === panelState.activeSurfaceId, + ); + const terminalOrder = new Map(drawerState.terminalIds.map((id, index) => [id, index])); + const groupRank = (ids: readonly string[]) => + Math.min(...ids.map((id) => terminalOrder.get(id) ?? Number.POSITIVE_INFINITY)); + const terminalIds = + owner === "drawer" + ? drawerState.terminalGroups + .toSorted((left, right) => groupRank(left.terminalIds) - groupRank(right.terminalIds)) + .flatMap((group) => group.terminalIds) + : panelState.surfaces.flatMap((surface) => + surface.kind === "terminal" ? surface.terminalIds : [], + ); + const activeTerminalId = + owner === "drawer" + ? drawerState.activeTerminalId + : activeSurface?.kind === "terminal" + ? activeSurface.activeTerminalId + : null; + const index = activeTerminalId === null ? -1 : terminalIds.indexOf(activeTerminalId); + if (index === -1 || (owner === "drawer" ? !drawerState.terminalOpen : !panelState.isOpen)) + return false; + const offset = direction === "next" ? 1 : -1; + const terminalId = terminalIds[(index + offset + terminalIds.length) % terminalIds.length]; + if (terminalId === undefined) return false; + if (owner === "drawer") { + drawer.setActiveTerminal(threadRef, terminalId); + } else { + const surface = panelState.surfaces.find( + (surface) => surface.kind === "terminal" && surface.terminalIds.includes(terminalId), + ); + if (!surface) return false; + panels.activateTerminal(threadRef, surface.id, terminalId); + panels.activateSurface(threadRef, surface.id); + } + focusTerminal(threadRef, terminalId); + return true; +} diff --git a/docs/user/terminal.md b/docs/user/terminal.md index 6af3ece46313c..9fb3b96f16240 100644 --- a/docs/user/terminal.md +++ b/docs/user/terminal.md @@ -46,6 +46,11 @@ then copy. Cmd+A on macOS and Ctrl+Shift+A elsewhere select the same output. Ctrl+A still moves to the beginning of shell input on Windows and Linux. Jump to latest in the context menu returns to the current output. +While a terminal is focused, use `Cmd+Shift+]` for the next terminal and `Cmd+Shift+[` for +the previous one on macOS. On Windows and Linux, use `Ctrl+Alt+]` and `Ctrl+Alt+[`. Cycling +wraps through tabs and split panes in the focused drawer or right panel. Rebind these +shortcuts in Settings > Keybindings. + On iPhone and iPad, long-press the terminal to paste or to choose Select Text. Select Text shows the visible output, where you can copy text or tap a link. diff --git a/packages/contracts/src/keybindings.ts b/packages/contracts/src/keybindings.ts index eda5138b760b9..855afb74013a5 100644 --- a/packages/contracts/src/keybindings.ts +++ b/packages/contracts/src/keybindings.ts @@ -66,6 +66,8 @@ export const STATIC_KEYBINDING_COMMANDS = [ "terminal.splitVertical", "terminal.new", "terminal.close", + "terminal.previous", + "terminal.next", "rightPanel.toggle", "rightPanel.new", "threadPanel.toggle", diff --git a/packages/shared/src/keybindings.ts b/packages/shared/src/keybindings.ts index 3d9fcc0727d3d..acca591ec68ac 100644 --- a/packages/shared/src/keybindings.ts +++ b/packages/shared/src/keybindings.ts @@ -73,6 +73,8 @@ export const DEFAULT_KEYBINDINGS: ReadonlyArray = [ { key: "mod+shift+d", command: "composer.dictation", when: "!terminalFocus" }, { key: "mod+n", command: "terminal.new", when: "terminalFocus" }, { key: "mod+w", command: "terminal.close", when: "terminalFocus" }, + { key: "ctrl+alt+[", command: "terminal.previous", when: "terminalFocus && !isMac" }, + { key: "ctrl+alt+]", command: "terminal.next", when: "terminalFocus && !isMac" }, { key: "mod+w", command: "rightPanel.close", when: "!terminalFocus" }, { key: "mod+shift+t", command: "view.reopenClosed" }, { key: "mod+d", command: "diff.toggle", when: "!terminalFocus" }, @@ -128,6 +130,8 @@ export const DEFAULT_KEYBINDINGS: ReadonlyArray = [ { key: "mod+o", command: "editor.openFavorite" }, { key: "mod+shift+[", command: "thread.previous" }, { key: "mod+shift+]", command: "thread.next" }, + { key: "cmd+shift+[", command: "terminal.previous", when: "terminalFocus && isMac" }, + { key: "cmd+shift+]", command: "terminal.next", when: "terminalFocus && isMac" }, { key: "mod+shift+c", command: "thread.copyReference", when: "!terminalFocus" }, { key: "mod+shift+s", command: "thread.settle", when: "!terminalFocus" }, { key: "mod+shift+p", command: "thread.pin", when: "!terminalFocus" }, From 87ac7d9446fe0cb42c290c8063bfd700eb01d4da Mon Sep 17 00:00:00 2001 From: Victor Date: Tue, 24 Nov 2026 19:35:22 -0600 Subject: [PATCH 017/880] fix(server): content search while indexing no longer breaks under user git config (#42520) Co-authored-by: Julius Marminge (cherry picked from commit 02dc3e440066a971f51e02f360f336b108b13460) --- .../workspace/WorkspaceSearchIndex.test.ts | 20 +++++++++++++++++-- .../src/workspace/WorkspaceSearchIndex.ts | 6 ++++++ 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/apps/server/src/workspace/WorkspaceSearchIndex.test.ts b/apps/server/src/workspace/WorkspaceSearchIndex.test.ts index 9a8e63f972b3c..a406f3cb8a4a3 100644 --- a/apps/server/src/workspace/WorkspaceSearchIndex.test.ts +++ b/apps/server/src/workspace/WorkspaceSearchIndex.test.ts @@ -302,8 +302,24 @@ it.live("answers content searches with git grep while a slow content index build const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; const vcsProcess = yield* VcsProcess.VcsProcess; - const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-content-warmup-" }); - yield* vcsProcess.run({ operation: "test.gitInit", command: "git", args: ["init"], cwd }); + const repoRoot = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-content-warmup-" }); + yield* vcsProcess.run({ + operation: "test.gitInit", + command: "git", + args: ["init"], + cwd: repoRoot, + }); + // User git config must not change git grep's records or make it refuse --untracked. + for (const setting of ["grep.column", "grep.fullName", "submodule.recurse"]) { + yield* vcsProcess.run({ + operation: "test.gitConfig", + command: "git", + args: ["config", setting, "true"], + cwd: repoRoot, + }); + } + const cwd = path.join(repoRoot, "project"); + yield* fileSystem.makeDirectory(cwd); yield* fileSystem.writeFileString(path.join(cwd, ".gitignore"), "ignored.txt\n"); yield* fileSystem.makeDirectory(path.join(cwd, "src")); yield* fileSystem.writeFileString( diff --git a/apps/server/src/workspace/WorkspaceSearchIndex.ts b/apps/server/src/workspace/WorkspaceSearchIndex.ts index 0006fab285dd4..ddef21beae0a8 100644 --- a/apps/server/src/workspace/WorkspaceSearchIndex.ts +++ b/apps/server/src/workspace/WorkspaceSearchIndex.ts @@ -749,6 +749,12 @@ export const make = Effect.fn("WorkspaceSearchIndex.make")(function* ( "core.quotePath=false", "-c", "core.fsmonitor=false", + "-c", + "grep.column=false", + "-c", + "grep.fullName=false", + "-c", + "submodule.recurse=false", "grep", "--untracked", "--no-color", From f7010f07f00c19fcba71d2a6252b57c662e591ab Mon Sep 17 00:00:00 2001 From: MauriceCRRR <149700827+MauriceCRRR@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:36:01 +0100 Subject: [PATCH 018/880] fix(server): a themes folder replaced by a link at start-up is still followed (#42516) Co-authored-by: Julius Marminge (cherry picked from commit 2aec607976e8a70c3f9c37566dfb9605f3d9a339) --- .../src/watchDirectoryReplacements.test.ts | 131 +++++++++++++++++- apps/server/src/watchDirectoryReplacements.ts | 43 ++++-- 2 files changed, 157 insertions(+), 17 deletions(-) diff --git a/apps/server/src/watchDirectoryReplacements.test.ts b/apps/server/src/watchDirectoryReplacements.test.ts index 09c5c2522b34e..bfa3b7434ad34 100644 --- a/apps/server/src/watchDirectoryReplacements.test.ts +++ b/apps/server/src/watchDirectoryReplacements.test.ts @@ -4,14 +4,55 @@ import { assert, it } from "@effect/vitest"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Path from "effect/Path"; +import * as PlatformError from "effect/PlatformError"; import * as Queue from "effect/Queue"; import * as Stream from "effect/Stream"; +import * as TestClock from "effect/testing/TestClock"; +import { vi } from "vite-plus/test"; import { watchDirectoryPath } from "./watchDirectoryReplacements.ts"; -it.live.skipIf(!symlinksSupported)( - "backs off stopped watches for an unchanged linked directory", - () => +// Watches under this root open but report only what a test sends, as a macOS watch can stay +// silent before it is armed. Their paths resolve to themselves unless linked or missing. +const silent = vi.hoisted(() => ({ + root: "/silent-watch", + owns(path: unknown): path is string { + return ( + typeof path === "string" && + (path === this.root || path.startsWith(`${this.root}/`) || path.startsWith(`${this.root}\\`)) + ); + }, + links: new Map(), + missing: new Set(), + listeners: new Map void>(), +})); + +vi.mock("node:fs", async (importOriginal) => { + const actual = await importOriginal(); + const watch = (...args: Parameters) => { + const [path, listener] = args; + if (!silent.owns(path)) return actual.watch(...args); + const report = listener as (event: string, filename: string | null) => void; + silent.listeners.set(path, report); + return { + on: () => undefined, + close: () => silent.listeners.get(path) === report && silent.listeners.delete(path), + }; + }; + const native = (...args: Parameters) => { + const [path, callback] = args; + if (!silent.owns(path)) return actual.realpath.native(...args); + if (silent.missing.has(path)) { + return callback(Object.assign(new Error(`ENOENT: ${path}`), { code: "ENOENT" }), ""); + } + return callback(null, silent.links.get(path) ?? path); + }; + return { ...actual, watch, realpath: Object.assign(actual.realpath.bind(undefined), { native }) }; +}); + +it.live.each(["linked", "plain"] as const)( + "backs off stopped watches for an unchanged %s directory", + (kind) => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; @@ -21,7 +62,8 @@ it.live.skipIf(!symlinksSupported)( const second = path.join(base, "second", "themes"); yield* fs.makeDirectory(first, { recursive: true }); yield* fs.makeDirectory(second, { recursive: true }); - yield* fs.symlink(first, entry); + if (kind === "linked" && !symlinksSupported) return; + yield* kind === "linked" ? fs.symlink(first, entry) : fs.makeDirectory(entry); const firstIdentity = yield* fs.stat(first); const secondIdentity = yield* fs.stat(second); let identity = firstIdentity; @@ -103,3 +145,84 @@ it.live.skipIf(!symlinksSupported)( assert.deepEqual(identities, []); }).pipe(Effect.provide(NodeServices.layer)), ); + +it.effect.each([ + { name: "another directory", folder: "elsewhere", linkedStat: "other" }, + { name: "a directory that is gone", folder: "gone", linkedStat: "missing" }, +] as const)( + "follows a directory replaced by a link to $name when its parent watch reports nothing", + ({ folder, linkedStat }) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const plain = yield* fs.stat(yield* fs.makeTempDirectoryScoped()); + const other = yield* fs.stat(yield* fs.makeTempDirectoryScoped()); + silent.root = path.resolve("/silent-watch", folder); + const entry = path.join(silent.root, "userdata", "themes"); + const target = path.join(silent.root, folder, "themes"); + let linked = false; + const acquisitions = yield* Queue.unbounded(); + const fail = (method: string, _tag: "InvalidData" | "NotFound") => + Effect.fail( + PlatformError.systemError({ + _tag, + module: "FileSystem", + method, + pathOrDescriptor: entry, + }), + ); + silent.links.clear(); + silent.missing.clear(); + + yield* watchDirectoryPath( + entry, + Stream.fromEffect(Effect.asVoid(Queue.offer(acquisitions, undefined))).pipe( + Stream.concat(Stream.never), + ), + Effect.succeed(false), + ).pipe( + Stream.runDrain, + Effect.provideService( + FileSystem.FileSystem, + FileSystem.FileSystem.of({ + ...fs, + // The watcher reuses the effects it builds, so each run reads the fixture afresh. + readLink: (file) => + silent.owns(file) + ? Effect.suspend(() => + file === entry && linked + ? Effect.succeed(target) + : fail("readLink", "InvalidData"), + ) + : fs.readLink(file), + stat: (file) => + file !== entry + ? fs.stat(file) + : Effect.suspend(() => + !linked + ? Effect.succeed(plain) + : linkedStat === "other" + ? Effect.succeed(other) + : fail("stat", "NotFound"), + ), + }), + ), + Effect.forkScoped, + ); + yield* Queue.take(acquisitions); + + // Replaced by a link with no parent event: only the next probe can see it. + linked = true; + silent.links.set(entry, target); + if (linkedStat === "missing") silent.missing.add(entry); + yield* TestClock.adjust("1 second"); + assert.equal(yield* Queue.size(acquisitions), 1); + yield* Queue.take(acquisitions); + + // The link target's parent is watched now: replacing the target rearms its contents. + const targetParent = silent.listeners.get(path.dirname(target)); + assert.isDefined(targetParent); + targetParent("rename", path.basename(target)); + yield* Queue.take(acquisitions); + }).pipe(Effect.provide(NodeServices.layer)), +); diff --git a/apps/server/src/watchDirectoryReplacements.ts b/apps/server/src/watchDirectoryReplacements.ts index 315069ec5e72c..ee6d320617635 100644 --- a/apps/server/src/watchDirectoryReplacements.ts +++ b/apps/server/src/watchDirectoryReplacements.ts @@ -106,9 +106,6 @@ export const watchDirectoryPath = ( Stream.unwrap( Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; - const link = yield* fs.readLink(entry).pipe(Effect.option); - if (Option.isNone(link)) return watchChild; - let childEnded = false; const watchContents = Stream.suspend(() => { childEnded = false; @@ -121,13 +118,30 @@ export const watchDirectoryPath = ( ); }); - // One stat per second for linked paths catches ancestor replacements the watches cannot see. - const identity = fs.stat(entry).pipe( - Effect.map( - (info) => - `${info.dev}:${info.ino.valueOrUndefined}:${info.birthtime.valueOrUndefined?.getTime()}`, - ), - Effect.orElseSucceed(() => null), + const statIdentity = fs + .stat(entry) + .pipe( + Effect.map( + (info) => + `${info.dev}:${info.ino.valueOrUndefined}:${info.birthtime.valueOrUndefined?.getTime()}`, + ), + ); + // One probe per second catches replacements the watches cannot see: a link target's + // ancestors, or the entry becoming a link before macOS has armed the parent watch. + // A missing entry probes as null and a link whose target is missing as "". + const identity = fs.readLink(entry).pipe( + Effect.matchEffect({ + onSuccess: (link) => + statIdentity.pipe( + Effect.map((id) => `link:${id}:${link}`), + Effect.orElseSucceed(() => ""), + ), + onFailure: () => + statIdentity.pipe( + Effect.map((id) => `plain:${id}`), + Effect.orElseSucceed(() => null), + ), + }), ); // The identity of the tree the current watches were acquired on. let previous: string | null | undefined; @@ -141,7 +155,7 @@ export const watchDirectoryPath = ( Stream.mapEffect(([current, tick]) => Effect.gen(function* () { // A catalog read can see the path missing even if both probes see the same inode. - const sawMissing = current !== null && (yield* consumeMissingObservation); + const sawMissing = Boolean(current) && (yield* consumeMissingObservation); const replaced = previous !== undefined && current !== previous; const firstProbe = previous === undefined; previous = current; @@ -152,7 +166,7 @@ export const watchDirectoryPath = ( } if (firstProbe) return false; if (replaced || sawMissing) return true; - if (!childEnded || current === null || tick < nextRetry) return false; + if (!childEnded || !current || tick < nextRetry) return false; // A stable inode can stay unwatchable due to permissions or OS watch limits. retryDelay = Math.min(60, retryDelay * 2); @@ -172,7 +186,10 @@ export const watchDirectoryPath = ( previous = acquired; }), ), - Effect.andThen(resolveLinkedPath(entry, link.value)), + Effect.andThen(fs.readLink(entry).pipe(Effect.option)), + Effect.flatMap((link) => + Option.isSome(link) ? resolveLinkedPath(entry, link.value) : Effect.succeed(entry), + ), Effect.map((target) => { if (target === entry || target === NodePath.dirname(target)) return watchContents; return watchDirectoryReplacements( From 28e2065653fc97c22cc22cbcf86bc73df7d0e10e Mon Sep 17 00:00:00 2001 From: Kevin Kreps <38342468+KevinKreps@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:40:39 +0100 Subject: [PATCH 019/880] fix(server): Claude instances that share a home through a symlink keep the session on switch (#42509) Co-authored-by: Julius Marminge (cherry picked from commit 5e3bc17587a48b1d1de02e91d566acde3ca41863) --- .../src/provider/Drivers/ClaudeHome.test.ts | 20 +++++++++++++++++++ .../server/src/provider/Drivers/ClaudeHome.ts | 10 ++++++++-- 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/apps/server/src/provider/Drivers/ClaudeHome.test.ts b/apps/server/src/provider/Drivers/ClaudeHome.test.ts index c772b79efe184..5cdc3e2906d3b 100644 --- a/apps/server/src/provider/Drivers/ClaudeHome.test.ts +++ b/apps/server/src/provider/Drivers/ClaudeHome.test.ts @@ -49,6 +49,26 @@ it.layer(NodeServices.layer)("ClaudeHome", (it) => { }), ); + it.effect("gives a symlinked Claude home the continuation key of its target", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fileSystem.realPath(yield* fileSystem.makeTempDirectoryScoped()); + const target = path.join(root, ".claude"); + const link = path.join(root, ".claude-second-account"); + yield* fileSystem.makeDirectory(target); + yield* fileSystem.symlink(target, link); + + const direct = yield* makeClaudeContinuationGroupKey({ homePath: target }); + expect(yield* makeClaudeContinuationGroupKey({ homePath: link })).toBe(direct); + expect( + yield* makeClaudeContinuationGroupKey({ homePath: "" }, { CLAUDE_CONFIG_DIR: link }), + ).toBe(direct); + // The spawned process keeps the literal path, because Claude keys its login by that path. + expect((yield* makeClaudeEnvironment({ homePath: link })).CLAUDE_CONFIG_DIR).toBe(link); + }).pipe(Effect.scoped), + ); + it.effect("separates capability probes by cwd", () => Effect.gen(function* () { const config = { binaryPath: "claude", homePath: "" }; diff --git a/apps/server/src/provider/Drivers/ClaudeHome.ts b/apps/server/src/provider/Drivers/ClaudeHome.ts index c027a32dc2a45..5e77c7d249d0c 100644 --- a/apps/server/src/provider/Drivers/ClaudeHome.ts +++ b/apps/server/src/provider/Drivers/ClaudeHome.ts @@ -147,9 +147,15 @@ export const makeClaudeContinuationGroupKey = Effect.fn("makeClaudeContinuationG function* ( config: Pick, environment?: NodeJS.ProcessEnv, - ): Effect.fn.Return { + ): Effect.fn.Return { + const fileSystem = yield* FileSystem.FileSystem; const resolvedHomePath = yield* resolveClaudeHomePath(config, environment); - return `claude:home:${resolvedHomePath}`; + // Two instances that reach one Claude home through a symlink share sessions, so they can resume. + // Only the key uses the real path: the spawn keeps the literal path, which names the Keychain login. + const canonicalHomePath = yield* fileSystem + .realPath(resolvedHomePath) + .pipe(Effect.orElseSucceed(() => resolvedHomePath)); + return `claude:home:${canonicalHomePath}`; }, ); From 00c417af9e527ca7649ec5bbeb22c12bfac5690a Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 24 Nov 2026 17:46:13 -0800 Subject: [PATCH 020/880] fix(server): delegate_task worktree children start every repository from the parent's branch (#42546) (cherry picked from commit 31d95f850bd8f1dfb68676500606d44b923e4883) --- .../src/mcp/OrchestratorMcpService.test.ts | 112 ++++++++++++++++++ apps/server/src/mcp/OrchestratorMcpService.ts | 17 ++- 2 files changed, 128 insertions(+), 1 deletion(-) diff --git a/apps/server/src/mcp/OrchestratorMcpService.test.ts b/apps/server/src/mcp/OrchestratorMcpService.test.ts index 6b81edf7dcdf5..74cc232f7030a 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.test.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.test.ts @@ -37,6 +37,7 @@ import * as Deferred from "effect/Deferred"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; +import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Queue from "effect/Queue"; @@ -63,6 +64,7 @@ import { OrchestratorThreadAboveModeLimitError, } from "../orchestration-v2/Orchestrator.ts"; import * as ProviderAdapterRegistry from "../orchestration-v2/ProviderAdapterRegistry.ts"; +import * as ServerConfig from "../config.ts"; import * as ThreadLaunchService from "../orchestration-v2/ThreadLaunchService.ts"; import * as GitVcsDriver from "../vcs/GitVcsDriver.ts"; import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts"; @@ -2815,6 +2817,116 @@ describe("OrchestratorMcpService provider resolution", () => { }), ); + // docs/user/multi-repo-projects.md: each repository starts from the thread's base branch + // where it has one, so the child's launch has to carry the parent's branch, not only its commit. + it.live( + "names the parent's branch as a worktree child's base so other repositories can match it", + () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const git = yield* GitVcsDriver.GitVcsDriver; + const workspaceRoot = yield* fileSystem.realPath( + yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-mcp-delegate-base-" }), + ); + for (const args of [ + ["init", "-b", "main"], + ["config", "user.email", "delegate@example.test"], + ["config", "user.name", "Delegate"], + ["commit", "--allow-empty", "-m", "main"], + ["checkout", "-b", "release"], + ["commit", "--allow-empty", "-m", "release"], + ]) { + yield* git.execute({ operation: "delegate-base-test", cwd: workspaceRoot, args }); + } + const commands: Array = []; + const task = { + id: taskId, + threadId: parentThreadId, + origin: "app_owned", + childThreadId, + providerInstanceId: codexInstanceId, + model: "gpt-5.4", + status: "running", + result: null, + }; + const dependencies = Layer.mergeAll( + Layer.mock(ThreadManagementService.ThreadManagementService)({ + hasReceipt: () => Effect.succeed(false), + getThreadRecords: (threadId) => + Effect.succeed( + threadId === parentThreadId + ? (() => { + const parent = parentProjection(commands.length > 0 ? [task] : []); + return { + ...parent, + thread: { ...parent.thread, worktreePath: null, branch: "release" }, + } as OrchestrationV2ThreadProjection; + })() + : childProjection, + ), + dispatch: (command) => + Effect.sync(() => { + commands.push(command); + return { + sequence: 1, + storedEvents: [{ event: { type: "subagent.updated", payload: task } }], + } as never; + }), + }), + ServerSettings.layerTest(), + providerRegistryLayer([ + providerSnapshot({ + instanceId: codexInstanceId, + driver: ProviderDriverKind.make("codex"), + model: "gpt-5.4", + }), + ]), + adapterRegistryLayer([codexInstanceId]), + Layer.mock(ProjectService.ProjectService)({ + getById: () => + Effect.succeedSome({ id: projectId, title: "parent", workspaceRoot } as never), + }), + Layer.mock(SecretRequests.SecretRequests)({}), + Layer.mock(RemoteDelegation.RemoteDelegation)({}), + Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), + Layer.mock(ThreadLaunchService.ThreadLaunchService)({ + isNonGitProject: () => Effect.succeed(false), + }), + Layer.succeed(GitVcsDriver.GitVcsDriver, git), + ); + yield* Effect.gen(function* () { + const service = yield* OrchestratorMcpService.OrchestratorMcpService; + yield* service.delegateTask(scope, { + task: "Change a and b together.", + isolation: "worktree", + mode: "async", + clientRequestId: "worktree-parent-branch", + }); + const workspaceStrategy = (commands[0] as { workspaceStrategy?: unknown }) + .workspaceStrategy; + assert.include( + JSON.stringify(workspaceStrategy), + "release", + "the child's workspace names only the parent's commit, so other repositories fall back to their default branch", + ); + }).pipe(Effect.provide(OrchestratorMcpService.layer.pipe(Layer.provide(dependencies)))); + }).pipe( + Effect.provide( + Layer.mergeAll( + NodeServices.layer, + NodeCrypto.layer, + GitVcsDriver.layer.pipe( + Layer.provideMerge( + ServerConfig.layerTest(process.cwd(), { prefix: "t3-mcp-delegate-base-" }), + ), + Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), + ), + ), + ), + Effect.scoped, + ), + ); + it.effect("rejects delegation to a provider without a registered adapter", () => Effect.gen(function* () { const forkOnlyInstanceId = ProviderInstanceId.make("forkOnly"); diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index 9bce3793aa4a6..6f52663a0836a 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -3004,7 +3004,22 @@ const make = Effect.gen(function* () { ), ); } - workspaceStrategy = { type: "worktree", baseRef: base.commitSha, startFromOrigin: false }; + // Other repositories in the project can only match a branch name, so name the + // parent's branch when it still points at the parent's commit. + const branch = parent.thread.branch; + const branchAtBase = + branch !== null && + (yield* gitDriver + .resolveCommit({ cwd: project.workspaceRoot, revision: `refs/heads/${branch}` }) + .pipe( + Effect.map((resolved) => resolved.commitSha === base.commitSha), + Effect.orElseSucceed(() => false), + )); + workspaceStrategy = { + type: "worktree", + baseRef: branchAtBase ? branch : base.commitSha, + startFromOrigin: false, + }; } const parentNodeId = parentRun.rootNodeId; // The command commits the child's preparing run, which only this call From a6096d23b2228cd9e8b3435aec72711907c700a9 Mon Sep 17 00:00:00 2001 From: Victor Date: Tue, 24 Nov 2026 20:08:47 -0600 Subject: [PATCH 021/880] fix(web): project action keybinding field records shortcuts instead of running them (#42543) Co-authored-by: Julius Marminge (cherry picked from commit 51a8d20271557b3ac2bf1305e5743f6d41ee8a13) --- .../chat/useChatShortcuts.browser.test.tsx | 40 ++++++++++++++++++- .../src/components/chat/useChatShortcuts.ts | 3 ++ .../projectScriptEditor.browser.test.tsx | 38 ++++++++++++++++++ .../src/components/projectScriptEditor.tsx | 13 ++++++ .../src/shortcuts/dispatcher.browser.test.ts | 23 +++++++++++ apps/web/src/shortcuts/dispatcher.ts | 5 +++ 6 files changed, 120 insertions(+), 2 deletions(-) diff --git a/apps/web/src/components/chat/useChatShortcuts.browser.test.tsx b/apps/web/src/components/chat/useChatShortcuts.browser.test.tsx index 472bc009ed344..da21e11af39d4 100644 --- a/apps/web/src/components/chat/useChatShortcuts.browser.test.tsx +++ b/apps/web/src/components/chat/useChatShortcuts.browser.test.tsx @@ -58,11 +58,13 @@ function Chat(props: { composerKeys: string[]; launcher?: { keys: string; received: string[] }; finds?: string[]; + scriptKeybindings?: ResolvedKeybindingsConfig; + scriptsRan?: string[]; }) { useChatShortcuts({ enabled: true, keybindings: [ctrl("f", "chat.find")], - scriptKeybindings: [], + scriptKeybindings: props.scriptKeybindings ?? [], getShortcutContext: () => shortcutContext, threadFindActive: false, // Type-to-focus only calls insertTextAtEnd, so the stand-in composer implements just that. @@ -77,7 +79,8 @@ function Chat(props: { branchToolbarRef: { current: null }, closeThreadFind: () => {}, commands: { "chat.find": () => void props.finds?.push("main") }, - fallback: () => undefined, + fallback: (command) => + props.scriptsRan ? () => void props.scriptsRan?.push(command) : undefined, }); return props.launcher ? : null; } @@ -393,3 +396,36 @@ it("leaves keys to a focused video player with controls", async () => { await userEvent.keyboard("a"); expect(composerKeys).toEqual(["a"]); }); + +it("leaves project-script shortcuts alone inside a keybinding capture field", async () => { + const scriptsRan: string[] = []; + const prevented: boolean[] = []; + await using screen = await render( + <> + + { + if (event.key.toLowerCase() === "y") prevented.push(event.defaultPrevented); + }} + /> + + , + options, + ); + + await userEvent.keyboard("{Control>}{Shift>}Y{/Shift}{/Control}"); + expect(scriptsRan).toEqual([]); + expect(prevented).toEqual([false]); + + await userEvent.click(screen.getByRole("button", { name: "Outside" })); + await userEvent.keyboard("{Control>}{Shift>}Y{/Shift}{/Control}"); + expect(scriptsRan).toEqual(["script.build.run"]); +}); diff --git a/apps/web/src/components/chat/useChatShortcuts.ts b/apps/web/src/components/chat/useChatShortcuts.ts index e8805b6c91809..d3b0ccff512b0 100644 --- a/apps/web/src/components/chat/useChatShortcuts.ts +++ b/apps/web/src/components/chat/useChatShortcuts.ts @@ -62,6 +62,9 @@ export function useChatShortcuts(input: ChatShortcutsInput) { const embedded = input.embedded === true; const composerElement = embedded ? (input.composerElement ?? null) : null; const handleShortcut = useEffectEvent((event: KeyboardEvent) => { + if (event.target instanceof Element && event.target.closest("[data-keybinding-capture]")) { + return; + } const { keybindings } = input; if (preventRepeatedTerminalCloseShortcut(event, keybindings)) { event.stopPropagation(); diff --git a/apps/web/src/components/projectScriptEditor.browser.test.tsx b/apps/web/src/components/projectScriptEditor.browser.test.tsx index 0f37c32b23a9e..cb7d73c98edde 100644 --- a/apps/web/src/components/projectScriptEditor.browser.test.tsx +++ b/apps/web/src/components/projectScriptEditor.browser.test.tsx @@ -100,3 +100,41 @@ describe("project action editor dismissal", () => { expect(onClose).not.toHaveBeenCalled(); }); }); + +describe("project action editor keybinding capture", () => { + it("captures modified shortcuts, ignores IME composition, and lets bare Escape close", async () => { + setup(); + await using screen = await render(null); + await open(screen, { scriptId: null, initial: EMPTY_PROJECT_SCRIPT_INPUT }); + await expect.element(page.getByRole("dialog")).toBeVisible(); + + const field = page.getByLabelText("Keybinding"); + await expect.element(field).toHaveAttribute("data-keybinding-capture", ""); + await field.click(); + await expect.element(field).toHaveFocus(); + + await userEvent.keyboard("{Shift>}{Escape}{/Shift}"); + await expect.element(field).toHaveValue("shift+esc"); + expect(onClose).not.toHaveBeenCalled(); + + for (const composition of [ + { key: "a", isComposing: true }, + { key: "a", isComposing: false, keyCode: 229 }, + ]) { + const keydown = new KeyboardEvent("keydown", { + ...composition, + bubbles: true, + cancelable: true, + }); + await act(() => { + field.element().dispatchEvent(keydown); + }); + expect(keydown.defaultPrevented).toBe(false); + await expect.element(field).toHaveValue("shift+esc"); + } + + await userEvent.keyboard("{Escape}"); + await expect.element(field).toHaveValue("shift+esc"); + expect(onClose).toHaveBeenCalledTimes(1); + }); +}); diff --git a/apps/web/src/components/projectScriptEditor.tsx b/apps/web/src/components/projectScriptEditor.tsx index 0f0edc100d0b0..65db905a79d3c 100644 --- a/apps/web/src/components/projectScriptEditor.tsx +++ b/apps/web/src/components/projectScriptEditor.tsx @@ -347,8 +347,20 @@ function ProjectScriptEditorForm({ const captureKeybinding = (event: KeyboardEvent) => { if (!readEnvironmentScope(environmentId, editScope)) return; if (!readEnvironmentScope(environmentId, AuthSettingsWriteScope)) return; + if (event.nativeEvent.isComposing || event.keyCode === 229) return; if (event.key === "Tab") return; + // Leave bare Escape unhandled so it keeps dismissing the dialog. + if ( + event.key === "Escape" && + !event.shiftKey && + !event.altKey && + !event.ctrlKey && + !event.metaKey + ) { + return; + } event.preventDefault(); + event.stopPropagation(); if (event.key === "Backspace" || event.key === "Delete") { setKeybinding(""); return; @@ -512,6 +524,7 @@ function ProjectScriptEditorForm({ Keybinding { expect(event.defaultPrevented).toBe(true); }); + it("skips capture scopes for keydowns inside a keybinding recorder", () => { + const command = vi.fn((event: KeyboardEvent) => { + event.preventDefault(); + }); + const recorder = document.createElement("div"); + recorder.setAttribute("data-keybinding-capture", ""); + const target = document.createElement("button"); + recorder.append(target); + document.body.append(recorder); + using stack = new DisposableStack(); + stack.defer(() => recorder.remove()); + stack.defer(registerCommands({ "chat.new": command }, { keybindings, capture: true })); + + const event = new KeyboardEvent("keydown", { key: "k", cancelable: true, bubbles: true }); + target.dispatchEvent(event); + + expect(command).not.toHaveBeenCalled(); + expect(event.defaultPrevented).toBe(false); + + press("k"); + expect(command).toHaveBeenCalledOnce(); + }); + it("routes a menu action to its newest handler", () => { const older = vi.fn(); const newer = vi.fn(); diff --git a/apps/web/src/shortcuts/dispatcher.ts b/apps/web/src/shortcuts/dispatcher.ts index 9e361e825db7f..c52f254cce68b 100644 --- a/apps/web/src/shortcuts/dispatcher.ts +++ b/apps/web/src/shortcuts/dispatcher.ts @@ -57,6 +57,10 @@ function isInsideConfirmation(target: EventTarget | null): boolean { return target instanceof Element && target.closest('[role="alertdialog"]') !== null; } +function isInsideKeybindingCapture(target: EventTarget | null): boolean { + return target instanceof Element && target.closest("[data-keybinding-capture]") !== null; +} + function scopeCommandHandler(scope: CommandScope, event: KeyboardEvent) { const { commands, options } = scope; const command = resolveShortcutCommand( @@ -102,6 +106,7 @@ function runScopes(scopes: readonly CommandScope[], event: KeyboardEvent): boole } function dispatchCaptureKeyDown(event: KeyboardEvent): void { + if (isInsideKeybindingCapture(event.target)) return; runScopes(captureScopes, event); } From f7d40fedcd700c733ea94f83f41677557a0b865a Mon Sep 17 00:00:00 2001 From: "Paul Dupuy, Jr." <70114489+pauldupuyjr@users.noreply.github.com> Date: Tue, 24 Nov 2026 20:13:26 -0600 Subject: [PATCH 022/880] fix(scenarios): editor and no-model shims run on Windows (#42533) Co-authored-by: Julius Marminge (cherry picked from commit 39a8d1f33e48b420b22c9ab6cb50523d83c64a04) --- pnpm-lock.yaml | 3 ++ scripts/package.json | 1 + scripts/scenarios/start-app.ts | 28 ++++++++++++------- ...al-bare-filename-opens-its-location.e2e.ts | 10 +++++-- 4 files changed, 29 insertions(+), 13 deletions(-) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 2921906554cde..8e85c9f294751 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -2662,6 +2662,9 @@ importers: '@t3tools/contracts': specifier: workspace:* version: link:../packages/contracts + '@t3tools/provider-testing': + specifier: workspace:* + version: link:../packages/provider-testing '@t3tools/shared': specifier: workspace:* version: link:../packages/shared diff --git a/scripts/package.json b/scripts/package.json index 223c91da44780..9ccde07b389ba 100644 --- a/scripts/package.json +++ b/scripts/package.json @@ -14,6 +14,7 @@ "@electron/asar": "^4.3.0", "@electron/osx-sign": "2.7.0", "@t3tools/contracts": "workspace:*", + "@t3tools/provider-testing": "workspace:*", "@t3tools/shared": "workspace:*", "@t3tools/tailscale": "workspace:*", "agent-device": "0.21.41", diff --git a/scripts/scenarios/start-app.ts b/scripts/scenarios/start-app.ts index 59d0715ffc4c6..188b2da203ea9 100644 --- a/scripts/scenarios/start-app.ts +++ b/scripts/scenarios/start-app.ts @@ -4,6 +4,7 @@ import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeRuntime from "@effect/platform-node/NodeRuntime"; import * as NodeServices from "@effect/platform-node/NodeServices"; +import { writeFakeCli } from "@t3tools/provider-testing/fakeCli"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as NetService from "@t3tools/shared/Net"; import * as Console from "effect/Console"; @@ -57,15 +58,20 @@ export const prepareHome = Effect.fn("startApp.prepareHome")(function* (home: st yield* fs.makeDirectory(path.join(home, "userdata"), { recursive: true }); yield* fs.makeDirectory(path.join(home, "bin")); // Editor discovery is cached, so the recording shim must exist before the server starts. - const editor = path.join(home, "bin", "cursor"); - yield* fs.writeFileString( - editor, - `#!/bin/sh\nprintf '%s\\n' "$@" > "$(dirname "$0")/../editor-args.txt"\n`, - ); - yield* fs.chmod(editor, 0o755); - const noModel = path.join(home, "bin/no-model"); - yield* fs.writeFileString(noModel, "#!/bin/sh\necho 'scenarios run no model' >&2\nexit 1\n"); - yield* fs.chmod(noModel, 0o755); + writeFakeCli({ + directory: path.join(home, "bin"), + name: "cursor", + source: [ + 'import { writeFileSync } from "node:fs";', + "const lines = process.argv.slice(2).map((arg) => `${arg}\\n`);", + 'writeFileSync(new URL("../editor-args.txt", import.meta.url), lines.join(""));', + ].join("\n"), + }); + const noModel = writeFakeCli({ + directory: path.join(home, "bin"), + name: "no-model", + source: 'process.stderr.write("scenarios run no model\\n");\nprocess.exit(1);', + }); yield* fs.writeFileString( path.join(home, "userdata/settings.json"), yield* encodeSettings({ @@ -128,7 +134,9 @@ const startApp = Effect.fn("startApp")(function* (input: { yield* prepareHome(input.home); const env = { ...hostEnvironment, - PATH: `${path.join(input.home, "bin")}:${hostEnvironment.PATH ?? ""}`, + PATH: [path.join(input.home, "bin"), hostEnvironment.PATH ?? ""].join( + (yield* HostProcess.Platform) === "win32" ? ";" : ":", + ), T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "0", ...SCENARIO_MACHINE_ENV, }; diff --git a/scripts/scenarios/terminal-bare-filename-opens-its-location.e2e.ts b/scripts/scenarios/terminal-bare-filename-opens-its-location.e2e.ts index 5adbb1c8040c8..0c35f251a158e 100644 --- a/scripts/scenarios/terminal-bare-filename-opens-its-location.e2e.ts +++ b/scripts/scenarios/terminal-bare-filename-opens-its-location.e2e.ts @@ -3,6 +3,7 @@ import { expect } from "e2e"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; +import * as Path from "effect/Path"; import { T3_HOME } from "../e2e.config.ts"; import { runPromise, test, WEB } from "./t3.ts"; @@ -11,6 +12,9 @@ import { runPromise, test, WEB } from "./t3.ts"; const DIAGNOSTIC = "main.c:1:25: error: 'missing' undeclared"; const EDITOR_ARGS = `${T3_HOME}/editor-args.txt`; +const hostPath = (...segments: ReadonlyArray) => + runPromise(Effect.map(Path.Path, (path) => path.join(...segments))); + /** The file's lines, or none while it does not exist. */ const readLines = (file: string) => runPromise( @@ -41,8 +45,8 @@ test( // The input mounts before fonts and WASM finish loading and its handlers are installed. await expect(input).toHaveAttribute("data-workspace-focus-default", ""); await input.focus(); - await browser.keyboard.type("cat build.log; touch cat.done\n"); - await expect.poll(() => readLines(`${project}/cat.done`), { timeout: 30_000 }).toEqual([""]); + await browser.keyboard.type("cat build.log; echo done > cat.done\n"); + await expect.poll(() => readLines(`${project}/cat.done`), { timeout: 30_000 }).not.toEqual([]); await app.screenshot("diagnostic-printed"); // The terminal draws on a canvas, so point at the first cells of its middle row. @@ -63,6 +67,6 @@ test( await expect .poll(() => readLines(EDITOR_ARGS), { timeout: 15_000 }) - .toEqual(["--classic", "--goto", `${project}/main.c:1:25`]); + .toEqual(["--classic", "--goto", `${await hostPath(project, "main.c")}:1:25`]); }, ); From f3c856fdec5806e7ccb45014efa64364cb45df5e Mon Sep 17 00:00:00 2001 From: Victor Date: Tue, 24 Nov 2026 20:15:41 -0600 Subject: [PATCH 023/880] fix(web): Link PR dialog stops duplicate Enter submits and locks input (#42548) Co-authored-by: Julius Marminge (cherry picked from commit 7e0d1cb9ba4253682978b4a1b5bc427727ba567a) --- .../LinkPullRequestDialog.browser.test.tsx | 86 +++++++++++++++++-- .../pullRequest/LinkPullRequestDialog.tsx | 14 ++- 2 files changed, 91 insertions(+), 9 deletions(-) diff --git a/apps/web/src/components/pullRequest/LinkPullRequestDialog.browser.test.tsx b/apps/web/src/components/pullRequest/LinkPullRequestDialog.browser.test.tsx index c1d7aa99fa903..324a4d49ce96e 100644 --- a/apps/web/src/components/pullRequest/LinkPullRequestDialog.browser.test.tsx +++ b/apps/web/src/components/pullRequest/LinkPullRequestDialog.browser.test.tsx @@ -1,13 +1,17 @@ import { EnvironmentId, ThreadId } from "@t3tools/contracts"; import { expect, it, vi } from "vite-plus/test"; -import { page } from "vite-plus/test/browser"; +import { page, userEvent } from "vite-plus/test/browser"; + +const linking = vi.hoisted(() => ({ + changeLink: vi.fn<(...args: unknown[]) => Promise>(), +})); vi.mock(import("~/hooks/usePullRequestLinking"), async (original) => ({ ...(await original()), usePullRequestLinking: (() => ({ mode: "multiple", canLink: () => true, - changeLink: vi.fn(), + changeLink: linking.changeLink, })) as never, })); vi.mock(import("~/state/entities"), async (original) => ({ @@ -22,11 +26,22 @@ import { appAtomRegistry } from "~/rpc/atomRegistry"; import { act, render } from "../../../test/render"; import { LinkPullRequestDialogHost, openLinkPullRequestDialog } from "./LinkPullRequestDialog"; -it("focuses the reference input when the dialog opens", async () => { - await using _screen = await render( - - - , +const PR_URL = "https://github.com/acme/demo-app/pull/7"; + +const enterEvent = (init?: KeyboardEventInit) => + new KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true, ...init }); + +async function openDialog() { + linking.changeLink.mockReset().mockResolvedValue(undefined); + appAtomRegistry.reset(); + await using stack = new AsyncDisposableStack(); + stack.defer(() => appAtomRegistry.reset()); + const screen = stack.use( + await render( + + + , + ), ); await act(() => openLinkPullRequestDialog({ @@ -34,6 +49,61 @@ it("focuses the reference input when the dialog opens", async () => { threadId: ThreadId.make("thread"), }), ); + const owned = stack.move(); + return { + ...screen, + input: page.getByPlaceholder("Pull request URL or #42"), + [Symbol.asyncDispose]: () => owned.disposeAsync(), + }; +} + +it("focuses the reference input when the dialog opens", async () => { + await using dialog = await openDialog(); + await expect.element(dialog.input).toHaveFocus(); +}); - await expect.element(page.getByPlaceholder("Pull request URL or #42")).toHaveFocus(); +it("starts only one link request on repeated Enter presses while pending and retries after failure", async () => { + await using dialog = await openDialog(); + const pending = Promise.withResolvers(); + linking.changeLink.mockReturnValueOnce(pending.promise); + await dialog.input.fill(PR_URL); + + await act(() => { + const element = dialog.input.element(); + element.dispatchEvent(enterEvent()); + element.dispatchEvent(enterEvent()); + }); + await userEvent.keyboard("{Enter}"); + + expect(linking.changeLink).toHaveBeenCalledOnce(); + await expect.element(dialog.input).toHaveAttribute("readonly"); + + await act(() => pending.reject(new Error("link failed"))); + await expect.element(page.getByText("link failed")).toBeVisible(); + await expect.element(dialog.input).not.toHaveAttribute("readonly"); + + await userEvent.keyboard("{Enter}"); + expect(linking.changeLink).toHaveBeenCalledTimes(2); + await expect.element(dialog.input).not.toBeInTheDocument(); }); + +it.each([{ isComposing: true }, { keyCode: 229 }, { repeat: true }])( + "ignores Enter during IME composition or auto-repeat without validating or submitting: %j", + async (ignoredEnter) => { + await using dialog = await openDialog(); + + await act(() => dialog.input.element().dispatchEvent(enterEvent(ignoredEnter))); + await expect + .element(page.getByText("Paste a pull request URL or enter 123 / #123.")) + .not.toBeInTheDocument(); + expect(linking.changeLink).not.toHaveBeenCalled(); + + await dialog.input.fill(PR_URL); + await act(() => dialog.input.element().dispatchEvent(enterEvent(ignoredEnter))); + expect(linking.changeLink).not.toHaveBeenCalled(); + + await userEvent.keyboard("{Enter}"); + expect(linking.changeLink).toHaveBeenCalledOnce(); + await expect.element(dialog.input).not.toBeInTheDocument(); + }, +); diff --git a/apps/web/src/components/pullRequest/LinkPullRequestDialog.tsx b/apps/web/src/components/pullRequest/LinkPullRequestDialog.tsx index 472a8bb8bbcf5..49eb7a1466268 100644 --- a/apps/web/src/components/pullRequest/LinkPullRequestDialog.tsx +++ b/apps/web/src/components/pullRequest/LinkPullRequestDialog.tsx @@ -68,6 +68,7 @@ function LinkPullRequestDialog({ }: LinkPullRequestDialogProps) { const gt = useGT(); const inputRef = useRef(null); + const submittingRef = useRef(false); const [reference, setReference] = useState(""); const [dirty, setDirty] = useState(false); const [submitError, setSubmitError] = useState(null); @@ -97,13 +98,16 @@ function LinkPullRequestDialog({ }); const submit = async () => { + if (submittingRef.current) return; setDirty(true); if (resolved === null || "error" in resolved) return; + submittingRef.current = true; setSubmitError(null); setPending(true); const result = await settlePromise(() => linking.changeLink(threadRef, resolved.link.url, true), ); + submittingRef.current = false; setPending(false); if (result._tag === "Failure") { const error = squashAtomCommandFailure(result); @@ -142,12 +146,20 @@ function LinkPullRequestDialog({ ref={inputRef} placeholder={gt("Pull request URL or #42")} value={reference} + readOnly={pending} onChange={(event) => { setDirty(true); setReference(event.target.value); }} onKeyDown={(event) => { - if (event.key !== "Enter") return; + if ( + event.key !== "Enter" || + event.repeat || + event.nativeEvent.isComposing || + event.keyCode === 229 + ) { + return; + } event.preventDefault(); void submit(); }} From 781d63651eea32f99244d2ac1265e2921dc81d71 Mon Sep 17 00:00:00 2001 From: Alex Date: Tue, 24 Nov 2026 18:23:24 -0800 Subject: [PATCH 024/880] feat(web): hide and restore the sidebar by dragging (#29546) Co-authored-by: maria-rcks Co-authored-by: Yash Singh (cherry picked from commit 801b32f3a6f02ee1c27bf1753c73c61157ae8a03) --- apps/web/src/components/AppSidebarLayout.tsx | 1 + apps/web/src/components/ChatView.tsx | 6 + .../chat/MessagesTimeline.logic.test.ts | 17 ++ .../components/chat/MessagesTimeline.logic.ts | 26 +- .../src/components/chat/MessagesTimeline.tsx | 13 +- .../src/components/chat/TimelineMinimap.tsx | 9 +- .../components/ui/sidebar.browser.test.tsx | 140 ++++++++++ apps/web/src/components/ui/sidebar.tsx | 244 +++++++++++++----- apps/web/src/hooks/useResizeDrag.ts | 15 +- apps/web/src/i18n/translations/de.json | 1 + apps/web/src/i18n/translations/en.json | 1 + apps/web/src/i18n/translations/es.json | 1 + apps/web/src/i18n/translations/fr.json | 1 + apps/web/src/i18n/translations/ja.json | 1 + apps/web/src/i18n/translations/ko.json | 1 + apps/web/src/i18n/translations/pt-BR.json | 1 + apps/web/src/i18n/translations/ru.json | 1 + apps/web/src/i18n/translations/sv.json | 1 + apps/web/src/i18n/translations/zh.json | 1 + apps/web/src/workspaceTitlebar.ts | 3 +- docs/user/thread-sidebar.md | 10 + 21 files changed, 404 insertions(+), 90 deletions(-) diff --git a/apps/web/src/components/AppSidebarLayout.tsx b/apps/web/src/components/AppSidebarLayout.tsx index c7515485662ac..5d0383915f8c0 100644 --- a/apps/web/src/components/AppSidebarLayout.tsx +++ b/apps/web/src/components/AppSidebarLayout.tsx @@ -484,6 +484,7 @@ export function AppSidebarLayout({ role="navigation" aria-label={gt("Threads")} resizable={{ + collapseOnResize: true, maxWidth: sidebarMaximumWidth, minWidth: sidebarMinimumWidth, shouldAcceptWidth: ({ currentWidth, nextWidth, wrapper }) => diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index bf5c4892620fe..192367734e21e 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -131,6 +131,7 @@ import { resolveThreadReferenceCopyTarget } from "@t3tools/client-runtime/thread import { resolveTerminalSessionLabel } from "@t3tools/shared/terminalLabelsCopy"; import { useAtomValue } from "@effect/atom-react"; import { + type CSSProperties, type MouseEvent as ReactMouseEvent, type SetStateAction, use, @@ -3506,6 +3507,11 @@ export default function ChatView(props: ChatViewProps) { )} data-chat-column-maximized-away={rightPanelMaximized ? "true" : "false"} data-chat-column + style={ + { + "--chat-header-height": embedded ? "0px" : "var(--workspace-topbar-height)", + } as CSSProperties + } inert={rightPanelMaximized} onMouseUp={preventMiddleClickPasteOutsideEditable} > diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts index 7779a66a1fd08..1cd25f647c40e 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts @@ -34,12 +34,29 @@ import { deriveMessagesTimelineRowsWithState, isTimelineMinimapTurnVisible, resolveAssistantMessageCopyState, + resolveTimelineMinimapHitStrip, type MessagesTimelineRow, workEntryDisplayLabel, workEntryReadOutput, } from "./MessagesTimeline.logic"; import { workEntryIconName } from "./TimelineWorkEntryRow.logic"; +describe("resolveTimelineMinimapHitStrip", () => { + it.each([ + { viewport: 1280, content: 768, left: 32, width: 40 }, + { viewport: 768, content: 672, left: 32, width: 16 }, + { viewport: 768, content: 704, left: 0, width: 8 }, + { viewport: 768, content: 720, left: 0, width: 8 }, + { viewport: 768, content: 756, left: 0, width: 6 }, + { viewport: 768, content: 768, left: 0, width: 0 }, + ])( + "keeps the minimap inside the gutter at $viewport/$content", + ({ viewport, content, left, width }) => { + expect(resolveTimelineMinimapHitStrip(viewport, content)).toEqual({ left, width }); + }, + ); +}); + describe("resolveAssistantMessageCopyState", () => { it("copies the rendered representation of Codex directives", () => { expect( diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.ts b/apps/web/src/components/chat/MessagesTimeline.logic.ts index d100e34e4f0cc..99b2032aeed5e 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.ts @@ -480,25 +480,25 @@ export function resolveTimelineMinimapHasPersistentGutter( ); } -const TIMELINE_MINIMAP_HIT_STRIP_LEFT = 12; +const TIMELINE_MINIMAP_HIT_STRIP_LEFT = 32; const TIMELINE_MINIMAP_HIT_STRIP_MAX_WIDTH = 40; +const TIMELINE_MINIMAP_NAVIGATION_REACH = 14; -export function resolveTimelineMinimapHitStripWidth( - viewportWidth: number, - contentWidth: number, -): number { - const sideGutter = resolveTimelineSideGutter(viewportWidth, contentWidth); - return Math.max( - 0, - Math.min( +export function resolveTimelineMinimapHitStrip(viewportWidth: number, contentWidth: number) { + const sideGutter = Math.floor(resolveTimelineSideGutter(viewportWidth, contentWidth)); + if (sideGutter < TIMELINE_MINIMAP_HIT_STRIP_LEFT + TIMELINE_MINIMAP_NAVIGATION_REACH) { + // Keep a hover target in the gutter, to the left of the sidebar restore handle. + return { left: 0, width: Math.min(8, sideGutter) }; + } + return { + left: TIMELINE_MINIMAP_HIT_STRIP_LEFT, + width: Math.min( TIMELINE_MINIMAP_HIT_STRIP_MAX_WIDTH, - Math.floor(sideGutter) - TIMELINE_MINIMAP_HIT_STRIP_LEFT, + sideGutter - TIMELINE_MINIMAP_HIT_STRIP_LEFT, ), - ); + }; } -const TIMELINE_MINIMAP_NAVIGATION_REACH = 14; - export function resolveTimelineMinimapNavigationInteractive(collapsedWidth: number): boolean { return collapsedWidth >= TIMELINE_MINIMAP_NAVIGATION_REACH; } diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx index 589f3d09815fc..1bd08298ec505 100644 --- a/apps/web/src/components/chat/MessagesTimeline.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.tsx @@ -88,7 +88,7 @@ import { resolveTimelineMinimapCurrentIndex, isTimelineMinimapTurnVisible, resolveTimelineMinimapVisibleRange, - resolveTimelineMinimapHitStripWidth, + resolveTimelineMinimapHitStrip, TIMELINE_MINIMAP_TARGET_OFFSET, timelineTurnFoldRunIdsByEntryId, liveAnswerPreview, @@ -909,7 +909,7 @@ const ConversationTimeline = memo(function ConversationTimeline({ ...(alwaysRenderIndices.length === 0 ? {} : { indices: alwaysRenderIndices }), ...(alwaysRenderKeys.length === 0 ? {} : { keys: alwaysRenderKeys }), }; - const [minimapHitStripWidth, setMinimapHitStripWidth] = useState(0); + const [minimapHitStrip, setMinimapHitStrip] = useState({ left: 0, width: 0 }); const [minimapCurrentIndex, setMinimapCurrentIndex] = useState(null); const [minimapAtEnd, setMinimapAtEnd] = useState(false); const handleAnchorReady = (info: { anchorIndex: number | undefined }) => { @@ -1078,7 +1078,12 @@ const ConversationTimeline = memo(function ConversationTimeline({ setMinimapHasPersistentGutter((current) => current === nextHasPersistentGutter ? current : nextHasPersistentGutter, ); - setMinimapHitStripWidth(resolveTimelineMinimapHitStripWidth(viewportWidth, contentWidth)); + const nextHitStrip = resolveTimelineMinimapHitStrip(viewportWidth, contentWidth); + setMinimapHitStrip((current) => + current.left === nextHitStrip.left && current.width === nextHitStrip.width + ? current + : nextHitStrip, + ); }; // Rows added, removed or rewrapped (chat width) change the content size, // which moves the scroll position, the overflow, and the content lane width. @@ -1540,7 +1545,7 @@ const ConversationTimeline = memo(function ConversationTimeline({ void): () => void { export function TimelineMinimap({ hasPersistentGutter, - hitStripWidth, + hitStrip: { left: hitStripLeft, width: hitStripWidth }, currentIndex, atEnd, items, @@ -41,7 +41,7 @@ export function TimelineMinimap({ onSelect, }: { hasPersistentGutter: boolean; - hitStripWidth: number; + hitStrip: { left: number; width: number }; currentIndex: number | null; atEnd: boolean; items: ReadonlyArray; @@ -107,7 +107,7 @@ export function TimelineMinimap({ return (
0 && !passThrough ? "pointer-events-auto" : "pointer-events-none", )} onMouseDown={() => { @@ -136,6 +136,7 @@ export function TimelineMinimap({ }} style={{ height: resolveTimelineMinimapHeightStyle(items.length), + left: hitStripLeft, width: hitStripWidth, }} > diff --git a/apps/web/src/components/ui/sidebar.browser.test.tsx b/apps/web/src/components/ui/sidebar.browser.test.tsx index 9e1d1ba3282af..29e75617f7e01 100644 --- a/apps/web/src/components/ui/sidebar.browser.test.tsx +++ b/apps/web/src/components/ui/sidebar.browser.test.tsx @@ -21,6 +21,7 @@ function Harness(props: { readonly onResize?: (width: number) => void }) { { expect(onResize).toHaveBeenCalledTimes(1); }); + it("commits drag hiding and edge restoration only on release, with reversal before release", async () => { + await page.viewport(1280, 800); + const onResize = vi.fn(); + await using screen = await render(, { + router: false /* no routes involved */, + }); + const sidebar = screen.container.querySelector('[data-slot="sidebar"]')!; + const wrapper = sidebar.closest('[data-slot="sidebar-wrapper"]')!; + wrapper.dataset.panelAnimations = "true"; + wrapper.style.setProperty("--panel-animation-duration", "1s"); + const container = sidebar.querySelector('[data-slot="sidebar-container"]')!; + const rail = sidebar.querySelector('[data-sidebar="rail"]')!; + const pointer = { + bubbles: true, + cancelable: true, + pointerId: 1, + button: 0, + pointerType: "mouse", + }; + const dispatch = (target: HTMLElement, type: string, clientX: number) => + target.dispatchEvent(new PointerEvent(type, { ...pointer, clientX })); + dispatch(rail, "pointerdown", 255); + dispatch(rail, "pointermove", 50); + await vi.waitFor(() => + expect( + sidebar.querySelector('[data-slot="sidebar-container"]')!.getBoundingClientRect().width, + ).toBe(200), + ); + expect( + sidebar.querySelector('[data-slot="sidebar-container"]')!.getBoundingClientRect().left, + ).toBe(0); + dispatch(rail, "pointermove", 48); + await vi.waitFor(() => + expect( + sidebar.querySelector('[data-slot="sidebar-container"]')!.getBoundingClientRect().right, + ).toBe(0), + ); + expect(sidebar.dataset.state).toBe("expanded"); + expect(onResize).not.toHaveBeenCalled(); + dispatch(rail, "pointermove", 280); + await vi.waitFor(() => + expect( + sidebar.querySelector('[data-slot="sidebar-container"]')!.getBoundingClientRect().left, + ).toBe(0), + ); + dispatch(rail, "pointerup", 280); + expect(onResize).toHaveBeenLastCalledWith(281); + expect(sidebar.dataset.state).toBe("expanded"); + dispatch(rail, "pointerdown", 280); + dispatch(rail, "pointermove", 0); + await vi.waitFor(() => expect(container.getBoundingClientRect().right).toBe(0)); + dispatch(rail, "pointerup", 0); + await vi.waitFor(() => expect(sidebar.dataset.state).toBe("collapsed")); + expect(container.getBoundingClientRect().right).toBe(0); + expect(onResize).toHaveBeenLastCalledWith(200); + expect(sidebar.inert).toBe(true); + const handle = screen.container.querySelector( + '[data-slot="sidebar-restore-handle"]', + )!; + const edge = screen.container.querySelector('[data-slot="sidebar-restore-edge"]')!; + await userEvent.hover(edge); + const bounds = edge.getBoundingClientRect(); + const startX = bounds.right - 1; + const endX = startX + 258; + const y = bounds.top + bounds.height / 2; + expect(handle.contains(document.elementFromPoint(startX, y))).toBe(true); + expect(edge.contains(document.elementFromPoint(2, y))).toBe(false); + dispatch(handle, "pointerdown", startX); + dispatch(handle, "pointermove", endX); + await vi.waitFor(() => + expect( + sidebar.querySelector('[data-slot="sidebar-gap"]')!.getBoundingClientRect().width, + ).toBe(258), + ); + expect(sidebar.dataset.state).toBe("collapsed"); + expect( + sidebar.querySelector('[data-slot="sidebar-container"]')!.getBoundingClientRect().left, + ).toBe(0); + dispatch(handle, "pointermove", startX); + await vi.waitFor(() => + expect( + sidebar.querySelector('[data-slot="sidebar-container"]')!.getBoundingClientRect().right, + ).toBe(0), + ); + expect(sidebar.querySelector('[data-slot="sidebar-gap"]')!.getBoundingClientRect().width).toBe( + 0, + ); + dispatch(handle, "pointerup", startX); + expect(sidebar.dataset.state).toBe("collapsed"); + expect(onResize).toHaveBeenCalledTimes(2); + dispatch(handle, "pointerdown", startX); + dispatch(handle, "pointermove", endX); + await vi.waitFor(() => + expect( + sidebar.querySelector('[data-slot="sidebar-container"]')!.getBoundingClientRect().left, + ).toBe(0), + ); + dispatch(handle, "pointerup", endX); + await vi.waitFor(() => expect(sidebar.dataset.state).toBe("expanded")); + expect(container.getBoundingClientRect().left).toBe(0); + expect(onResize).toHaveBeenLastCalledWith(258); + expect(sidebar.inert).toBe(false); + }); + + it.each(["pointercancel", "lostpointercapture", "blur"])( + "abandons hide intent on %s", + async (eventType) => { + await page.viewport(1280, 800); + const onResize = vi.fn(); + await using screen = await render(, { + router: false /* no routes involved */, + }); + const rail = screen.container.querySelector('[data-sidebar="rail"]')!; + const sidebar = screen.container.querySelector('[data-slot="sidebar"]')!; + const pointer = { + bubbles: true, + cancelable: true, + pointerId: 1, + button: 0, + pointerType: "mouse", + clientX: 255, + }; + rail.dispatchEvent(new PointerEvent("pointerdown", pointer)); + rail.dispatchEvent(new PointerEvent("pointermove", { ...pointer, clientX: 0 })); + await vi.waitFor(() => + expect( + sidebar.querySelector('[data-slot="sidebar-container"]')!.getBoundingClientRect().right, + ).toBe(0), + ); + if (eventType === "blur") window.dispatchEvent(new Event("blur")); + else rail.dispatchEvent(new PointerEvent(eventType, { ...pointer, clientX: 0 })); + rail.dispatchEvent(new PointerEvent("pointerup", { ...pointer, clientX: 0 })); + expect(sidebar.dataset.state).toBe("expanded"); + expect(onResize).not.toHaveBeenCalled(); + expect( + sidebar.querySelector('[data-slot="sidebar-container"]')!.getBoundingClientRect().left, + ).toBe(0); + }, + ); }); it("restores collapsed and expanded desktop state after remounting", async () => { diff --git a/apps/web/src/components/ui/sidebar.tsx b/apps/web/src/components/ui/sidebar.tsx index b7dd79e9b97c4..963d74a7d03cd 100644 --- a/apps/web/src/components/ui/sidebar.tsx +++ b/apps/web/src/components/ui/sidebar.tsx @@ -32,6 +32,7 @@ const SIDEBAR_WIDTH = "16rem"; const SIDEBAR_WIDTH_MOBILE = "calc(100vw - var(--spacing) * 3)"; const SIDEBAR_WIDTH_ICON = "3rem"; const SIDEBAR_RESIZE_DEFAULT_MIN_WIDTH = 16 * 16; +const SIDEBAR_COLLAPSE_DRAG_RATIO = 0.75; const SIDEBAR_TITLEBAR_CONTROL_SIZE = "max-sm:[--workspace-titlebar-control-size:--spacing(8)]"; type SidebarContextProps = { @@ -49,6 +50,7 @@ type SidebarContextProps = { }; type SidebarResizableOptions = { + collapseOnResize?: boolean; maxWidth?: number; minWidth?: number; onResize?: (width: number) => void; @@ -64,6 +66,7 @@ type SidebarResizableOptions = { }; type SidebarResolvedResizableOptions = { + collapseOnResize: boolean; maxWidth: number; minWidth: number; onResize?: (width: number) => void; @@ -271,6 +274,7 @@ function resolveSidebarResizable({ const options = typeof resizable === "boolean" ? {} : resizable; return { + collapseOnResize: options.collapseOnResize ?? false, maxWidth: options.maxWidth ?? Number.POSITIVE_INFINITY, minWidth: options.minWidth ?? SIDEBAR_RESIZE_DEFAULT_MIN_WIDTH, storageKey: options.storageKey ?? null, @@ -422,6 +426,9 @@ function Sidebar({
+ {offcanvasCollapsed && side === "left" && resolvedResizable?.collapseOnResize && ( + + )} ); } @@ -459,6 +466,110 @@ function clampSidebarWidth(width: number, options: SidebarResolvedResizableOptio return Math.max(options.minWidth, Math.min(width, options.maxWidth)); } +function commitSidebarWidth( + wrapper: HTMLElement, + options: SidebarResolvedResizableOptions, + width: number, +) { + wrapper.style.setProperty("--sidebar-width", `${width}px`); + if (options.storageKey) { + try { + setLocalStorageItem(options.storageKey, width, Schema.Finite); + } catch (error) { + console.error("Could not persist sidebar width.", error); + } + } + options.onResize?.(width); +} + +function SidebarRestoreHandle({ options }: { options: SidebarResolvedResizableOptions }) { + const { setOpen } = useSidebar(); + const gt = useGT(); + const [near, setNear] = React.useState(false); + const suppressClick = React.useRef(false); + const resize = useResizeDrag((event) => { + if (event.pointerType !== "mouse") return null; + const wrapper = event.currentTarget.closest('[data-slot="sidebar-wrapper"]'); + const sidebar = wrapper?.querySelector('[data-slot="sidebar"][data-side="left"]'); + const container = sidebar?.querySelector('[data-slot="sidebar-container"]'); + const gap = sidebar?.querySelector('[data-slot="sidebar-gap"]'); + if (!wrapper || !container || !gap) return null; + let restorePending = false; + wrapper.dataset.sidebarDragState = "collapsed"; + return { + width: 0, + edge: "right", + bounds: { min: 0, max: options.maxWidth }, + cancelOnInterrupt: true, + resize(nextWidth) { + const shouldRestore = nextWidth >= 48; + if (shouldRestore !== restorePending) { + restorePending = shouldRestore; + wrapper.dataset.sidebarDragState = restorePending ? "expanded" : "collapsed"; + } + const width = clampSidebarWidth(nextWidth, options); + container.style.left = restorePending ? "0px" : `${-width}px`; + for (const element of [container, gap]) { + element.style.width = `${restorePending || element === container ? width : 0}px`; + element.style.transitionDuration = "0ms"; + } + return width; + }, + finish(width, moved) { + suppressClick.current = moved; + if (moved && restorePending) { + commitSidebarWidth(wrapper, options, width); + setOpen(true); + } + }, + cleanup() { + delete wrapper.dataset.sidebarDragState; + container.style.removeProperty("left"); + for (const element of [container, gap]) { + element.style.removeProperty("width"); + element.style.removeProperty("transition-duration"); + } + }, + }; + }); + const { ref: handleRef, ...drag } = resize; + return ( +
{ + if (event.pointerType === "mouse") setNear(true); + }} + onPointerLeave={() => setNear(false)} + > +
+ ); +} + function SidebarRail({ className, onClick, @@ -469,7 +580,7 @@ function SidebarRail({ onPointerUp, ...props }: React.ComponentProps<"button">) { - const { open, toggleSidebar, onCollapse } = useSidebar(); + const { open, setOpen, toggleSidebar, onCollapse } = useSidebar(); const gt = useGT(); const sidebarInstance = React.use(SidebarInstanceContext); const suppressClickRef = React.useRef(false); @@ -489,6 +600,9 @@ function SidebarRail({ if (!wrapper || !sidebarRoot || !sidebarContainer) return null; const side = sidebarInstance?.side ?? "left"; + const canCollapse = open && side === "left" && options.collapseOnResize; + let collapsePending = false; + if (canCollapse) wrapper.dataset.sidebarDragState = "expanded"; let width = clampSidebarWidth(sidebarContainer.getBoundingClientRect().width, options); // Write width only to gap/container during drag; inherited --sidebar-width restyles the whole app, so // update it at commit. @@ -498,8 +612,13 @@ function SidebarRail({ ].filter((element): element is HTMLElement => element !== null); const setTargetWidth = (value: number) => { widthTargets.forEach((element) => { - element.style.setProperty("width", `${value}px`); + element.style.setProperty( + "width", + `${collapsePending && element !== sidebarContainer ? 0 : value}px`, + ); }); + // Match the offcanvas left offset so releasing a drag cannot restart the slide. + if (canCollapse) sidebarContainer.style.left = collapsePending ? `${-value}px` : "0px"; }; widthTargets.forEach((element) => { element.style.setProperty("transition-duration", "0ms"); @@ -510,7 +629,14 @@ function SidebarRail({ width, edge: side === "left" ? "right" : "left", bounds: { min: options.minWidth, max: options.maxWidth }, - resize(nextWidth) { + cancelOnInterrupt: canCollapse, + resize(nextWidth, rawWidth) { + const shouldCollapse = + canCollapse && rawWidth < options.minWidth * (1 - SIDEBAR_COLLAPSE_DRAG_RATIO); + if (shouldCollapse !== collapsePending) { + collapsePending = shouldCollapse; + wrapper.dataset.sidebarDragState = collapsePending ? "collapsed" : "expanded"; + } const accepted = options.shouldAcceptWidth?.({ currentWidth: width, @@ -521,24 +647,21 @@ function SidebarRail({ wrapper, }) ?? true; if (accepted) { - setTargetWidth(nextWidth); width = nextWidth; } + setTargetWidth(width); return width; }, finish(finalWidth, moved) { - wrapper.style.setProperty("--sidebar-width", `${finalWidth}px`); suppressClickRef.current = moved; - if (options.storageKey) { - try { - setLocalStorageItem(options.storageKey, finalWidth, Schema.Finite); - } catch (error) { - console.error("Could not persist sidebar width.", error); - } - } - options.onResize?.(finalWidth); + commitSidebarWidth(wrapper, options, finalWidth); + if (moved && collapsePending) setOpen(false); }, cleanup() { + if (canCollapse) { + delete wrapper.dataset.sidebarDragState; + sidebarContainer.style.removeProperty("left"); + } widthTargets.forEach((element) => { element.style.removeProperty("width"); element.style.removeProperty("transition-duration"); @@ -576,55 +699,56 @@ function SidebarRail({ toggleSidebar(); }; + const rail = ( +
", @@ -177,32 +204,9 @@ it("keeps only the well-typed fields of what the page reports about an element", stack: [{ functionName: "Checkout", fileName: ["x"], lineNumber: "12", columnNumber: 4 }, 3], }); const card = document.body.appendChild(document.createElement("div")); - document.elementsFromPoint = () => [card]; - using listeners = vi.spyOn(HTMLButtonElement.prototype, "addEventListener"); - const shadowRoot = startAnnotation(); - card.dispatchEvent( - new PointerEvent("pointerdown", { button: 0, clientX: 100, clientY: 100, bubbles: true }), - ); - const attach = Array.from(shadowRoot.querySelectorAll("button")).find( - (button) => button.textContent === "Attach", - ); - const listenerIndex = listeners.mock.contexts.findIndex( - (target, index) => target === attach && listeners.mock.calls[index]?.[0] === "click", - ); - const listener = listeners.mock.calls[listenerIndex]?.[1]; - if (!attach || typeof listener !== "function") throw new Error("Attach listener not found"); - // The DOM test environment has no native input source. - listener.call(attach, { isTrusted: true } as MouseEvent); - - await vi.waitFor(() => - expect(ipcSend.calls.some(([channel]) => channel === ELEMENT_PICKED_CHANNEL)).toBe(true), - ); - const [, annotation] = - ipcSend.calls.find(([channel]) => channel === ELEMENT_PICKED_CHANNEL) ?? []; + const element = await pickAndAttach(card); const frame = { functionName: "Checkout", fileName: null, lineNumber: null, columnNumber: 4 }; - expect( - (annotation as { elements: Array<{ element: unknown }> }).elements[0]?.element, - ).toMatchObject({ + expect(element).toMatchObject({ selector: null, htmlPreview: "", componentName: null, @@ -211,3 +215,11 @@ it("keeps only the well-typed fields of what the page reports about an element", stack: [frame, { functionName: null, fileName: null, lineNumber: null, columnNumber: null }], }); }); + +it("drops a straddling surrogate pair when falling back to outerHTML preview", async () => { + pageElementContext.mockRejectedValueOnce(new Error("page lookup failed")); + const card = document.body.appendChild(document.createElement("div")); + card.textContent = `${"a".repeat(494)}🚀tail`; + expect(card.outerHTML.charCodeAt(499)).toBe(0xd83d); + expect((await pickAndAttach(card))?.htmlPreview).toBe(card.outerHTML.slice(0, 499)); +}); diff --git a/apps/desktop/src/preview/PickPreload.ts b/apps/desktop/src/preview/PickPreload.ts index a227d5136b6c6..61e3c8070d722 100644 --- a/apps/desktop/src/preview/PickPreload.ts +++ b/apps/desktop/src/preview/PickPreload.ts @@ -494,10 +494,14 @@ async function captureElement(element: Element): Promise { }; } } catch {} + const html = element.outerHTML; + const before = html.charCodeAt(HTML_PREVIEW_MAX_CHARS - 1); + const after = html.charCodeAt(HTML_PREVIEW_MAX_CHARS); + const splitPair = before >= 0xd800 && before <= 0xdbff && after >= 0xdc00 && after <= 0xdfff; return { ...base, selector: null, - htmlPreview: element.outerHTML.slice(0, HTML_PREVIEW_MAX_CHARS), + htmlPreview: html.slice(0, splitPair ? HTML_PREVIEW_MAX_CHARS - 1 : HTML_PREVIEW_MAX_CHARS), componentName: null, source: null, stack: [], From 63b9724f5e580a9977735929f8d68197373145ee Mon Sep 17 00:00:00 2001 From: Victor Date: Wed, 25 Nov 2026 03:48:40 -0600 Subject: [PATCH 068/880] fix(web): xlsx previews no longer fail on cells truncated mid-emoji (#42718) Co-authored-by: Julius Marminge (cherry picked from commit b125918f4b4147f45749e97872b93b5676f031e4) --- .../components/files/officeArchive.test.ts | 24 ++++++++++++++++++- .../web/src/components/files/officeArchive.ts | 6 ++++- 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/apps/web/src/components/files/officeArchive.test.ts b/apps/web/src/components/files/officeArchive.test.ts index fd8718e21fdcf..a1d7912265a8e 100644 --- a/apps/web/src/components/files/officeArchive.test.ts +++ b/apps/web/src/components/files/officeArchive.test.ts @@ -170,6 +170,7 @@ async function workbookFile( sheetPath: string, extraRels = "", targetMode = "Internal", + sheetData = `42`, ) { const zip = new JSZip(); zip.file( @@ -190,7 +191,7 @@ async function workbookFile( ); zip.file( sheetPath, - `42`, + `${sheetData}`, ); return zip.generateAsync({ type: "arraybuffer" }); } @@ -232,3 +233,24 @@ describe("Workbook relationship targets", () => { expect(await zip.file("xl/worksheets/sheet1.xml")?.async("string")).toContain("42"); }); }); + +describe("Workbook preview limits", () => { + it("does not split a surrogate pair when truncating cell text", async () => { + const prefix = "a".repeat(4095); + const result = await prepareOffice( + await workbookFile( + "worksheets/sheet1.xml", + "xl/worksheets/sheet1.xml", + "", + "Internal", + `${prefix}🚀tail`, + ), + "xlsx", + ); + const zip = await JSZip.loadAsync(result.bytes); + const sheet = await zip.file("xl/worksheets/sheet1.xml")?.async("string"); + expect(result.truncated).toBe(true); + expect(sheet).toContain(`${prefix}`); + expect(sheet).not.toContain("\ufffd"); + }); +}); diff --git a/apps/web/src/components/files/officeArchive.ts b/apps/web/src/components/files/officeArchive.ts index 0e9b59ab8e9eb..b9b08801e5300 100644 --- a/apps/web/src/components/files/officeArchive.ts +++ b/apps/web/src/components/files/officeArchive.ts @@ -411,7 +411,11 @@ function boundedWorksheet( const end = cell.selfClosing ? cell.start : xml.lastIndexOf("<", parser.position - 1); const raw = cell.opening + xml.slice(cell.start, end) + ``; const shown = cell.shared ? (strings[Number(cell.value)] ?? "") : cell.text || cell.value; - const kept = shown.slice(0, Math.min(4096, budget.remaining)); + let limit = Math.min(4096, budget.remaining); + const before = shown.charCodeAt(limit - 1); + const after = shown.charCodeAt(limit); + if (before >= 0xd800 && before <= 0xdbff && after >= 0xdc00 && after <= 0xdfff) limit--; + const kept = shown.slice(0, limit); budget.remaining -= kept.length; if (kept.length < shown.length) { truncated = true; From 4033b25404aeda2f89b10d7b563f98d9e48b5034 Mon Sep 17 00:00:00 2001 From: Alex Hatzenbuhler Date: Wed, 25 Nov 2026 03:52:29 -0600 Subject: [PATCH 069/880] fix(server): report stopped and disabled launch agents in macOS service status (#42715) Co-authored-by: Julius Marminge (cherry picked from commit 341864854bea1dc891805d64915ffdeb6d4011e2) --- apps/server/src/cloud/bootService.test.ts | 47 ++++++++++++++++++----- apps/server/src/cloud/bootService.ts | 28 ++++++++++++-- 2 files changed, 61 insertions(+), 14 deletions(-) diff --git a/apps/server/src/cloud/bootService.test.ts b/apps/server/src/cloud/bootService.test.ts index 535e2cfed313f..d8ad4f281933b 100644 --- a/apps/server/src/cloud/bootService.test.ts +++ b/apps/server/src/cloud/bootService.test.ts @@ -276,7 +276,13 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* ( control.linger = "yes"; control.managerReachable ||= control.lingerStartsManager; } - if (!failed && command === "systemctl --user enable t3code.service") control.enabled = true; + if ( + !failed && + (command === "systemctl --user enable t3code.service" || + command.startsWith("launchctl enable ")) + ) { + control.enabled = true; + } const taskMissing = input.command === SCHTASKS && input.args[0] !== "/Create" && control.task === undefined; if (input.command === SCHTASKS && !failed) { @@ -290,14 +296,25 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* ( if (input.args[0] === "/Delete") delete control.task; if (input.args[0] === "/End") control.launcher?.close(); } - if (!refusedStart && !failed && command.startsWith("systemctl --user restart ")) + if ( + !refusedStart && + !failed && + (command.startsWith("systemctl --user restart ") || + command.startsWith("launchctl bootstrap ")) + ) { control.active = true; + } // The manager loads units only from its own unit directory. const unitOutsideManager = command === "systemctl --user enable t3code.service" && !(yield* fs.exists(path.join(managerUnitDir, "t3code.service"))); // A timed-out stop may still stop the service. - if (command === "systemctl --user stop t3code.service") control.active = false; + if ( + command === "systemctl --user stop t3code.service" || + command.startsWith("launchctl bootout --wait ") + ) { + control.active = false; + } if ( control.stateAfterStop !== undefined && (command === "systemctl --user stop t3code.service" || @@ -326,11 +343,13 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* ( : (control.task?.xml ?? "") : input.command === "loginctl" && input.args[0] === "show-user" ? `${control.linger ?? ""}\n` - : input.args[1] === "is-enabled" - ? control.enabled - ? "enabled\n" - : "disabled\n" - : "", + : input.command === "launchctl" && input.args[0] === "print-disabled" + ? `disabled services = {\n\t"${BootService.BOOT_SERVICE_LAUNCHD_LABEL}" => ${control.enabled ? "enabled" : "disabled"}\n}\n` + : input.args[1] === "is-enabled" + ? control.enabled + ? "enabled\n" + : "disabled\n" + : "", stderr: "", code: ChildProcessSpawner.ExitCode( taskMissing && input.args.includes("/HRESULT") @@ -345,6 +364,7 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* ( input.args[0] === "show-user" && control.linger === undefined) || (input.args[1] === "is-active" && !control.active) || + (input.command === "launchctl" && input.args[0] === "print" && !control.active) || (input.args[1] === "is-enabled" && !control.enabled) ? 1 : 0, @@ -1524,7 +1544,7 @@ process.disconnect(); it.effect("installs, reports current state, and uninstalls on macOS", () => Effect.gen(function* () { - const { service, fs, statePath, commands, timeouts, runtime, markersAtStop } = + const { service, fs, statePath, commands, timeouts, runtime, markersAtStop, control } = yield* makeHarness("darwin"); const path = yield* Path.Path; const plan = yield* service.install(); @@ -1547,6 +1567,13 @@ process.disconnect(); expect(yield* service.status).toMatchObject({ current: true, installedVersion: "1.2.3", + problems: [], + }); + control.active = false; + control.enabled = false; + expect(yield* service.status).toMatchObject({ + current: false, + problems: ["service-disabled", "service-stopped"], }); const relayMarker = path.join(plan.baseDir, "runtime", DESKTOP_UPDATE_RESTART_MARKER_FILE); expect(yield* service.restart).toBe("restarted"); @@ -1802,7 +1829,7 @@ process.disconnect(); expect((yield* service.install().pipe(Effect.flip))._tag).toBe("BootServiceCommandError"); expect(yield* service.status).toMatchObject({ current: false, - problems: ["restart-pending"], + problems: ["service-stopped", "restart-pending"], }); expect(yield* fs.readFileString(markerPath)).toBe("1.2.3\n"); diff --git a/apps/server/src/cloud/bootService.ts b/apps/server/src/cloud/bootService.ts index 6937d5887a6a9..a2ce79b938528 100644 --- a/apps/server/src/cloud/bootService.ts +++ b/apps/server/src/cloud/bootService.ts @@ -1129,6 +1129,28 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { runner.run({ command, args, timeout: Duration.seconds(5) }).pipe(Effect.option); const succeeded = (result: Option.Option) => Option.isSome(result) && result.value.code === 0; + const launchdJobLoaded = probe("launchctl", [ + "print", + `gui/${uid}/${BOOT_SERVICE_LAUNCHD_LABEL}`, + ]).pipe(Effect.map(succeeded)); + const readLaunchdProblems = Effect.fn("cloud.boot_service.read_launchd_problems")(function* () { + const [loaded, disabled] = yield* Effect.all( + [launchdJobLoaded, probe("launchctl", ["print-disabled", `gui/${uid}`])], + { concurrency: "unbounded" }, + ); + const problems: BootServiceProblem[] = []; + if ( + Option.isSome(disabled) && + disabled.value.code === 0 && + // Older macOS versions print `true` instead of `disabled`. + (disabled.value.stdout.includes(`"${BOOT_SERVICE_LAUNCHD_LABEL}" => disabled`) || + disabled.value.stdout.includes(`"${BOOT_SERVICE_LAUNCHD_LABEL}" => true`)) + ) { + problems.push("service-disabled"); + } + if (!loaded) problems.push("service-stopped"); + return problems; + }); const lingerArgs = [ "show-user", ...(uid === undefined ? [] : [String(uid)]), @@ -1554,9 +1576,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { (problems) => !problems.includes("service-disabled") || !problems.includes("service-stopped"), ) - : succeeded( - yield* probe("launchctl", ["print", `gui/${uid}/${BOOT_SERVICE_LAUNCHD_LABEL}`]), - ); + : yield* launchdJobLoaded; return yield* Effect.acquireUseRelease( // Require every stop before repair when restoring, so the server releases the database. // Otherwise stops are best-effort; launchd rejects bootout of an unloaded job. @@ -1624,7 +1644,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { ? [...(yield* readSystemdProblems(true))] : manager.kind === "schtasks" ? [...(yield* readSchtasksProblems(Option.some(unit)))] - : []; + : [...(yield* readLaunchdProblems())]; if (yield* fs.exists(restartPendingPath)) problems.push("restart-pending"); return { supported: true, From 1ac544892a820e2c059b106eaa743380bc4bae58 Mon Sep 17 00:00:00 2001 From: AymanKhan9 Date: Wed, 25 Nov 2026 15:38:19 +0530 Subject: [PATCH 070/880] fix(web): hide the right panel add-surface menu when no surfaces are available (#42722) Co-authored-by: Julius Marminge (cherry picked from commit b042e4ee757947ca1cd47bb217c94296f9c695cf) --- .../RightPanelTabs.browser.test.tsx | 62 ++++++++++++++- apps/web/src/components/RightPanelTabs.tsx | 75 ++++++++++--------- 2 files changed, 98 insertions(+), 39 deletions(-) diff --git a/apps/web/src/components/RightPanelTabs.browser.test.tsx b/apps/web/src/components/RightPanelTabs.browser.test.tsx index 347971993c7c3..4306d6bc1a219 100644 --- a/apps/web/src/components/RightPanelTabs.browser.test.tsx +++ b/apps/web/src/components/RightPanelTabs.browser.test.tsx @@ -1,12 +1,13 @@ import "~/index.css"; import { EnvironmentId } from "@t3tools/contracts"; +import { DEFAULT_RESOLVED_KEYBINDINGS } from "@t3tools/shared/keybindings"; import { describe, expect, it, vi } from "vite-plus/test"; -import { userEvent } from "vite-plus/test/browser"; +import { page, userEvent } from "vite-plus/test/browser"; import { InputGroup, InputGroupAddon, InputGroupInput } from "~/components/ui/input-group"; import type { RightPanelSurface } from "~/rightPanelStore"; -import { render, stubGlobal } from "../../test/render"; +import { act, render, stubGlobal } from "../../test/render"; import { HistorySwipeNavigation } from "./HistorySwipeNavigation"; import { RightPanelTabs, type RightPanelTabsProps } from "./RightPanelTabs"; import { subscribePreviewAction } from "./preview/previewActionBus"; @@ -292,3 +293,60 @@ describe("device tab rename", () => { expect(onRenameDevice).toHaveBeenCalledExactlyOnceWith(DEVICE_SURFACE.id, "日本語"); }); }); + +describe("add surface launcher", () => { + it("hides the button, closes the open menu and stops taking Mod+T and the desktop menu action once no surface can be added", async () => { + const menuListeners = new Set<(action: string) => void>(); + using _bridge = stubGlobal("desktopBridge", { + onMenuAction: (listener: (action: string) => void) => { + menuListeners.add(listener); + return () => menuListeners.delete(listener); + }, + }); + using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("Linux x86_64"); + const tabs = (sideChatAvailable: boolean) => ( + {}} + sideChatAvailable={sideChatAvailable} + > + {null} + + ); + const pressModT = async () => { + const event = new KeyboardEvent("keydown", { + key: "t", + ctrlKey: true, + bubbles: true, + cancelable: true, + }); + await act(() => { + document.body.dispatchEvent(event); + }); + return event.defaultPrevented; + }; + await using screen = await render(tabs(true)); + const addButton = screen.getByRole("button", { name: "Add panel surface" }); + + await expect.element(addButton).toBeInTheDocument(); + expect(menuListeners.size).toBe(1); + expect(await pressModT()).toBe(true); + await expect.element(page.getByRole("menu")).toBeVisible(); + + await screen.rerender(tabs(false)); + expect(addButton.query()).toBeNull(); + expect(page.getByRole("menu").query()).toBeNull(); + expect(menuListeners.size).toBe(0); + expect(await pressModT()).toBe(false); + expect(page.getByRole("menu").query()).toBeNull(); + }); +}); diff --git a/apps/web/src/components/RightPanelTabs.tsx b/apps/web/src/components/RightPanelTabs.tsx index 2b57b4516e454..d3d4359a4e88d 100644 --- a/apps/web/src/components/RightPanelTabs.tsx +++ b/apps/web/src/components/RightPanelTabs.tsx @@ -1139,42 +1139,6 @@ export function RightPanelTabs(props: RightPanelTabsProps) { canScrollRight: false, }); - if (props.open === false && addSurfaceMenuOpen) setAddSurfaceMenuOpen(false); - - const addSurfaceMenuBlocked = () => - !addSurfaceMenuOpen && document.querySelector(LAUNCHER_SHORTCUT_BLOCKING_LAYERS) !== null; - const onNewSurfaceKeyDown = useEffectEvent((event: KeyboardEvent) => { - if (event.defaultPrevented || event.isComposing) return; - if ( - resolveShortcutCommand(event, props.keybindings, { - context: { ...props.getShortcutContext(), rightPanelOpen: true }, - }) !== "rightPanel.new" - ) - return; - if (addSurfaceMenuBlocked()) return; - event.preventDefault(); - event.stopPropagation(); - if (!event.repeat) { - addSurfaceTriggerRef.current?.focus(); - setAddSurfaceMenuOpen(true); - } - }); - // Forwarded from a focused browser page. Focusing the trigger here would let ChatView's - // window-focus handler see a plain button and refocus the composer, closing the menu. - const onMenuAction = useEffectEvent((action: string) => { - if (action === "rightPanel.new" && !addSurfaceMenuBlocked()) setAddSurfaceMenuOpen(true); - }); - // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes document keydown and the desktop menu action (forwarded from a focused browser page) for the new surface shortcut while the panel is open - useEffect(() => { - if (props.open === false) return; - document.addEventListener("keydown", onNewSurfaceKeyDown, true); - const unsubscribe = window.desktopBridge?.onMenuAction(onMenuAction); - return () => { - document.removeEventListener("keydown", onNewSurfaceKeyDown, true); - unsubscribe?.(); - }; - }, [props.open]); - const updateTabScrollState = (viewport: HTMLDivElement) => { const hasOverflow = viewport.scrollWidth - viewport.clientWidth > TAB_SCROLL_EDGE_TOLERANCE; const canScrollLeft = hasOverflow && viewport.scrollLeft > TAB_SCROLL_EDGE_TOLERANCE; @@ -1274,6 +1238,43 @@ export function RightPanelTabs(props: RightPanelTabsProps) { ] : []), ] as const; + const canAddSurface = addSurfaceActions.some((action) => action.available); + + if ((props.open === false || !canAddSurface) && addSurfaceMenuOpen) setAddSurfaceMenuOpen(false); + + const addSurfaceMenuBlocked = () => + !addSurfaceMenuOpen && document.querySelector(LAUNCHER_SHORTCUT_BLOCKING_LAYERS) !== null; + const onNewSurfaceKeyDown = useEffectEvent((event: KeyboardEvent) => { + if (event.defaultPrevented || event.isComposing) return; + if ( + resolveShortcutCommand(event, props.keybindings, { + context: { ...props.getShortcutContext(), rightPanelOpen: true }, + }) !== "rightPanel.new" + ) + return; + if (addSurfaceMenuBlocked()) return; + event.preventDefault(); + event.stopPropagation(); + if (!event.repeat) { + addSurfaceTriggerRef.current?.focus(); + setAddSurfaceMenuOpen(true); + } + }); + // Forwarded from a focused browser page. Focusing the trigger here would let ChatView's + // window-focus handler see a plain button and refocus the composer, closing the menu. + const onMenuAction = useEffectEvent((action: string) => { + if (action === "rightPanel.new" && !addSurfaceMenuBlocked()) setAddSurfaceMenuOpen(true); + }); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes document keydown and the desktop menu action (forwarded from a focused browser page) for the new surface shortcut while the panel is open and can add a surface + useEffect(() => { + if (props.open === false || !canAddSurface) return; + document.addEventListener("keydown", onNewSurfaceKeyDown, true); + const unsubscribe = window.desktopBridge?.onMenuAction(onMenuAction); + return () => { + document.removeEventListener("keydown", onNewSurfaceKeyDown, true); + unsubscribe?.(); + }; + }, [props.open, canAddSurface]); const handleAddSurfaceMenuKeyDown = (event: ReactKeyboardEvent) => { const action = surfaceShortcutActionForKey(addSurfaceActions, event.nativeEvent); @@ -1550,7 +1551,7 @@ export function RightPanelTabs(props: RightPanelTabsProps) { ); })} - {props.open !== false ? ( + {props.open !== false && canAddSurface ? ( Date: Wed, 25 Nov 2026 04:15:30 -0600 Subject: [PATCH 071/880] fix(web): EPUB chapter titles no longer end in a broken emoji (#42725) Co-authored-by: Julius Marminge (cherry picked from commit a686952304a5474a5d24fcf498b845baadbed17b) --- apps/web/src/components/files/FilePreviewPanel.test.ts | 4 ++-- apps/web/src/components/files/extendedDocumentPreview.ts | 7 +++---- 2 files changed, 5 insertions(+), 6 deletions(-) diff --git a/apps/web/src/components/files/FilePreviewPanel.test.ts b/apps/web/src/components/files/FilePreviewPanel.test.ts index 6de12a7863475..8ec04ee1cabe4 100644 --- a/apps/web/src/components/files/FilePreviewPanel.test.ts +++ b/apps/web/src/components/files/FilePreviewPanel.test.ts @@ -694,7 +694,7 @@ Third}`; ) .file( "Book/one.xhtml", - 'First

First chapter

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

First chapter

Cover`, ) .file( "Book/two&&&.xhtml", @@ -710,7 +710,7 @@ Third}`; const result = await openEpub(archive); expect(result.type).toBe("document"); if (result.type !== "document") throw new Error("Expected document"); - expect(result.pages.map((page) => page.title)).toEqual(["Second", "First"]); + expect(result.pages.map((page) => page.title)).toEqual(["Second", "a".repeat(119)]); expect(result.pages[0]!.html).toContain("A\u00a0B © — ≂̸ &lt;"); expect(result.pages[0]!.html).toContain("
Use &amp; and &lt; literally
"); expect(result.pages[0]!.html).toContain( diff --git a/apps/web/src/components/files/extendedDocumentPreview.ts b/apps/web/src/components/files/extendedDocumentPreview.ts index db744de3cf48a..517e404f0a8c2 100644 --- a/apps/web/src/components/files/extendedDocumentPreview.ts +++ b/apps/web/src/components/files/extendedDocumentPreview.ts @@ -465,11 +465,10 @@ export async function openEpub(archive: JSZip): Promise { const entry = path ? archive.file(path) : null; if (!entry || !path) continue; const chapter = parseXml(await entry.async("string")); + const title = text(find(chapter, "title")[0] ?? find(chapter, "h1")[0] ?? chapter).trim(); + const last = title.charCodeAt(119); pages.push({ - title: - text(find(chapter, "title")[0] ?? find(chapter, "h1")[0] ?? chapter) - .trim() - .slice(0, 120) || undefined, + title: title.slice(0, last >= 0xd800 && last <= 0xdbff ? 119 : 120) || undefined, html: await epubHtml(chapter, archive, path), }); } From 12dee51ad6fcf8ec57ee5dc50e56b4c90d3c8046 Mon Sep 17 00:00:00 2001 From: Victor Date: Wed, 25 Nov 2026 04:24:02 -0600 Subject: [PATCH 072/880] fix(web): long thread titles no longer break dropped thread attachment names (#42727) Co-authored-by: Julius Marminge (cherry picked from commit 009ae578d0b6ce3d1af317b9e259e25929680941) --- apps/web/src/lib/threadContextAttachment.test.ts | 11 +++++++++++ apps/web/src/lib/threadContextAttachment.ts | 4 +++- 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/apps/web/src/lib/threadContextAttachment.test.ts b/apps/web/src/lib/threadContextAttachment.test.ts index 3d0fddd2b787f..b634c0934649f 100644 --- a/apps/web/src/lib/threadContextAttachment.test.ts +++ b/apps/web/src/lib/threadContextAttachment.test.ts @@ -84,4 +84,15 @@ describe("threadContextAttachment", () => { expect(first.name).toMatch(/^Same _ title_ notes-[a-f0-9]+\.jsonl$/); expect(first.name.length).toBeLessThan(255); }); + + it("does not split a surrogate pair when truncating long titles", () => { + const source = EnvironmentId.make("source"); + const threadId = ThreadId.make("surrogate-thread"); + const updatedAt = DateTime.makeUnsafe("2026-09-29T00:00:00.000Z"); + const title = `${"a".repeat(63)}𠀀`; + + const file = threadContextAttachment(source, { threadId, title, updatedAt, items: [] }); + + expect(file.name).toMatch(/^a{63}-[a-f0-9]+\.jsonl$/); + }); }); diff --git a/apps/web/src/lib/threadContextAttachment.ts b/apps/web/src/lib/threadContextAttachment.ts index 996b444d7f766..c8bfc5a9b5db3 100644 --- a/apps/web/src/lib/threadContextAttachment.ts +++ b/apps/web/src/lib/threadContextAttachment.ts @@ -1,4 +1,5 @@ import type { EnvironmentId, OrchestrationV2ThreadTranscript } from "@t3tools/contracts"; +import { splitsSurrogatePair } from "@t3tools/shared/assistantCitations"; import { toKindScopedComposerContextId } from "@t3tools/shared/composerContextReferences"; import { threadTranscriptHeader } from "@t3tools/shared/threadTranscript"; import * as DateTime from "effect/DateTime"; @@ -12,7 +13,8 @@ export function threadContextAttachment( "thread", `${environmentId}:${transcript.threadId}:${updatedAt}`, ); - const title = transcript.title.replace(/[^\p{L}\p{N}._ -]/gu, "_").slice(0, 64) || "Thread"; + const sanitized = transcript.title.replace(/[^\p{L}\p{N}._ -]/gu, "_"); + const title = sanitized.slice(0, splitsSurrogatePair(sanitized, 64) ? 63 : 64) || "Thread"; return new File( [ threadTranscriptHeader(environmentId, transcript), From 61fefc66e3ae70ebb9225c0cdd04fea4a88cbbb0 Mon Sep 17 00:00:00 2001 From: Stanislav Zmiev Date: Wed, 25 Nov 2026 14:27:27 +0400 Subject: [PATCH 073/880] fix(server): tasks delegated to an older linked machine report back when they finish (#42717) Co-authored-by: Julius Marminge (cherry picked from commit f9da246cd5cbbf5c09b045dfcde6c76435608528) --- apps/server/src/peer/RemoteDelegation.test.ts | 13 ++++++++----- apps/server/src/peer/RemoteDelegation.ts | 6 ++++-- 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/apps/server/src/peer/RemoteDelegation.test.ts b/apps/server/src/peer/RemoteDelegation.test.ts index d075c44ef9ff2..f925f65b48b09 100644 --- a/apps/server/src/peer/RemoteDelegation.test.ts +++ b/apps/server/src/peer/RemoteDelegation.test.ts @@ -451,7 +451,9 @@ const boxToolkitLayer = (thread: BoxThread) => { }, ]), ] - ).map((entry, position) => ({ ...entry, position })); + ) + // Position 0 is the task's prompt, which the follower reads past. + .map((entry, index) => ({ ...entry, position: index + 1 })); const visible = options.itemId === undefined ? replies.filter( @@ -492,7 +494,7 @@ const boxToolkitLayer = (thread: BoxThread) => { }), } as never, })), - totalItems: replies.length, + totalItems: replies.length + 1, hasMore: options.itemId === undefined && matching.length > 0 && @@ -1714,7 +1716,7 @@ it.effect.each(["tail-error", "middle-error", "reply-fallback", "cancel-refill"] const pages = reads.filter((read) => read.itemId === undefined && read.limit === 100); // A page moves on by however many items the response budget left it. const remaining = (read: OrchestratorMcpThreadReadInput) => - timeline.length - 1 - (read.afterPosition ?? -1); + timeline.length - (read.afterPosition ?? 0); expect(pages[0]).toMatchObject({ view: "activity", limit: 100, @@ -1832,8 +1834,9 @@ it.effect.each([ } const pages = reads.filter((read) => read.itemId === undefined && read.limit === 100); // The thread's final page starts at its canonical 100-item boundary. - const tailPosition = Math.floor((timeline.length - 1) / 100) * 100 - 1; - expect(pages.at(0)?.afterPosition).toBe(-1); + const tailPosition = Math.floor(timeline.length / 100) * 100 - 1; + // Starts after the prompt, a cursor every peer accepts. + expect(pages.at(0)?.afterPosition).toBe(0); expect( pages.every( (read) => diff --git a/apps/server/src/peer/RemoteDelegation.ts b/apps/server/src/peer/RemoteDelegation.ts index 5ed03b795b686..07033bf8f38f9 100644 --- a/apps/server/src/peer/RemoteDelegation.ts +++ b/apps/server/src/peer/RemoteDelegation.ts @@ -619,8 +619,10 @@ const make = Effect.gen(function* () { ) { let reply: OrchestratorMcpThreadTimelineItem | undefined; let error: OrchestratorMcpThreadTimelineItem | undefined; - // Linked peers read newest first without a cursor; this scan runs forward. - let afterPosition = -1; + // Linked peers read newest first without a cursor, so this scan runs forward. It starts + // after position 0, the message that started the thread, which no run's reply can precede; + // older peers refuse -1. + let afterPosition = 0; let run: OrchestratorMcpThreadRun | undefined; let remainingItems = 0; let tailProbed = false; From e96a78ee6843c3817fe611b7aee84854e69ddbc2 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 25 Nov 2026 02:30:37 -0800 Subject: [PATCH 074/880] fix(server): diff panel reads GBK/GB18030 files instead of showing mojibake (#42735) (cherry picked from commit 4a34889e286344a519163482a8fa561123e5901f) --- apps/server/src/vcs/GitVcsDriverCore.test.ts | 85 ++++++++++++++++++++ apps/server/src/vcs/GitVcsDriverCore.ts | 64 ++++++++++++--- 2 files changed, 139 insertions(+), 10 deletions(-) diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.ts index 29484e835fed7..e715f10a7f642 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.test.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts @@ -4777,6 +4777,91 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); + it.effect("shows GBK-encoded files as readable text in the review diff and expansion", () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + yield* initRepoWithCommit(cwd); + const before = "// 初始中文注释\nint a = 1;\n"; + const after = "// 修改后的中文注释\nint a = 2;\n"; + // GBK bytes of `before` and `after`. + const writeMain = (hex: string) => + Effect.sync(() => + NodeFS.writeFileSync(NodePath.join(cwd, "main.c"), Buffer.from(hex, "hex")), + ); + yield* writeMain("2f2f20b3f5cabcd6d0cec4d7a2cacd0a696e742061203d20313b0a"); + yield* git(cwd, ["add", "main.c"]); + yield* git(cwd, ["commit", "-m", "add GBK file"]); + yield* writeMain("2f2f20d0deb8c4baf3b5c4d6d0cec4d7a2cacd0a696e742061203d20323b0a"); + const driver = yield* GitVcsDriver.GitVcsDriver; + + const preview = yield* driver.getReviewDiffPreview({ cwd }); + const diff = preview.sources.map((source) => source.diff).join("\n"); + assert.include(diff, "-// 初始中文注释"); + assert.include(diff, "+// 修改后的中文注释"); + + const contents = yield* driver.getReviewDiffFileContents( + makeReviewDiffFileContentsInput(cwd, { oldPath: "main.c", newPath: "main.c" }), + ); + assert.deepStrictEqual(contents, { oldContents: before, newContents: after }); + }), + ); + + // macOS and Windows filesystems reject file names that are not valid UTF-8. + it.effect.skipIf(HostProcess.Platform.defaultValue() !== "linux")( + "keeps UTF-8 paths intact next to a non-UTF-8 path in NUL-separated output", + () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + yield* initRepoWithCommit(cwd); + for (const name of ["文档.md", "café.md"]) { + NodeFS.writeFileSync(NodePath.join(cwd, name), "x\n"); + } + NodeFS.writeFileSync( + Buffer.concat([ + Buffer.from(`${cwd}/Gro`), + Buffer.from([0xf6, 0xdf]), + Buffer.from("e.c"), + ]), + "x\n", + ); + const driver = yield* GitVcsDriver.GitVcsDriver; + + const result = yield* driver.execute({ + operation: "test.lsFilesOthers", + cwd, + args: ["ls-files", "-z", "--others"], + }); + const paths = result.stdout.split("\0"); + assert.include(paths, "文档.md"); + assert.include(paths, "café.md"); + }), + ); + + it.effect("keeps truncated UTF-8 output as UTF-8 when the cap cuts a character", () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + yield* initRepoWithCommit(cwd); + const driver = yield* GitVcsDriver.GitVcsDriver; + const blob = yield* driver.execute({ + operation: "test.hashObject", + cwd, + args: ["hash-object", "-w", "--stdin"], + stdin: "a中文中文\n", + }); + + // "a" + "中" + the first byte of "文": the cap lands inside a UTF-8 character. + const result = yield* driver.execute({ + operation: "test.catFile", + cwd, + args: ["cat-file", "-p", blob.stdout.trim()], + maxOutputBytes: 5, + appendTruncationMarker: true, + }); + assert.isTrue(result.stdoutTruncated); + assert.strictEqual(result.stdout, "a中\uFFFD"); + }), + ); + it.effect("reads a base ref that looks like an option as a revision", () => Effect.gen(function* () { const cwd = yield* makeTmpDir(); diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index 3ab8a6c7f6e82..dbba7fc75c6af 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -903,6 +903,51 @@ export function parseGitCheckoutProgressLine( const OUTPUT_LINE_SEPARATOR = /\r\n|\r|\n/; +const strictUtf8Decoder = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }); +const lenientUtf8Decoder = new TextDecoder("utf-8", { ignoreBOM: true }); +const gb18030Decoder = new TextDecoder("gb18030", { ignoreBOM: true }); + +// A byte cap can cut the last UTF-8 character; that tail is not evidence of another encoding. +const decodeStrictUtf8 = (bytes: Uint8Array, truncated: boolean): string => { + if (!truncated) return strictUtf8Decoder.decode(bytes); + const decoder = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }); + const text = decoder.decode(bytes, { stream: true }); + try { + return text + decoder.decode(); + } catch { + return `${text}\uFFFD`; + } +}; + +const decodeUtf8OrGb18030 = (bytes: Uint8Array, truncated: boolean): string => { + try { + return decodeStrictUtf8(bytes, truncated); + } catch { + const fallback = gb18030Decoder.decode(bytes); + return fallback.includes("\uFFFD") ? lenientUtf8Decoder.decode(bytes) : fallback; + } +}; + +// Git emits file bytes as stored; without a working-tree-encoding attribute, GBK/GB18030 +// sources are not UTF-8. Decode per LF line or NUL record (`-z` output) so one such file or +// path does not garble UTF-8 neighbours. +const decodeGitText = (bytes: Uint8Array, truncated = false): string => { + try { + return decodeStrictUtf8(bytes, truncated); + } catch { + let text = ""; + let start = 0; + while (start < bytes.length) { + let end = start; + while (end < bytes.length && bytes[end] !== 0x0a && bytes[end] !== 0x00) end += 1; + end = Math.min(end + 1, bytes.length); + text += decodeUtf8OrGb18030(bytes.subarray(start, end), truncated && end === bytes.length); + start = end; + } + return text; + } +}; + const collectOutput = Effect.fnUntraced(function* ( input: Pick, stream: Stream.Stream, @@ -911,10 +956,10 @@ const collectOutput = Effect.fnUntraced(function* ( onLine: ((line: string) => Effect.Effect) | undefined, keepLineCallbacksAfterTruncation = false, ): Effect.fn.Return<{ readonly text: string; readonly truncated: boolean }, GitCommandError> { - const decoder = new TextDecoder("utf-8", { ignoreBOM: true }); const lineDecoder = keepLineCallbacksAfterTruncation && onLine ? new TextDecoder() : null; + const lineStreamDecoder = new TextDecoder("utf-8", { ignoreBOM: true }); + const chunks: Array = []; let bytes = 0; - let text = ""; let lineBuffer = ""; let truncated = false; // Bound newline-free output; oversized lines are not useful to callbacks. @@ -966,10 +1011,11 @@ const collectOutput = Effect.fnUntraced(function* ( bytes += chunkToDecode.byteLength; truncated = appendTruncationMarker && nextBytes > maxOutputBytes; - const decoded = decoder.decode(chunkToDecode, { stream: !truncated }); - text += decoded; + chunks.push(chunkToDecode); if (onLine) { - lineBuffer += lineDecoder ? lineDecoder.decode(chunk, { stream: true }) : decoded; + lineBuffer += lineDecoder + ? lineDecoder.decode(chunk, { stream: true }) + : lineStreamDecoder.decode(chunkToDecode, { stream: !truncated }); yield* emitCompleteLines(false); } }); @@ -985,15 +1031,13 @@ const collectOutput = Effect.fnUntraced(function* ( }), ); - const remainder = truncated ? "" : decoder.decode(); - text += remainder; if (onLine) { - lineBuffer += remainder; + if (!truncated && !lineDecoder) lineBuffer += lineStreamDecoder.decode(); if (lineDecoder) lineBuffer += lineDecoder.decode(); yield* emitCompleteLines(true); } return { - text, + text: decodeGitText(Buffer.concat(chunks), truncated), truncated, }; }); @@ -5154,7 +5198,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* if (bytes.includes(0)) { return yield* fileError("fs.readFile", `Cannot expand binary file '${input.newPath}'.`); } - const contents = new TextDecoder("utf-8", { ignoreBOM: true }).decode(bytes); + const contents = decodeGitText(bytes); if (!contents.includes("$Id:")) return contents; const collapsed = contents.replace(GIT_IDENT_KEYWORD, () => "$Id$"); if (collapsed === contents) return contents; From 429dc172de1cf954eade876cfd14c473c4422b22 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 25 Nov 2026 02:54:06 -0800 Subject: [PATCH 075/880] fix(server): Claude skill picker lists only the skills a marketplace entry declares (#42743) (cherry picked from commit e8fb0a0d4364e8a17689fb4f7db554e036cacc36) --- .../src/provider/Drivers/ClaudeSkills.test.ts | 59 +++++++++ .../src/provider/Drivers/ClaudeSkills.ts | 124 ++++++++++++++---- 2 files changed, 161 insertions(+), 22 deletions(-) diff --git a/apps/server/src/provider/Drivers/ClaudeSkills.test.ts b/apps/server/src/provider/Drivers/ClaudeSkills.test.ts index f9112247cab81..bb2b8ecc9a690 100644 --- a/apps/server/src/provider/Drivers/ClaudeSkills.test.ts +++ b/apps/server/src/provider/Drivers/ClaudeSkills.test.ts @@ -85,6 +85,65 @@ it.layer(NodeServices.layer)("discoverClaudeSkills", (it) => { }), ); + it.effect("loads only the skills a non-strict marketplace entry declares", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-claude-skills-" }); + const configDir = path.join(tempDir, "claude-home"); + const marketplace = path.join(tempDir, "marketplace"); + const marketplaceJson = JSON.stringify({ + name: "shared-root", + plugins: [ + { name: "collection-a", source: "./", strict: false, skills: ["./skills/skill-one"] }, + { name: "collection-b", source: "./", strict: false, skills: ["./skills/skill-two"] }, + ], + }); + // `claude plugin install` copies the whole repository into each plugin's cache folder. + const installs = ["collection-a", "collection-b"].map((name) => + path.join(configDir, "plugins", "cache", "shared-root", name, "abc123"), + ); + for (const root of [marketplace, ...installs]) { + yield* writeSkill(path.join(root, "skills"), "skill-one", "# One"); + yield* writeSkill(path.join(root, "skills"), "skill-two", "# Two"); + yield* fs.makeDirectory(path.join(root, ".claude-plugin"), { recursive: true }); + yield* fs.writeFileString( + path.join(root, ".claude-plugin", "marketplace.json"), + marketplaceJson, + ); + } + yield* fs.writeFileString( + path.join(configDir, "plugins", "known_marketplaces.json"), + JSON.stringify({ + "shared-root": { + source: { source: "directory", path: marketplace }, + installLocation: marketplace, + }, + }), + ); + yield* fs.writeFileString( + path.join(configDir, "plugins", "installed_plugins.json"), + JSON.stringify({ + version: 2, + plugins: { + "collection-a@shared-root": [{ scope: "user", installPath: installs[0] }], + "collection-b@shared-root": [{ scope: "user", installPath: installs[1] }], + }, + }), + ); + yield* fs.writeFileString( + path.join(configDir, "settings.json"), + '{"enabledPlugins":{"collection-a@shared-root":true,"collection-b@shared-root":true}}', + ); + + const skills = yield* discoverClaudeSkills({ homePath: configDir }); + assert.deepEqual( + skills.map((skill) => skill.name), + ["collection-a:skill-one", "collection-b:skill-two"], + ); + }), + ); + it.effect("merges plugin enablement and selects installs in native registry order", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; diff --git a/apps/server/src/provider/Drivers/ClaudeSkills.ts b/apps/server/src/provider/Drivers/ClaudeSkills.ts index 5d87bc3dd8f27..9c241af6204a6 100644 --- a/apps/server/src/provider/Drivers/ClaudeSkills.ts +++ b/apps/server/src/provider/Drivers/ClaudeSkills.ts @@ -347,6 +347,20 @@ const PluginManifest = Schema.fromJsonString( defaultEnabled: Schema.optional(Schema.Unknown), }), ); +const KnownMarketplaces = Schema.fromJsonString(Schema.Record(Schema.String, Schema.Unknown)); +const decodeKnownMarketplace = Schema.decodeUnknownOption( + Schema.Struct({ installLocation: Schema.NonEmptyString }), +); +const MarketplaceManifest = Schema.fromJsonString( + Schema.Struct({ plugins: Schema.Array(Schema.Unknown) }), +); +const decodeMarketplaceEntry = Schema.decodeUnknownOption( + Schema.Struct({ + name: Schema.String, + source: Schema.Unknown, + skills: Schema.optional(Schema.Union([Schema.String, Schema.Array(Schema.String)])), + }), +); const SyncedPlugins = Schema.fromJsonString( Schema.Struct({ plugins: Schema.Array(Schema.Unknown) }), @@ -389,32 +403,18 @@ const readPluginManifest = Effect.fn("readPluginManifest")(function* (pluginPath ); }); -const pluginSkillRoots = Effect.fn("pluginSkillRoots")(function* ( +/** Declared skill folders that exist inside the install, through symlinks too, as the native loader requires. */ +const containedSkillDirectories = Effect.fn("containedSkillDirectories")(function* ( installPath: string, - scope: ClaudeSkillScope, - prefix: string, - manifest: typeof PluginManifest.Type | undefined, + declared: ReadonlyArray, ) { const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; - const roots: Array = []; - const defaultDirectory = path.join(installPath, "skills"); - const hasDefaultDirectory = yield* fileSystem - .exists(defaultDirectory) - .pipe(Effect.orElseSucceed(() => false)); - if (hasDefaultDirectory) roots.push({ directory: defaultDirectory, scope, prefix }); - const declared = manifest?.skills; - if (declared === undefined && !hasDefaultDirectory) { - const hasRootSkill = yield* fileSystem - .exists(path.join(installPath, "SKILL.md")) - .pipe(Effect.orElseSucceed(() => false)); - if (hasRootSkill) roots.push({ directory: installPath, scope, prefix }); - } - const canonicalInstallPath = yield* fileSystem .realPath(installPath) .pipe(Effect.orElseSucceed(() => undefined)); - for (const relative of typeof declared === "string" ? [declared] : (declared ?? [])) { + const directories: Array = []; + for (const relative of declared) { const directory = path.resolve(installPath, relative); if (!isInsideDirectory(path, installPath, directory) || canonicalInstallPath === undefined) { continue; @@ -422,14 +422,53 @@ const pluginSkillRoots = Effect.fn("pluginSkillRoots")(function* ( const canonicalDirectory = yield* fileSystem .realPath(directory) .pipe(Effect.orElseSucceed(() => undefined)); - // The native loader rejects manifest roots that escape through a symlink, too. if ( canonicalDirectory !== undefined && isInsideDirectory(path, canonicalInstallPath, canonicalDirectory) ) { - roots.push({ directory, scope, prefix }); + directories.push(directory); } } + return directories; +}); + +const pluginSkillRoots = Effect.fn("pluginSkillRoots")(function* ( + installPath: string, + scope: ClaudeSkillScope, + prefix: string, + manifest: typeof PluginManifest.Type | undefined, + entrySkills?: ReadonlyArray, +) { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const defaultDirectory = path.join(installPath, "skills"); + // A root-sourced marketplace entry's skills list replaces the plugin's skills; `./` means skills/. + const entryDirectories = + entrySkills === undefined ? [] : yield* containedSkillDirectories(installPath, entrySkills); + if (entryDirectories.length > 0) { + return entryDirectories.map((directory) => ({ + directory: directory === installPath ? defaultDirectory : directory, + scope, + prefix, + })); + } + const roots: Array = []; + const hasDefaultDirectory = yield* fileSystem + .exists(defaultDirectory) + .pipe(Effect.orElseSucceed(() => false)); + if (hasDefaultDirectory) roots.push({ directory: defaultDirectory, scope, prefix }); + const declared = manifest?.skills; + if (declared === undefined && !hasDefaultDirectory) { + const hasRootSkill = yield* fileSystem + .exists(path.join(installPath, "SKILL.md")) + .pipe(Effect.orElseSucceed(() => false)); + if (hasRootSkill) roots.push({ directory: installPath, scope, prefix }); + } + const declaredDirectories = yield* containedSkillDirectories( + installPath, + typeof declared === "string" ? [declared] : (declared ?? []), + ); + for (const directory of declaredDirectories) roots.push({ directory, scope, prefix }); return roots; }); @@ -567,6 +606,42 @@ const discoverPluginSkillRoots = Effect.fn("discoverPluginSkillRoots")(function* const projectRepositoryRoots = new Map(); const repositoryRoot = workspace === undefined ? undefined : yield* findPluginRepositoryRoot(workspace); + const knownMarketplaces = yield* fileSystem + .readFileString(path.join(pluginsPath, "known_marketplaces.json")) + .pipe( + Effect.flatMap(Schema.decodeUnknownEffect(KnownMarketplaces)), + Effect.orElseSucceed((): Record => ({})), + ); + const marketplaceEntries = new Map>(); + // Claude applies an entry's skills list only when the entry's source is the marketplace root. + const readRootEntrySkills = Effect.fnUntraced(function* (marketplace: string, plugin: string) { + if (!marketplaceEntries.has(marketplace)) { + const location = Option.getOrUndefined( + decodeKnownMarketplace(knownMarketplaces[marketplace]), + )?.installLocation; + const manifest = + location === undefined + ? undefined + : yield* fileSystem + .readFileString(path.join(location, ".claude-plugin", "marketplace.json")) + .pipe( + Effect.flatMap(Schema.decodeUnknownEffect(MarketplaceManifest)), + Effect.orElseSucceed(() => undefined), + ); + marketplaceEntries.set(marketplace, manifest?.plugins ?? []); + } + const entry = (marketplaceEntries.get(marketplace) ?? []) + .flatMap((candidate) => Option.toArray(decodeMarketplaceEntry(candidate))) + .find((candidate) => candidate.name === plugin); + if ( + entry?.skills === undefined || + typeof entry.source !== "string" || + !entry.source.split(/[\\/]/).every((segment) => segment === "" || segment === ".") + ) { + return undefined; + } + return typeof entry.skills === "string" ? [entry.skills] : entry.skills; + }); for (const [key, entries] of Object.entries(installed?.plugins ?? {}).sort()) { if (enabledPlugins.get(key) !== true) continue; @@ -600,7 +675,12 @@ const discoverPluginSkillRoots = Effect.fn("discoverPluginSkillRoots")(function* if (!prefix || inlinePluginNames.has(pluginNameKey(prefix))) continue; // A registry record whose install is gone loads nothing and claims no namespace. if (Option.isSome(existing)) claimedPluginNames.add(pluginNameKey(prefix)); - roots.push(...(yield* pluginSkillRoots(installPath, scope, prefix, manifest))); + const separator = key.lastIndexOf("@"); + const entrySkills = + separator > 0 + ? yield* readRootEntrySkills(key.slice(separator + 1), key.slice(0, separator)) + : undefined; + roots.push(...(yield* pluginSkillRoots(installPath, scope, prefix, manifest, entrySkills))); } if (syncedBucket === undefined) return roots; From ddb9e04e7fb27195f3dbf4bd16f946a53c612442 Mon Sep 17 00:00:00 2001 From: Victor Date: Wed, 25 Nov 2026 04:57:15 -0600 Subject: [PATCH 076/880] fix(server): PowerPoint attachment text no longer includes slide animation names (#42741) Co-authored-by: Julius Marminge (cherry picked from commit 45a3880ce1aebbfe4a3669ab9966e3497ec01f2a) --- apps/server/src/provider/documentTextWorker.ts | 5 +++++ apps/server/src/provider/userInputAttachments.test.ts | 8 ++++++-- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/apps/server/src/provider/documentTextWorker.ts b/apps/server/src/provider/documentTextWorker.ts index 84521565d0f79..36f635784b9f2 100644 --- a/apps/server/src/provider/documentTextWorker.ts +++ b/apps/server/src/provider/documentTextWorker.ts @@ -124,6 +124,11 @@ function xml(source: string, extension: string): XmlNode { (prop) => prop.name === "vanish" && ["true", "1", "on"].includes(prop.attrs.val ?? "1"), )) || (odf && node.name === "annotation" && parent.name !== "semantics") || + (extension === ".pptx" && + node.name === "timing" && + stack.every((ancestor) => + ["root", "sld", "AlternateContent", "Choice", "Fallback"].includes(ancestor.name), + )) || (extension === ".odp" && node.name === "page-thumbnail" && stack.some((ancestor) => ancestor.name === "notes")) diff --git a/apps/server/src/provider/userInputAttachments.test.ts b/apps/server/src/provider/userInputAttachments.test.ts index 8e4d7322de740..d51ec07e755bc 100644 --- a/apps/server/src/provider/userInputAttachments.test.ts +++ b/apps/server/src/provider/userInputAttachments.test.ts @@ -1165,8 +1165,10 @@ describe("question answer paths", () => { `, "ppt/_rels/presentation.xml.rels": '', - "ppt/slides/slide1.xml": "Departure", - "ppt/slides/slide2.xml": "Juniper Pier", + "ppt/slides/slide1.xml": + 'Departurestyle.visibility', + "ppt/slides/slide2.xml": + 'Juniper Pierppt_x', "ppt/slides/_rels/slide2.xml.rels": '', "ppt/slides/_rels/slide1.xml.rels": @@ -1190,6 +1192,8 @@ describe("question answer paths", () => { "11/21/2026", "Crew only", "57", + "style.visibility", + "ppt_x", "[Skipped document part", "[Extracted text truncated", ], From 2badfe8d53c3aef39bf0478c0a21f714da61f09a Mon Sep 17 00:00:00 2001 From: Victor Date: Wed, 25 Nov 2026 05:38:01 -0600 Subject: [PATCH 077/880] fix(web): reasoning previews no longer cut emojis in half (#42755) Co-authored-by: Julius Marminge (cherry picked from commit f99eceb76dac7c8ee405a0c71dd9a5dd4a32d700) --- .../chat/MessagesTimeline.browser.test.tsx | 28 ++++++++++++++++++- .../chat/TimelineWorkEntryRow.logic.ts | 10 +++++++ .../components/chat/TimelineWorkEntryRow.tsx | 7 ++--- .../components/chat/TimelineWorkGroupRows.tsx | 6 ++-- 4 files changed, 42 insertions(+), 9 deletions(-) diff --git a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx index fa46f2788a27a..e21246e19c2be 100644 --- a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx @@ -43,7 +43,11 @@ import { deriveTimelineEntriesFromVisibleTurnItems, } from "../../session-logic"; import { ViewedImagesTimelineRow } from "./TimelineWorkEntryRow"; -import { THOUGHT_PREVIEW_MAX_LENGTH, thoughtPreviewMarkdown } from "./TimelineWorkEntryRow.logic"; +import { + THOUGHT_PREVIEW_MAX_LENGTH, + THOUGHT_PREVIEW_SOURCE_MAX_LENGTH, + thoughtPreviewMarkdown, +} from "./TimelineWorkEntryRow.logic"; import { wordsHast } from "~/markdown/wordsHast"; import { TimelineRowCtx } from "./timelineRowContext"; import { searchableMessageSegments } from "@t3tools/shared/threadFindText"; @@ -2302,6 +2306,28 @@ describe("compact reasoning math", () => { ), ).toEqual(expected); }); + + it("does not split a surrogate pair at the reasoning preview source limit", async () => { + setup(); + const prefix = `[l](${"u".repeat(8_100)}) `; + const filler = "c".repeat(THOUGHT_PREVIEW_SOURCE_MAX_LENGTH - 1 - prefix.length); + await using screen = await renderTimeline( + [ + work("thought-1", { + label: "Thinking", + tone: "thinking", + itemType: "reasoning", + toolLifecycleStatus: "inProgress", + detail: `${prefix}${filler}😀 tail`, + }), + ], + { isWorking: true }, + ); + await vi.waitFor(() => { + expect(screen.text()).toContain(`l ${filler}`); + }); + expect(screen.text()).not.toContain("\uFFFD"); + }); }); it("renders automatic compaction as one live divider that finishes with its reason and token delta", async () => { diff --git a/apps/web/src/components/chat/TimelineWorkEntryRow.logic.ts b/apps/web/src/components/chat/TimelineWorkEntryRow.logic.ts index 894f58f45edb4..098d69f38c81c 100644 --- a/apps/web/src/components/chat/TimelineWorkEntryRow.logic.ts +++ b/apps/web/src/components/chat/TimelineWorkEntryRow.logic.ts @@ -4,6 +4,7 @@ import { resolveWorkEntryToolPresentation, toolGroupAction, } from "@t3tools/client-runtime/work-log/presentation"; +import { splitsSurrogatePair } from "@t3tools/shared/assistantCitations"; import { isJavaScriptReplTool } from "@t3tools/shared/toolActivity"; import { formatWorkspaceRelativePath } from "../../filePathDisplay"; import { m, type MessageResolver } from "../../i18n/messages"; @@ -208,6 +209,15 @@ export function workEntryIconName(workEntry: TimelineWorkEntry): WorkEntryIconNa export const THOUGHT_PREVIEW_SOURCE_MAX_LENGTH = 8_192; export const THOUGHT_PREVIEW_MAX_LENGTH = 2_048; +export function sliceThoughtPreviewSource(text: string): string { + return text.slice( + 0, + splitsSurrogatePair(text, THOUGHT_PREVIEW_SOURCE_MAX_LENGTH) + ? THOUGHT_PREVIEW_SOURCE_MAX_LENGTH - 1 + : THOUGHT_PREVIEW_SOURCE_MAX_LENGTH, + ); +} + const thoughtPreviews = new Map(); /** Compact reasoning keeps formulas while flattening other Markdown into label text. */ diff --git a/apps/web/src/components/chat/TimelineWorkEntryRow.tsx b/apps/web/src/components/chat/TimelineWorkEntryRow.tsx index 4cd6fc0e8dee6..864399d72496c 100644 --- a/apps/web/src/components/chat/TimelineWorkEntryRow.tsx +++ b/apps/web/src/components/chat/TimelineWorkEntryRow.tsx @@ -73,8 +73,8 @@ import { workEntryRawCommand, buildToolCallExpandedBody, workEntryIconName, + sliceThoughtPreviewSource, thoughtPreviewMarkdown, - THOUGHT_PREVIEW_SOURCE_MAX_LENGTH, } from "./TimelineWorkEntryRow.logic"; export function useThreadReadTarget(entry: TimelineWorkEntry, environmentId: EnvironmentId) { @@ -584,10 +584,7 @@ function WorkEntryLogRow(props: WorkEntryRowProps) { {isReasoning && !expanded ? ( Date: Wed, 25 Nov 2026 05:45:47 -0600 Subject: [PATCH 078/880] fix(web): held overlay and Usage shortcuts no longer flicker (#42757) Co-authored-by: Julius Marminge (cherry picked from commit dca3ab2025c15cfa5907757229be894cbc04cd80) --- .../commandPaletteCommands.browser.test.tsx | 44 ++++++++++++++++++- .../src/shortcuts/commandPaletteCommands.ts | 3 ++ 2 files changed, 46 insertions(+), 1 deletion(-) diff --git a/apps/web/src/shortcuts/commandPaletteCommands.browser.test.tsx b/apps/web/src/shortcuts/commandPaletteCommands.browser.test.tsx index 14054438242a5..92a090def3123 100644 --- a/apps/web/src/shortcuts/commandPaletteCommands.browser.test.tsx +++ b/apps/web/src/shortcuts/commandPaletteCommands.browser.test.tsx @@ -9,10 +9,13 @@ import { useCommandPaletteMount, useCommandPaletteStore, } from "../commandPaletteStore"; +import { useThemeEditorStore } from "../components/settings/themeEditorStore"; import { installCommandPaletteCommands } from "./commandPaletteCommands"; const keybindings = compileResolvedKeybindingsConfig([ { key: "mod+k", command: "commandPalette.toggle" }, + { key: "mod+alt+shift+t", command: "themeEditor.toggle" }, + { key: "mod+u", command: "usage.open" }, ]); function MountedPalette() { @@ -22,6 +25,7 @@ function MountedPalette() { function setup() { useCommandPaletteStore.setState(useCommandPaletteStore.getInitialState(), true); + useThemeEditorStore.setState(useThemeEditorStore.getInitialState(), true); } describe("command palette shortcuts", () => { @@ -39,7 +43,7 @@ describe("command palette shortcuts", () => { expect(useCommandPaletteStore.getState().open).toBe(false); }); - it("open the palette while it is mounted, and it closes when it unmounts", async () => { + it("open the palette while it is mounted, keep it open on repeat, and it closes when it unmounts", async () => { setup(); using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("Linux x86_64"); await using screen = await render(, { router: "/" }); @@ -51,6 +55,17 @@ describe("command palette shortcuts", () => { await userEvent.keyboard("{Control>}k{/Control}"); expect(useCommandPaletteStore.getState().open).toBe(true); + const repeatEvent = new KeyboardEvent("keydown", { + key: "k", + ctrlKey: true, + repeat: true, + bubbles: true, + cancelable: true, + }); + document.body.dispatchEvent(repeatEvent); + expect(repeatEvent.defaultPrevented).toBe(true); + expect(useCommandPaletteStore.getState().open).toBe(true); + await screen.rerender(
); expect(useCommandPaletteStore.getState().open).toBe(false); }); @@ -137,6 +152,33 @@ describe("command palette shortcuts", () => { expect(freshEscape.defaultPrevented).toBe(true); expect(useCommandPaletteStore.getState()).toMatchObject({ open: true, mode: "command" }); }); + + it("ignore held theme editor and Usage shortcuts", async () => { + setup(); + using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("Linux x86_64"); + await using screen = await render(, { router: "/" }); + using commands = new DisposableStack(); + commands.defer( + installCommandPaletteCommands(screen.router!, { keybindings: () => keybindings }), + ); + using navigate = vi.spyOn(screen.router!, "navigate").mockResolvedValue(undefined); + + for (const keys of [ + { key: "T", ctrlKey: true, altKey: true, shiftKey: true }, + { key: "u", ctrlKey: true }, + ]) { + const event = new KeyboardEvent("keydown", { + ...keys, + repeat: true, + bubbles: true, + cancelable: true, + }); + document.body.dispatchEvent(event); + expect(event.defaultPrevented, keys.key).toBe(true); + } + expect(useThemeEditorStore.getState().session).toBeNull(); + expect(navigate).not.toHaveBeenCalled(); + }); }); describe("openCommandPalette", () => { diff --git a/apps/web/src/shortcuts/commandPaletteCommands.ts b/apps/web/src/shortcuts/commandPaletteCommands.ts index 7b4992cc0c29c..531eb74ca1375 100644 --- a/apps/web/src/shortcuts/commandPaletteCommands.ts +++ b/apps/web/src/shortcuts/commandPaletteCommands.ts @@ -34,6 +34,7 @@ const toggleOverlay = const mode = overlayModeForCommand(command); if (mode === null) return false; consume(event); + if (event.repeat) return; dispatchCommandPalette({ _tag: "ToggleMode", mode }); }; @@ -101,11 +102,13 @@ export function installCommandPaletteCommands( }, "themeEditor.toggle": (event) => { consume(event); + if (event.repeat) return; const { theme, themeHalves, resolvedTheme } = getThemeSnapshot(); toggleThemeEditorForTheme({ theme, themeHalves, initialAppearance: resolvedTheme }); }, "usage.open": (event) => { consume(event); + if (event.repeat) return; dispatchCommandPalette({ _tag: "SetOpen", open: false }); void router.navigate({ to: "/usage" }); }, From 75e9748ba3bf87a3fa9b943a135d683ca6214289 Mon Sep 17 00:00:00 2001 From: Thomas Molinari <100191128+thomas0903@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:04:14 +1100 Subject: [PATCH 079/880] fix(web): expanding linked issues no longer hides thread details sections (#42771) Co-authored-by: Julius Marminge (cherry picked from commit 3a63e0ca37a50d31f78b0188960557ff69964e76) --- .../chat/ThreadDetailsCard.browser.test.tsx | 16 ++++++++ .../src/components/chat/ThreadDetailsCard.tsx | 6 +-- .../chat/ThreadDetailsIssueRows.tsx | 40 ++++++++++--------- .../chat/ThreadDetailsPrRow.browser.test.tsx | 2 + 4 files changed, 43 insertions(+), 21 deletions(-) diff --git a/apps/web/src/components/chat/ThreadDetailsCard.browser.test.tsx b/apps/web/src/components/chat/ThreadDetailsCard.browser.test.tsx index e234686d6ff0c..b03b58e10f4e2 100644 --- a/apps/web/src/components/chat/ThreadDetailsCard.browser.test.tsx +++ b/apps/web/src/components/chat/ThreadDetailsCard.browser.test.tsx @@ -45,6 +45,7 @@ function Card({ rows = 1, automationRows = 0, serverOverflowRows = 0, + issueListRows = 0, }: { threadRef: ScopedThreadRef; inline: boolean; @@ -55,6 +56,8 @@ function Card({ automationRows?: number; /** Rows of 100px that expanded server lists add, which density ignores. */ serverOverflowRows?: number; + /** Rows of 100px that expanded linked issues add, which density ignores. */ + issueListRows?: number; }) { return ( // The web root renders in StrictMode, which re-runs ref callbacks on every mount. @@ -92,6 +95,9 @@ function Card({ style={{ height: serverOverflowRows * 100 }} /> ) : null} + {issueListRows > 0 ? ( +
+ ) : null} )} @@ -196,3 +202,13 @@ it("stays full while expanded server rows overflow", async () => { .element(page.getByRole("region", { name: "Thread details" })) .toHaveAttribute("data-density", "full"); }); + +it("stays full while expanded issue rows overflow", async () => { + using fixture = setup(); + await using _screen = await render( + , + ); + await expect + .element(page.getByRole("region", { name: "Thread details" })) + .toHaveAttribute("data-density", "full"); +}); diff --git a/apps/web/src/components/chat/ThreadDetailsCard.tsx b/apps/web/src/components/chat/ThreadDetailsCard.tsx index 9959dbe2dc41c..aadb47d0724ce 100644 --- a/apps/web/src/components/chat/ThreadDetailsCard.tsx +++ b/apps/web/src/components/chat/ThreadDetailsCard.tsx @@ -80,10 +80,10 @@ export function ThreadDetailsCard({ const measure = () => { const frame = element.closest("[data-thread-details-card]"); const next = element.offsetHeight + (frame ? frame.offsetHeight - frame.clientHeight : 0); - // PR lists, servers, lineage, side chats and automations scroll as they grow. Counting them - // toward density would hide the section and workspace controls when the user asks to see more. + // PR and issue lists, servers, lineage, side chats and automations scroll as they grow. + // Counting them toward density would hide the section and workspace controls when the user asks to see more. const lists = element.querySelectorAll( - "[data-thread-relationships-panel], [data-thread-side-chats-panel], [data-thread-details-pr-list], [data-thread-automations-panel], [data-thread-details-server-overflow]", + "[data-thread-relationships-panel], [data-thread-side-chats-panel], [data-thread-details-pr-list], [data-thread-details-issue-list], [data-thread-automations-panel], [data-thread-details-server-overflow]", ); const fittingHeight = next - Array.from(lists).reduce((sum, list) => sum + list.offsetHeight, 0); diff --git a/apps/web/src/components/chat/ThreadDetailsIssueRows.tsx b/apps/web/src/components/chat/ThreadDetailsIssueRows.tsx index 5726d1edeca14..36776560c594a 100644 --- a/apps/web/src/components/chat/ThreadDetailsIssueRows.tsx +++ b/apps/web/src/components/chat/ThreadDetailsIssueRows.tsx @@ -160,27 +160,31 @@ export function ThreadDetailsIssueRows({ const [expandedThread, setExpandedThread] = useState(null); const threadKey = scopedThreadKey(threadRef); const expanded = expandedThread === threadKey; - const hasMore = compact && links.length > 1; - const visibleLinks = hasMore && !expanded ? links.slice(0, 1) : links; + const row = (link: ThreadIssueLink) => ( + + ); + const [first, ...rest] = links; + if (first === undefined || !compact || rest.length === 0) return <>{links.map(row)}; return ( <> - {visibleLinks.map((link) => ( - - ))} - {hasMore ? ( - setExpandedThread(expanded ? null : threadKey)} - /> + {row(first)} + {expanded ? ( +
+ {rest.map(row)} +
) : null} + setExpandedThread(expanded ? null : threadKey)} + /> ); } diff --git a/apps/web/src/components/chat/ThreadDetailsPrRow.browser.test.tsx b/apps/web/src/components/chat/ThreadDetailsPrRow.browser.test.tsx index 666bbccd13684..d58a084f4bf68 100644 --- a/apps/web/src/components/chat/ThreadDetailsPrRow.browser.test.tsx +++ b/apps/web/src/components/chat/ThreadDetailsPrRow.browser.test.tsx @@ -455,6 +455,8 @@ it("names the first linked issue and reveals more issues on demand", async () => await expect.element(extra).not.toBeInTheDocument(); await screen.getByRole("button", { name: "Show 1 more" }).click(); await expect.element(extra).toBeVisible(); + // The details card leaves this list out of its density measurement. + expect(extra.element().closest("[data-thread-details-issue-list]")).not.toBeNull(); await screen.getByRole("button", { name: "Show less" }).click(); await expect.element(extra).not.toBeInTheDocument(); }); From c01866818583864f356d713354ba13ba5873c3d9 Mon Sep 17 00:00:00 2001 From: Victor Date: Wed, 25 Nov 2026 06:09:57 -0600 Subject: [PATCH 080/880] fix(server): GB18030 RTF attachments no longer fail text extraction (#42776) Co-authored-by: Julius Marminge (cherry picked from commit f7d6796019709464d1ce1c10a19620eb129f638a) --- .../server/src/provider/documentTextWorker.ts | 4 ++- .../src/provider/userInputAttachments.test.ts | 26 +++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/apps/server/src/provider/documentTextWorker.ts b/apps/server/src/provider/documentTextWorker.ts index 36f635784b9f2..93b875e4ad305 100644 --- a/apps/server/src/provider/documentTextWorker.ts +++ b/apps/server/src/provider/documentTextWorker.ts @@ -506,6 +506,7 @@ const RTF_CODE_PAGES = new Map([ [949, "euc-kr"], [950, "big5"], [10000, "macintosh"], + [54936, "gb18030"], [65001, "utf-8"], ]); @@ -546,7 +547,8 @@ function* rtf(source: string): Generator { yield String.fromCharCode(byte); return; } - encoded ??= new Uint8Array(Math.min(source.length, MAX_OUTPUT * 3 + 4)); + // GB18030 spends up to 4 bytes per UTF-16 unit, so a full buffer decodes past MAX_OUTPUT. + encoded ??= new Uint8Array(Math.min(source.length, MAX_OUTPUT * 4 + 4)); if (encodedLength === encoded.length) yield* flushBytes(); encoded[encodedLength++] = byte; } diff --git a/apps/server/src/provider/userInputAttachments.test.ts b/apps/server/src/provider/userInputAttachments.test.ts index d51ec07e755bc..0fca878dfb291 100644 --- a/apps/server/src/provider/userInputAttachments.test.ts +++ b/apps/server/src/provider/userInputAttachments.test.ts @@ -375,6 +375,11 @@ describe("question answer paths", () => { "{\\rtf1\\ansi\\ansicpg936 \\'c4\n\\'e3\\'ba\\'c3}", "你好", ], + [ + "GB18030 code page", + String.raw`{\rtf1\ansi\ansicpg54936 \'d6\'d0\'ce\'c4 \'95\'32\'82\'36}`, + "中文 𠀀", + ], ["Big5 code page", String.raw`{\rtf1\ansi\ansicpg950 \'a7A\'a6n}`, "你好"], [ "multibyte font charsets and font code pages", @@ -434,6 +439,27 @@ describe("question answer paths", () => { }).pipe(Effect.provide(layer)), ); + it.effect("keeps long GB18030 four-byte RTF runs intact up to the output limit", () => + Effect.gen(function* () { + const config = yield* ServerConfig.ServerConfig; + const path = NodePath.join(config.attachmentsDir, "gb18030-long.rtf"); + NodeFS.writeFileSync( + path, + Buffer.concat([ + Buffer.from(String.raw`{\rtf1\ansi\ansicpg54936 `, "latin1"), + Buffer.from([0xd6, 0xd0]), + Buffer.alloc(1_050_000 * 4, Buffer.from([0x81, 0x39, 0xee, 0x39])), + Buffer.from("}", "latin1"), + ]), + ); + const text = yield* Effect.promise(() => extractDocumentText(path, ".rtf")); + expect(text.search(/[^中㐀]/u)).toBe(1_000_000); + expect(text.slice(1_000_000)).toBe( + "\n\n[Extracted text truncated at document extraction limits.]", + ); + }).pipe(Effect.provide(layer)), + ); + it.effect.each([false, true])("limits the child heap for standalone=%s", (standalone) => Effect.acquireUseRelease( Effect.promise(async () => { From d69ebebf17bf99e73680b5ea3800e4dbb43e4a5e Mon Sep 17 00:00:00 2001 From: Victor Date: Wed, 25 Nov 2026 06:44:36 -0600 Subject: [PATCH 081/880] fix(web): file picker highlights no longer break emoji in file names (#42805) Co-authored-by: Julius Marminge (cherry picked from commit cef38e408d45b74a02f99da0ed3d400d97fd4182) --- .../files/ProjectFilePicker.logic.test.ts | 42 +++++++++++++++- .../files/ProjectFilePicker.logic.ts | 50 +++++++++++++------ .../components/files/ProjectFilePicker.tsx | 15 +++--- 3 files changed, 85 insertions(+), 22 deletions(-) diff --git a/apps/web/src/components/files/ProjectFilePicker.logic.test.ts b/apps/web/src/components/files/ProjectFilePicker.logic.test.ts index 47efe8f58c44f..ed9344b31a115 100644 --- a/apps/web/src/components/files/ProjectFilePicker.logic.test.ts +++ b/apps/web/src/components/files/ProjectFilePicker.logic.test.ts @@ -1,6 +1,6 @@ import { assert, describe, it } from "vite-plus/test"; -import { getProjectFilePickerMatches } from "./ProjectFilePicker.logic"; +import { getProjectFilePickerMatches, groupMatchRanges } from "./ProjectFilePicker.logic"; function pathsForQuery(entries: Parameters[0], query: string) { return getProjectFilePickerMatches(entries, query).map(({ name, path }) => ({ name, path })); @@ -51,4 +51,44 @@ describe("getProjectFilePickerMatches", () => { ]); assert.deepEqual(indices("İ"), [[0], [0, 6]]); }); + + it("matches emoji by code point without splitting surrogate pairs", () => { + const match = getProjectFilePickerMatches([{ kind: "file", path: "notes/📁-🔥.md" }], "🔥")[0]; + + assert.deepEqual(match, { + name: "📁-🔥.md", + nameMatchIndices: [3, 4], + path: "notes/📁-🔥.md", + pathMatchIndices: [9, 10], + }); + }); + + it("maps emoji highlights accurately when lowercasing expands earlier characters", () => { + const entries = [{ kind: "file", path: "notes/İ-📁-🔥.md" }] as const; + + assert.deepEqual(getProjectFilePickerMatches(entries, "🔥")[0], { + name: "İ-📁-🔥.md", + nameMatchIndices: [5, 6], + path: "notes/İ-📁-🔥.md", + pathMatchIndices: [11, 12], + }); + assert.deepEqual(getProjectFilePickerMatches(entries, "İ🔥m")[0], { + name: "İ-📁-🔥.md", + nameMatchIndices: [0, 5, 6, 8], + path: "notes/İ-📁-🔥.md", + pathMatchIndices: [6, 11, 12, 14], + }); + }); +}); + +describe("groupMatchRanges", () => { + it("groups contiguous indices into [start, end) ranges", () => { + assert.deepEqual(groupMatchRanges([0, 1]), [[0, 2]]); + assert.deepEqual(groupMatchRanges([0, 2, 4, 5]), [ + [0, 1], + [2, 3], + [4, 6], + ]); + assert.deepEqual(groupMatchRanges([]), []); + }); }); diff --git a/apps/web/src/components/files/ProjectFilePicker.logic.ts b/apps/web/src/components/files/ProjectFilePicker.logic.ts index a19e8b4a1e8d5..fcf7993aba8c6 100644 --- a/apps/web/src/components/files/ProjectFilePicker.logic.ts +++ b/apps/web/src/components/files/ProjectFilePicker.logic.ts @@ -15,11 +15,12 @@ function fileName(path: string): string { } /** Return null for unmatched subsequences; server-matched entries still render without highlights. */ -function findMatchIndices(value: string, query: string): number[] | null { - if (!query) return []; +function findMatchIndices(value: string, queryChars: ReadonlyArray): number[] | null { + if (queryChars.length === 0) return []; + // Whole-string lowercasing preserves context-sensitive rules like Greek final sigma (Σ → ς); + // lowercasing lengthens İ (to i̇) and shortens nothing, so only a length change needs mapping back. const normalizedValue = value.toLowerCase(); - // Lowercasing lengthens İ (to i̇) and shortens nothing, so only a longer result needs mapping back. const sourceSpans: Array = []; if (normalizedValue.length !== value.length) { let sourceOffset = 0; @@ -29,20 +30,39 @@ function findMatchIndices(value: string, query: string): number[] | null { sourceOffset = span[1]; } } + const indices: number[] = []; let queryIndex = 0; + let offset = 0; - for (let valueIndex = 0; valueIndex < normalizedValue.length; valueIndex += 1) { - if (normalizedValue[valueIndex] !== query[queryIndex]) continue; - const [start, end] = sourceSpans[valueIndex] ?? [valueIndex, valueIndex + 1]; - for (let i = Math.max(start, (indices.at(-1) ?? -1) + 1); i < end; i += 1) indices.push(i); - queryIndex += 1; - if (queryIndex === query.length) return indices; + for (const char of normalizedValue) { + if (char === queryChars[queryIndex]) { + const [start, end] = sourceSpans[offset] ?? [offset, offset + char.length]; + for (let i = Math.max(start, (indices.at(-1) ?? -1) + 1); i < end; i += 1) indices.push(i); + queryIndex += 1; + if (queryIndex === queryChars.length) return indices; + } + offset += char.length; } return null; } +export function groupMatchRanges( + indices: ReadonlyArray, +): Array { + const ranges: Array<[number, number]> = []; + for (const index of indices) { + const previous = ranges.at(-1); + if (previous && previous[1] === index) { + previous[1] = index + 1; + } else { + ranges.push([index, index + 1]); + } + } + return ranges; +} + /** Preserve server ranking and query normalization while filtering files and computing highlights. */ export function getProjectFilePickerMatches( entries: ReadonlyArray, @@ -51,17 +71,19 @@ export function getProjectFilePickerMatches( ): ProjectFilePickerMatch[] { if (limit <= 0) return []; - const query = normalizeSearchQuery(rawQuery, { - trimLeadingPattern: /^[@./]+/, - }).replaceAll(/\s/g, ""); + const queryChars = Array.from( + normalizeSearchQuery(rawQuery, { + trimLeadingPattern: /^[@./]+/, + }).replaceAll(/\s/g, ""), + ); const matches: ProjectFilePickerMatch[] = []; for (const entry of entries) { if (entry.kind !== "file") continue; const name = fileName(entry.path); - const nameMatchIndices = findMatchIndices(name, query); - const pathMatchIndices = findMatchIndices(entry.path, query); + const nameMatchIndices = findMatchIndices(name, queryChars); + const pathMatchIndices = findMatchIndices(entry.path, queryChars); matches.push({ name, nameMatchIndices: nameMatchIndices ?? [], diff --git a/apps/web/src/components/files/ProjectFilePicker.tsx b/apps/web/src/components/files/ProjectFilePicker.tsx index 8e3f67ff0e809..c5fea40287543 100644 --- a/apps/web/src/components/files/ProjectFilePicker.tsx +++ b/apps/web/src/components/files/ProjectFilePicker.tsx @@ -15,6 +15,7 @@ import { type CommandPaletteActionItem } from "../CommandPalette.logic"; import { CommandPaletteResults } from "../CommandPaletteResults"; import { getProjectFilePickerMatches, + groupMatchRanges, PROJECT_FILE_PICKER_RESULT_LIMIT, } from "./ProjectFilePicker.logic"; import { useProjectFilePickerQuery } from "./projectFilesQueryState"; @@ -31,17 +32,17 @@ function HighlightedFuzzyText(props: { if (!props.active) return props.value; const parts: ReactNode[] = []; - let start = 0; - for (const index of props.indices) { - if (start < index) parts.push(props.value.slice(start, index)); + let cursor = 0; + for (const [start, end] of groupMatchRanges(props.indices)) { + if (cursor < start) parts.push(props.value.slice(cursor, start)); parts.push( - - {props.value[index]} + + {props.value.slice(start, end)} , ); - start = index + 1; + cursor = end; } - if (start < props.value.length) parts.push(props.value.slice(start)); + if (cursor < props.value.length) parts.push(props.value.slice(cursor)); return {parts}; } From d940eed1496994eb601f32a8cb33ef9d0546817c Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 25 Nov 2026 05:03:08 -0800 Subject: [PATCH 082/880] fix(web): issue number in the Issue panel follows 'Open links in' (#42824) (cherry picked from commit 2f7b7f03e32eaf38965246911e1af72d951ca934) --- .../issue/IssueDetailPanel.browser.test.tsx | 94 +++++++++++++++++++ .../src/components/issue/IssueDetailPanel.tsx | 6 ++ 2 files changed, 100 insertions(+) create mode 100644 apps/web/src/components/issue/IssueDetailPanel.browser.test.tsx diff --git a/apps/web/src/components/issue/IssueDetailPanel.browser.test.tsx b/apps/web/src/components/issue/IssueDetailPanel.browser.test.tsx new file mode 100644 index 0000000000000..7b9755435a1e9 --- /dev/null +++ b/apps/web/src/components/issue/IssueDetailPanel.browser.test.tsx @@ -0,0 +1,94 @@ +import type { IssueDetail } from "@t3tools/contracts"; +import * as AsyncResult from "effect/reactivity/AsyncResult"; +import { describe, expect, it, vi } from "vite-plus/test"; + +import { render } from "../../../test/render"; + +const url = "https://github.com/owner/repo/issues/7"; +const detail = vi.hoisted(() => ({ + tracker: "github", + host: "github.com", + scope: "owner/repo", + key: "7", + displayKey: "#7", + title: "Something is broken", + url: "https://github.com/owner/repo/issues/7", + author: null, + state: { category: "open", name: "Open" }, + createdAt: "2026-01-01T00:00:00.000Z", + updatedAt: "2026-01-01T00:00:00.000Z", + closedAt: null, + assignees: [], + labels: [], + commentCount: 0, + projectId: "project-1", + projectTitle: "Project", + writable: false, + capabilities: { + create: false, + edit: false, + comment: false, + labels: false, + assignees: false, + reactions: false, + templates: false, + linkedPullRequests: false, + events: false, + search: false, + }, + viewerPermissions: { + setState: false, + comment: false, + edit: false, + labels: false, + assignees: false, + }, + states: [], + viewer: null, + body: "", + comments: [], + commentsCursor: null, + events: [], + linkedPullRequests: [], +})) as unknown as IssueDetail; + +const state = vi.hoisted(() => ({ openLink: vi.fn(async () => {}) })); + +vi.mock(import("~/browser/useOpenLink"), () => ({ useOpenLink: () => state.openLink })); +vi.mock(import("./IssueThreadLinks"), () => ({ IssueThreadLinks: (() => null) as never })); +vi.mock(import("~/state/issues"), async (original) => { + const { Atom } = await import("effect/reactivity"); + const actual = await original(); + const detailAtom = Atom.make(AsyncResult.success(detail)); + return { + ...actual, + issueEnvironment: { ...actual.issueEnvironment, detail: (() => detailAtom) as never }, + }; +}); + +import { IssueDetailPanel } from "./IssueDetailPanel"; + +describe("IssueDetailPanel", () => { + it("opens the issue number through the link-target setting, not a popup", async () => { + const threadRef = { environmentId: "env-1", threadId: "thread-1" } as never; + await using screen = await render( + , + ); + const number = screen.getByRole("link", { name: "Open #7 on GitHub" }); + const click = new MouseEvent("click", { bubbles: true, cancelable: true }); + (await number.element()).dispatchEvent(click); + + expect(click.defaultPrevented).toBe(true); + expect(state.openLink).toHaveBeenCalledOnce(); + expect(state.openLink).toHaveBeenCalledWith(url, { event: expect.anything() }); + }); +}); diff --git a/apps/web/src/components/issue/IssueDetailPanel.tsx b/apps/web/src/components/issue/IssueDetailPanel.tsx index 30a55dd1d9e48..38d803e896779 100644 --- a/apps/web/src/components/issue/IssueDetailPanel.tsx +++ b/apps/web/src/components/issue/IssueDetailPanel.tsx @@ -43,6 +43,7 @@ import { m } from "~/i18n/messages"; import { issueEnvironment, refreshIssueLists } from "~/state/issues"; import { useProjects } from "~/state/entities"; import { useEnvironmentQuery } from "~/state/query"; +import { useOpenLink } from "~/browser/useOpenLink"; import { useAtomCommand } from "~/state/use-atom-command"; import { formatRelativeTimeLabel } from "~/timestampFormat"; @@ -443,6 +444,7 @@ export function IssueDetailPanel({ const loadComments = useAtomCommand(issueEnvironment.comments, { reportFailure: false }); const update = useAtomCommand(issueEnvironment.update, { reportFailure: false }); const setState = useAtomCommand(issueEnvironment.setState, { reportFailure: false }); + const openLink = useOpenLink(threadRef); const [editing, setEditing] = useState<"title" | "body" | null>(null); const [titleDraft, setTitleDraft] = useState(""); const [saving, setSaving] = useState(false); @@ -618,6 +620,10 @@ export function IssueDetailPanel({ provider: tracker.providerName, })} render={} + onClick={(event) => { + event.preventDefault(); + void openLink(detail.url, { event }).catch(console.error); + }} > {detail.displayKey} From 261d5a05d096d79e812e278a0597413db8693b9b Mon Sep 17 00:00:00 2001 From: Victor Date: Wed, 25 Nov 2026 07:03:31 -0600 Subject: [PATCH 083/880] fix(server): EPUB glossary entries no longer run together in extracted text (#42816) Co-authored-by: Julius Marminge (cherry picked from commit e849afabb4c1aa600d5c5c33eb51e0fe080a2a4e) --- apps/server/src/provider/documentTextWorker.ts | 2 +- apps/server/src/provider/userInputAttachments.test.ts | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/apps/server/src/provider/documentTextWorker.ts b/apps/server/src/provider/documentTextWorker.ts index 93b875e4ad305..230e5d22c144c 100644 --- a/apps/server/src/provider/documentTextWorker.ts +++ b/apps/server/src/provider/documentTextWorker.ts @@ -254,7 +254,7 @@ function* paragraphs(node: XmlNode): Generator { yield "\n"; } else { yield* paragraphs(child); - if (["li", "div", "section"].includes(child.name)) yield "\n"; + if (["li", "div", "section", "dt", "dd"].includes(child.name)) yield "\n"; } } } diff --git a/apps/server/src/provider/userInputAttachments.test.ts b/apps/server/src/provider/userInputAttachments.test.ts index 0fca878dfb291..6aad293a35ec9 100644 --- a/apps/server/src/provider/userInputAttachments.test.ts +++ b/apps/server/src/provider/userInputAttachments.test.ts @@ -1497,7 +1497,7 @@ describe("question answer paths", () => { "OEBPS/a.xhtml": '

Last chapter

Price 10 8 old

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

First chapter

Larkspur

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

    First chapter

    Larkspur

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

    Привет

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

    Quarterly notes: 中文 𠀀 龦 你 done

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

    中文

    ", + ], ] as const) { const decoded = openRtf(bytes(rtf)); if (decoded.type !== "document") throw new Error("Expected document"); diff --git a/apps/web/src/components/files/extendedDocumentPreview.ts b/apps/web/src/components/files/extendedDocumentPreview.ts index 517e404f0a8c2..75d8c01b4e3f0 100644 --- a/apps/web/src/components/files/extendedDocumentPreview.ts +++ b/apps/web/src/components/files/extendedDocumentPreview.ts @@ -583,6 +583,7 @@ const rtfCodePageLabel = (codePage: number) => 950: "big5", 874: "windows-874", 10000: "macintosh", + 54936: "gb18030", } as Record )[codePage] ?? `windows-${codePage}`; diff --git a/scripts/scenarios/rtf-preview-decodes-gb18030.e2e.ts b/scripts/scenarios/rtf-preview-decodes-gb18030.e2e.ts new file mode 100644 index 0000000000000..8389d1c219bc8 --- /dev/null +++ b/scripts/scenarios/rtf-preview-decodes-gb18030.e2e.ts @@ -0,0 +1,32 @@ +import { expect } from "e2e"; + +import { test, WEB } from "./t3.ts"; + +// A Simplified Chinese RTF saved with the GB18030 code page (\ansicpg54936). +const GB18030_RTF = String.raw`{\rtf1\ansi\ansicpg54936 Quarterly notes: \'d6\'d0\'ce\'c4 \'95\'32\'82\'36 \'82\'35\'8f\'33 \uc2\u20320\'c4\'e3 done\par}`; + +test( + "An RTF preview decodes text saved with the GB18030 code page", + WEB, + async ({ t3, app, screen, browser }) => { + const project = await t3.project("demo", { "notes.rtf": GB18030_RTF }); + const thread = await t3.thread({ project, title: "Review notes", messages: ["Start"] }); + await t3.open(thread); + await screen.getByText("fixture turn complete", { exact: false }).waitFor(); + + await browser.keyboard.press("Control+p"); + await screen.getByPlaceholder("Search files…").fill("notes.rtf"); + await screen.getByRole("option", "notes.rtf", { exact: false }).tap(); + + const document = browser.frameLocator('iframe[title^="notes.rtf"]'); + try { + // The first document preview loads its worker, which a cold Vite cache optimizes on demand. + // List form treats a missing iframe as 0 matches (ASSERTION_FAILED) rather than LOCATOR_NOT_FOUND. + await expect(document.locator("body")).toHaveText(["Quarterly notes: 中文 𠀀 龦 你 done"], { + timeout: 120_000, + }); + } finally { + await app.screenshot("text"); + } + }, +); From 1426d7516b2e281442aba2c1aeeaafcd9d902bb3 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 25 Nov 2026 05:44:25 -0800 Subject: [PATCH 087/880] fix(web): Changes pane explains a diff of only hidden test files (#42851) (cherry picked from commit e3f7eb50856870fa52f5c2864294639a1f0fa2d2) --- .../src/components/DiffPanel.browser.test.tsx | 30 +++++++++++++++++++ apps/web/src/components/DiffPanel.tsx | 14 ++++++++- 2 files changed, 43 insertions(+), 1 deletion(-) diff --git a/apps/web/src/components/DiffPanel.browser.test.tsx b/apps/web/src/components/DiffPanel.browser.test.tsx index 685cac0fc7f62..2e1990b29b63e 100644 --- a/apps/web/src/components/DiffPanel.browser.test.tsx +++ b/apps/web/src/components/DiffPanel.browser.test.tsx @@ -282,6 +282,36 @@ it("opens a repository-relative file from a nested project without a remote", as ).toMatchObject({ activeSurfaceId: "file:back\\slash.txt" }); }); +it("explains a branch diff whose only changes are hidden test files", async () => { + using context = setup("origin/orphan"); + using _hideTestFiles = { + [Symbol.dispose]() { + window.localStorage.removeItem("t3code.diffHideTestFiles"); + }, + }; + const path = "math.test.ts"; + const metadata = preview(); + const source = { + ...metadata.sources[0]!, + files: [{ path, previousPath: null, additions: 1, deletions: 0 }], + }; + state.previews.set("main", Atom.make(AsyncResult.success({ ...metadata, sources: [source] }))); + useDiffPanelStore.getState().selectBranchBaseRef(context.threadRef, "main"); + await using screen = await render( + +
    + +
    +
    , + ); + await expect.element(screen.getByText(path, { exact: true })).toBeVisible(); + await userEvent.click(screen.getByRole("button", { name: "Hide test files", exact: true })); + await expect.element(screen.getByText(path, { exact: true })).not.toBeInTheDocument(); + await expect.element(screen.getByText("1 test file hidden", { exact: true })).toBeVisible(); + await userEvent.click(screen.getByRole("button", { name: "Show test files", exact: true })); + await expect.element(screen.getByText(path, { exact: true })).toBeVisible(); +}); + it.each([false, true])( "expands an unloaded file on the first click with default collapse %s", async (collapsed) => { diff --git a/apps/web/src/components/DiffPanel.tsx b/apps/web/src/components/DiffPanel.tsx index d41a17b890898..cb9f8bf5e89ad 100644 --- a/apps/web/src/components/DiffPanel.tsx +++ b/apps/web/src/components/DiffPanel.tsx @@ -81,7 +81,7 @@ import { DiffFileTree } from "./diffs/DiffFileTree"; import { FileExplorerPane } from "./files/FileExplorerPane"; import { diffFileTreeEntries } from "./diffs/diffFileTree.logic"; import { getDiffHeaderClickAction } from "./diffs/diffHeaderClick"; -import { Button } from "./ui/button"; +import { Button, InlineButton } from "./ui/button"; import { ToggleGroup, Toggle } from "./ui/toggle-group"; import { Switch } from "./ui/switch"; import { @@ -1676,6 +1676,18 @@ export default function DiffPanel({

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

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

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

    - {gt("{count, plural, one {{formatted} sessions} other {{formatted} sessions}}", { + {gt("{count, plural, one {{formatted} session} other {{formatted} sessions}}", { count: merged.sessions, formatted: formatCount(merged.sessions, locale), })} diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 8289ee0dc9764..53ed85b34e994 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -12430,7 +12430,6 @@ "d2d071e45a2d6b89": "Wähle eine Umgebung, um Limits zu sehen.", "c9180daea905a0a6": "Wähle eine Umgebung, um die Nutzung zu sehen.", "f0297ec79e896a13": "{environment}: {error}", - "6dcbf651d51d4023": "{count, plural, one {{formatted} Sitzung} other {{formatted} Sitzungen}}", "b01bf98dd90ee819": "API-Schätzung", "bab34b28e9ee8e88": "Details zur Nutzung ohne Preis", "61571f4542da9903": "{count, plural, one {{formatted} Sitzung} other {{formatted} Sitzungen}}", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index 27bcb58ccc52e..b7e36809cd13b 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -12438,7 +12438,6 @@ "d2d071e45a2d6b89": "Select an environment to see limits.", "c9180daea905a0a6": "Select an environment to see usage.", "f0297ec79e896a13": "{environment}: {error}", - "6dcbf651d51d4023": "{count, plural, one {{formatted} sessions} other {{formatted} sessions}}", "b01bf98dd90ee819": "API estimate", "bab34b28e9ee8e88": "Unpriced usage details", "61571f4542da9903": "{count, plural, one {{formatted} session} other {{formatted} sessions}}", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index ee4af308353a3..cb39fa0e0f465 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -12424,7 +12424,6 @@ "d2d071e45a2d6b89": "Selecciona un entorno para ver los límites.", "c9180daea905a0a6": "Selecciona un entorno para ver el uso.", "f0297ec79e896a13": "{environment}: {error}", - "6dcbf651d51d4023": "{count, plural, one {{formatted} sesión} other {{formatted} sesiones}}", "b01bf98dd90ee819": "Estimación de API", "bab34b28e9ee8e88": "Detalles del uso sin precio", "61571f4542da9903": "{count, plural, one {{formatted} sesión} other {{formatted} sesiones}}", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index 9ca7686394051..48befb5fd11c6 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -12428,7 +12428,6 @@ "d2d071e45a2d6b89": "Sélectionnez un environnement pour voir les limites.", "c9180daea905a0a6": "Sélectionnez un environnement pour voir l’utilisation.", "f0297ec79e896a13": "{environment} : {error}", - "6dcbf651d51d4023": "{count, plural, one {{formatted} session} other {{formatted} sessions}}", "b01bf98dd90ee819": "Estimation API", "bab34b28e9ee8e88": "Détails de l’utilisation sans prix", "61571f4542da9903": "{count, plural, one {{formatted} session} other {{formatted} sessions}}", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index 14528c2e316e6..494c686625dc2 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -12386,7 +12386,6 @@ "d2d071e45a2d6b89": "上限を表示するには環境を選択してください。", "c9180daea905a0a6": "使用量を表示するには環境を選択してください。", "f0297ec79e896a13": "{environment}: {error}", - "6dcbf651d51d4023": "{count, plural, other {{formatted} セッション}}", "b01bf98dd90ee819": "API の推定額", "bab34b28e9ee8e88": "価格不明の使用量の詳細", "61571f4542da9903": "{count, plural, other {{formatted} セッション}}", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index fcf33e90a6b9b..7844faad30cf1 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -12385,7 +12385,6 @@ "d2d071e45a2d6b89": "한도를 보려면 환경을 선택하세요.", "c9180daea905a0a6": "사용량을 보려면 환경을 선택하세요.", "f0297ec79e896a13": "{environment}: {error}", - "6dcbf651d51d4023": "{count, plural, other {세션 {formatted}개}}", "b01bf98dd90ee819": "API 추정치", "bab34b28e9ee8e88": "가격 없는 사용량 세부 정보", "61571f4542da9903": "{count, plural, other {세션 {formatted}개}}", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index 13b1485dfdff0..bd6490414e57f 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -12428,7 +12428,6 @@ "d2d071e45a2d6b89": "Selecione um ambiente para ver os limites.", "c9180daea905a0a6": "Selecione um ambiente para ver o uso.", "f0297ec79e896a13": "{environment}: {error}", - "6dcbf651d51d4023": "{count, plural, one {{formatted} sessão} other {{formatted} sessões}}", "b01bf98dd90ee819": "Estimativa da API", "bab34b28e9ee8e88": "Detalhes do uso sem preço", "61571f4542da9903": "{count, plural, one {{formatted} sessão} other {{formatted} sessões}}", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 0a43af1fb1c37..26c825554341a 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -12430,7 +12430,6 @@ "d2d071e45a2d6b89": "Выберите окружение, чтобы увидеть лимиты.", "c9180daea905a0a6": "Выберите окружение, чтобы увидеть использование.", "f0297ec79e896a13": "{environment}: {error}", - "6dcbf651d51d4023": "{count, plural, one {{formatted} сеанс} few {{formatted} сеанса} many {{formatted} сеансов} other {{formatted} сеанса}}", "b01bf98dd90ee819": "Оценка по API", "bab34b28e9ee8e88": "Подробности использования без цены", "61571f4542da9903": "{count, plural, one {{formatted} сеанс} few {{formatted} сеанса} many {{formatted} сеансов} other {{formatted} сеанса}}", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index 30261f72f4a4d..940f82aa4da4f 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -12437,7 +12437,6 @@ "d2d071e45a2d6b89": "Välj en miljö för att se gränser.", "c9180daea905a0a6": "Välj en miljö för att se användning.", "f0297ec79e896a13": "{environment}: {error}", - "6dcbf651d51d4023": "{count, plural, one {{formatted} session} other {{formatted} sessioner}}", "b01bf98dd90ee819": "API-uppskattning", "bab34b28e9ee8e88": "Detaljer om användning utan pris", "61571f4542da9903": "{count, plural, one {{formatted} session} other {{formatted} sessioner}}", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index 81f1d5cfeb5ce..a7248eebfeaf3 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -12455,7 +12455,6 @@ "d2d071e45a2d6b89": "选择一个环境即可查看限制。", "c9180daea905a0a6": "选择一个环境即可查看用量。", "f0297ec79e896a13": "{environment}:{error}", - "6dcbf651d51d4023": "{count, plural, other {{formatted} 个会话}}", "b01bf98dd90ee819": "API 估算", "bab34b28e9ee8e88": "未定价用量的详情", "61571f4542da9903": "{count, plural, other {{formatted} 个会话}}", From a8301fc77c4ed6a893ef57b38048268edde7fb54 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 25 Nov 2026 06:30:19 -0800 Subject: [PATCH 091/880] fix(desktop): WSL-only backend no longer falls back to Windows when reg.exe is blocked by policy (#42857) (cherry picked from commit 7814c9f884b2baff651c132ce38a077767de138d) --- .../src/wsl/DesktopWslEnvironment.test.ts | 39 ++++++++++++++++++- apps/desktop/src/wsl/DesktopWslEnvironment.ts | 14 +++++-- 2 files changed, 48 insertions(+), 5 deletions(-) diff --git a/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts b/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts index 470091f334fb7..aab0f0b2f8eea 100644 --- a/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts +++ b/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts @@ -557,6 +557,7 @@ describe("parseResolvedPath", () => { const WSL_EXE = "/windows/System32/wsl.exe"; const STORE_SERVICE = "HKLM\\SYSTEM\\CurrentControlSet\\Services\\WSLService"; const INBOX_SERVICE = "HKLM\\SYSTEM\\CurrentControlSet\\Services\\LxssManager"; +const SERVICES_ROOT = "HKLM\\SYSTEM\\CurrentControlSet\\Services"; const registrySpawner = (keys: ReadonlyArray) => ChildProcessSpawner.make((command) => @@ -570,7 +571,7 @@ const registrySpawner = (keys: ReadonlyArray) => ChildProcessSpawner.ExitCode( command._tag === "StandardCommand" && command.command === "reg.exe" && - keys.some((key) => command.args.includes(key)) + [SERVICES_ROOT, ...keys].some((key) => command.args.includes(key)) ? 0 : 1, ), @@ -608,6 +609,42 @@ describe("makeIsAvailable", () => { }), ); + it.effect("keeps WSL when registry tools are disabled by policy and reg.exe cannot answer", () => + Effect.gen(function* () { + const denied = new TextEncoder().encode( + "ERROR: Registry editing has been disabled by your administrator.\r\n", + ); + const blockedRegistry = ChildProcessSpawner.make(() => + Effect.succeed( + ChildProcessSpawner.makeHandle({ + pid: ChildProcessSpawner.ProcessId(1), + stdout: Stream.empty, + stderr: Stream.make(denied), + all: Stream.make(denied), + exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(1)), + isRunning: Effect.succeed(false), + kill: () => Effect.void, + stdin: Sink.drain, + getInputFd: () => Sink.drain, + getOutputFd: () => Stream.empty, + unref: Effect.succeed(Effect.void), + }), + ), + ); + const available = yield* makeIsAvailable("win32", "/windows").pipe( + Effect.provide( + Layer.mergeAll( + FileSystem.layerNoop({ exists: (path) => Effect.succeed(path === WSL_EXE) }), + Path.layer, + DesktopManagedPolicy.layerTest(undefined), + ), + ), + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, blockedRegistry), + ); + assert.isTrue(available); + }), + ); + it.effect("turns WSL off on a machine with a managed policy, even an invalid one", () => Effect.gen(function* () { assert.isTrue(yield* isAvailable()); diff --git a/apps/desktop/src/wsl/DesktopWslEnvironment.ts b/apps/desktop/src/wsl/DesktopWslEnvironment.ts index 54ddc15131c6d..72dc59babfb38 100644 --- a/apps/desktop/src/wsl/DesktopWslEnvironment.ts +++ b/apps/desktop/src/wsl/DesktopWslEnvironment.ts @@ -1124,13 +1124,16 @@ const WSL_SERVICE_KEYS = [ "HKLM\\SYSTEM\\CurrentControlSet\\Services\\WSLService", "HKLM\\SYSTEM\\CurrentControlSet\\Services\\LxssManager", ] as const; +// Always present; when reg.exe cannot read it (e.g. "Prevent access to registry editing tools"), +// a failed service query says nothing about WSL, so fall back to trusting wsl.exe. +const SERVICES_ROOT_KEY = "HKLM\\SYSTEM\\CurrentControlSet\\Services"; const SERVICE_QUERY_TIMEOUT = Duration.seconds(5); const wslServiceRegistered = Effect.scoped( Effect.gen(function* () { const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const registered = yield* Effect.forEach( - WSL_SERVICE_KEYS, + const [rootReadable, ...servicesFound] = yield* Effect.forEach( + [SERVICES_ROOT_KEY, ...WSL_SERVICE_KEYS], (key) => spawner .spawn( @@ -1142,10 +1145,13 @@ const wslServiceRegistered = Effect.scoped( forceKillAfter: PROCESS_TERMINATE_GRACE, }), ) - .pipe(Effect.flatMap((handle) => handle.exitCode)), + .pipe( + Effect.flatMap((handle) => handle.exitCode), + Effect.map((exitCode) => (exitCode as unknown as number) === 0), + ), { concurrency: "unbounded" }, ); - return registered.some((exitCode) => (exitCode as unknown as number) === 0); + return rootReadable === false || servicesFound.includes(true); }), ).pipe( Effect.timeoutOption(SERVICE_QUERY_TIMEOUT), From cf00937750ab164745352bba75f890edb0990a91 Mon Sep 17 00:00:00 2001 From: Pedro Sousa Date: Wed, 25 Nov 2026 15:39:56 +0100 Subject: [PATCH 092/880] fix(github): count team review requests in the Reviewing filter (#42835) Co-authored-by: Pedro Sousa <4235827+pedrosousa13@users.noreply.github.com> Co-authored-by: Julius Marminge (cherry picked from commit 6cca0b18646b172d00fc0d88e2a80021d6b55372) --- .../server/GitHubPullRequestProvider.test.ts | 71 +++++++++++++++++++ .../src/server/GitHubPullRequestProvider.ts | 20 +++++- 2 files changed, 89 insertions(+), 2 deletions(-) diff --git a/packages/source-control-github/src/server/GitHubPullRequestProvider.test.ts b/packages/source-control-github/src/server/GitHubPullRequestProvider.test.ts index 7d305ac4b7873..ad6eab9634315 100644 --- a/packages/source-control-github/src/server/GitHubPullRequestProvider.test.ts +++ b/packages/source-control-github/src/server/GitHubPullRequestProvider.test.ts @@ -967,6 +967,60 @@ describe("loginAvatarUrl", () => { }); }); +describe("listChangeRequests", () => { + it.effect("counts a team review request as the viewer's only on search rows", () => + Effect.gen(function* () { + const teamOnly = { + number: 1, + title: "Change", + url: "https://github.com/acme/web/pull/1", + author: null, + headBranch: "feature", + baseBranch: "main", + state: "open" as const, + isDraft: false, + mergeability: "mergeable" as const, + additions: 0, + deletions: 0, + createdAt: "2026-07-01T00:00:00Z", + updatedAt: "2026-07-02T00:00:00Z", + reviewRequestLogins: ["someone-else"], + hasTeamReviewRequest: true, + labels: [], + reviewDecision: null, + checksState: null, + }; + const list = (continues: boolean, involvement: "all" | "reviewing") => + make.pipe( + Effect.provide( + Layer.mock(GitHubPullRequestApi.GitHubPullRequestApi)({ + listPullRequests: () => + Effect.succeed({ items: [teamOnly], truncated: false, continues }), + }), + ), + Effect.flatMap((provider) => + provider.listChangeRequests({ + cwd: "/w", + host: "github.com", + repository: "acme/web", + state: "open", + involvement, + viewer: "Viewer", + limit: 50, + }), + ), + ); + const searched = yield* list(true, "reviewing"); + expect(searched.items[0]!.reviewRequestLogins).toEqual(["someone-else", "Viewer"]); + const all = yield* list(true, "all"); + expect(all.items[0]!.reviewRequestLogins).toEqual(["someone-else"]); + // The listing fallback keeps any team's request; it cannot say the team is the viewer's. + const listed = yield* list(false, "reviewing"); + expect(listed.items[0]!.reviewRequestLogins).toEqual(["someone-else"]); + }), + ); +}); + describe("listChangeRequestsAcross", () => { const searched = (repository: string): GitHubPullRequestSearchItem => ({ repository, @@ -1082,6 +1136,23 @@ describe("listChangeRequestsAcross", () => { }), ); + it.effect("counts a review requested from the viewer's team as requested from the viewer", () => + Effect.gen(function* () { + const teamOnly = { ...searched("acme/web"), hasTeamReviewRequest: true }; + const read = yield* providerAnswering({ + pages: [ + { items: [teamOnly], truncated: false }, + { items: [teamOnly], truncated: false }, + ], + covered: () => true, + }); + const reviewing = yield* read({ ...across, involvement: "reviewing" }); + expect(reviewing.items[0]!.reviewRequestLogins).toEqual(["viewer"]); + const all = yield* read(across); + expect(all.items[0]!.reviewRequestLogins).toEqual([]); + }), + ); + it.effect("past the first slice, believes a covered repository and not an uncovered one", () => Effect.gen(function* () { const read = yield* providerAnswering({ diff --git a/packages/source-control-github/src/server/GitHubPullRequestProvider.ts b/packages/source-control-github/src/server/GitHubPullRequestProvider.ts index 88dcc1aea2ed9..19e894eb308e0 100644 --- a/packages/source-control-github/src/server/GitHubPullRequestProvider.ts +++ b/packages/source-control-github/src/server/GitHubPullRequestProvider.ts @@ -32,6 +32,22 @@ import type { } from "./gitHubPullRequestJson.ts"; import { definition } from "../shared/definition.ts"; +/** + * `review-requested:` search rows include the viewer's team requests, which name no login, + * so record the viewer as requested. Search rows only: the listing fallback cannot tell whether the + * viewer belongs to a requested team. + */ +function withViewerRequested }>( + item: T, + input: { readonly involvement: string; readonly viewer: string }, +): T { + const viewer = input.viewer.toLowerCase(); + return input.involvement === "reviewing" && + !item.reviewRequestLogins.some((login) => login.toLowerCase() === viewer) + ? { ...item, reviewRequestLogins: [...item.reviewRequestLogins, input.viewer] } + : item; +} + const CAPABILITIES: PullRequestCapabilities = { diff: true, comment: true, @@ -434,7 +450,7 @@ export const make = Effect.gen(function* () { Effect.map((page) => ({ ...page, items: page.items.map((item) => ({ - ...item, + ...(page.continues ? withViewerRequested(item, input) : item), author: withAvatar(item.author, new Map(), input.host), })), })), @@ -460,7 +476,7 @@ export const make = Effect.gen(function* () { Effect.map(unresolvedBySearch(input, batch), (unresolved) => ({ truncated: batch.truncated, items: batch.items.map((item) => ({ - ...item, + ...withViewerRequested(item, input), author: withAvatar(item.author, new Map(), input.host), })), unresolved, From 1cf0879c88d5b25d9865521f4f7ffc2115506d5a Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 25 Nov 2026 06:42:29 -0800 Subject: [PATCH 093/880] perf(web): Files panel Refresh reads only the folders on screen (#42870) (cherry picked from commit 9de5a941eaa42914da08984220daaccb2d971ad2) --- .../files/FileBrowserPanel.browser.test.tsx | 8 +++ .../src/components/files/FileBrowserPanel.tsx | 24 ++++++--- .../files/fileTreeExpansion.test.ts | 10 ++++ .../src/components/files/fileTreeExpansion.ts | 16 +++++- .../useDirectoryEntries.browser.test.tsx | 42 +++++++++++++++- .../components/files/useDirectoryEntries.ts | 49 ++++++++++++++++--- 6 files changed, 131 insertions(+), 18 deletions(-) create mode 100644 apps/web/src/components/files/fileTreeExpansion.test.ts diff --git a/apps/web/src/components/files/FileBrowserPanel.browser.test.tsx b/apps/web/src/components/files/FileBrowserPanel.browser.test.tsx index 2a1f16b31070b..ecf51be124491 100644 --- a/apps/web/src/components/files/FileBrowserPanel.browser.test.tsx +++ b/apps/web/src/components/files/FileBrowserPanel.browser.test.tsx @@ -20,6 +20,7 @@ const directory: { entries: readonly ProjectEntry[]; load: () => Promise; refresh: () => void; + revalidate: (directoryPath: string) => void; ready: boolean; error: null; isPending: boolean; @@ -28,6 +29,7 @@ const directory: { entries, load: () => Promise.resolve(), refresh: () => {}, + revalidate: () => {}, ready: true, error: null, isPending: false, @@ -365,9 +367,15 @@ describe("FileBrowserPanel", () => { ); } + using revalidate = vi.spyOn(directory, "revalidate"); await using _second = await render(panel()); await vi.waitFor(() => expect(findTreeRow("src/")).not.toBeNull()); await vi.waitFor(() => expect(findTreeRow("src/")!.getAttribute("aria-expanded")).toBe("true")); + + // Refresh revalidates the folders behind the rows on screen: the open one and the root. + revalidate.mockClear(); + await userEvent.click(page.getByRole("button", { name: "Refresh workspace files" })); + expect(revalidate.mock.calls).toEqual([["src"], [""]]); }); describe("revealing a folder while folders above it are still loading", () => { const roots = Array.from({ length: 12 }, (_, index): ProjectEntry => { diff --git a/apps/web/src/components/files/FileBrowserPanel.tsx b/apps/web/src/components/files/FileBrowserPanel.tsx index 4609a8bacd089..03c6d30972b34 100644 --- a/apps/web/src/components/files/FileBrowserPanel.tsx +++ b/apps/web/src/components/files/FileBrowserPanel.tsx @@ -188,6 +188,7 @@ export default function FileBrowserPanel({ entries: directoryEntries, load, refresh, + revalidate, ready, error, isPending, @@ -300,6 +301,7 @@ export default function FileBrowserPanel({ ); const loadingDirectoriesRef = useRef(loadingDirectories); + const revalidateDirectory = useStableCallback(revalidate); const dragMention = createFileTreeDragMentionController( hostFolder ? { mentionPath: (path: string) => joinHostPath(cwd, path) } : {}, ); @@ -332,12 +334,15 @@ export default function FileBrowserPanel({ } }, paths: [], - renderRowDecoration: ({ item, row }) => - row.kind === "directory" && - row.isExpanded && - loadingDirectoriesRef.current.has(item.path.replace(/\/$/, "")) + renderRowDecoration: ({ item, row }) => { + const path = item.path.replace(/\/$/, ""); + const open = row.kind === "directory" && row.isExpanded; + // Pierre calls this for the rows it renders, which is the only sign of what is on screen. + revalidateDirectory(open ? path : path.slice(0, Math.max(0, path.lastIndexOf("/")))); + return open && loadingDirectoriesRef.current.has(path) ? { icon: "t3-tree-icon-loading", title: gt("Loading…") } - : null, + : null; + }, search: false, onSearchChange: (value) => setQuery(value ?? ""), unsafeCSS: PIERRE_TREE_UNSAFE_CSS, @@ -452,15 +457,20 @@ export default function FileBrowserPanel({ } search.setValue(value); }; - const handleRefresh = () => { + const refreshDirectories = () => { refresh(); + // Renders the rows again, so each one on screen revalidates the folders it comes from. + model.setComposition(model.getComposition()); + }; + const handleRefresh = () => { + refreshDirectories(); if (query.trim()) pathSearch.refresh(); onRefreshSelectedFile?.(); }; useWorkspaceMutationRefresh({ mutationId: workspaceMutationId, refresh: () => { - refresh(); + refreshDirectories(); if (query.trim()) pathSearch.refresh(); }, resourceKey: `files:${environmentId}:${cwd}`, diff --git a/apps/web/src/components/files/fileTreeExpansion.test.ts b/apps/web/src/components/files/fileTreeExpansion.test.ts new file mode 100644 index 0000000000000..6d8ea1a883b9a --- /dev/null +++ b/apps/web/src/components/files/fileTreeExpansion.test.ts @@ -0,0 +1,10 @@ +import { expect, it } from "vite-plus/test"; + +import { readExpandedDirectories, writeExpandedDirectories } from "./fileTreeExpansion"; + +it("keeps the 100 expanded folders nearest the root, so a remount does not list hundreds", () => { + const deep = Array.from({ length: 150 }, (_, index) => `pkg/mod/d${index}/`); + writeExpandedDirectories("env:/repo", [...deep, "pkg/mod/", "pkg/"]); + const restored = readExpandedDirectories("env:/repo"); + expect(restored).toEqual(["pkg/", "pkg/mod/", ...deep.slice(0, 98)]); +}); diff --git a/apps/web/src/components/files/fileTreeExpansion.ts b/apps/web/src/components/files/fileTreeExpansion.ts index 35e6a548603ee..f7055bd1e1b08 100644 --- a/apps/web/src/components/files/fileTreeExpansion.ts +++ b/apps/web/src/components/files/fileTreeExpansion.ts @@ -106,6 +106,8 @@ export function coalesceReentrantCalls(run: () => void): () => void { const EXPANDED_DIRECTORIES_STORAGE_KEY = "t3code.fileTreeExpandedDirectories"; // Roots are kept most recent first and capped so worktrees that come and go do not grow storage. const MAX_STORED_ROOTS = 20; +// Every restored folder is listed when the panel mounts, so a root keeps the folders nearest it. +const MAX_STORED_PATHS_PER_ROOT = 100; const StoredExpandedDirectories = Schema.Array( Schema.Struct({ root: Schema.String, paths: Schema.Array(Schema.String) }), ); @@ -119,13 +121,23 @@ function readStoredExpandedDirectories() { } } +function nearestToRoot(paths: readonly string[]): readonly string[] { + if (paths.length <= MAX_STORED_PATHS_PER_ROOT) return paths; + const depth = (path: string) => path.split("/").length; + return paths + .toSorted((left, right) => depth(left) - depth(right)) + .slice(0, MAX_STORED_PATHS_PER_ROOT); +} + export function readExpandedDirectories(root: string): readonly string[] { - return readStoredExpandedDirectories().find((entry) => entry.root === root)?.paths ?? []; + return nearestToRoot( + readStoredExpandedDirectories().find((entry) => entry.root === root)?.paths ?? [], + ); } export function writeExpandedDirectories(root: string, paths: readonly string[]): void { const others = readStoredExpandedDirectories().filter((entry) => entry.root !== root); - const next = paths.length > 0 ? [{ root, paths }, ...others] : others; + const next = paths.length > 0 ? [{ root, paths: nearestToRoot(paths) }, ...others] : others; try { setLocalStorageItem( EXPANDED_DIRECTORIES_STORAGE_KEY, diff --git a/apps/web/src/components/files/useDirectoryEntries.browser.test.tsx b/apps/web/src/components/files/useDirectoryEntries.browser.test.tsx index 694004d0a044d..cee9a88148050 100644 --- a/apps/web/src/components/files/useDirectoryEntries.browser.test.tsx +++ b/apps/web/src/components/files/useDirectoryEntries.browser.test.tsx @@ -188,11 +188,15 @@ it("retains the four-query concurrency bound across directories and refreshes", expect(state.activeQueries).toBe(0); const refreshStart = state.calls.length; state.resetPeakQueries(); - await act(async () => state.view.refresh()); + const refreshOnScreen = () => { + state.view.refresh(); + for (const folder of folders) state.view.revalidate(folder.path); + }; + await act(async () => refreshOnScreen()); expect(state.peakQueries).toBe(4); expect(state.activeQueries).toBe(4); await act(async () => { - for (let index = 0; index < 20; index++) state.view.refresh(); + for (let index = 0; index < 20; index++) refreshOnScreen(); }); for (let index = refreshStart; index < state.calls.length; index++) { await state.settle(index, state.calls[index]!.path === "" ? folders : []); @@ -206,6 +210,40 @@ it("retains the four-query concurrency bound across directories and refreshes", expect(state.view.isPending).toBe(false); }); +it("refreshes the root, and another folder only once one of its rows is on screen", async () => { + const state = setup(); + // The hook probe does not navigate. + await using _screen = await render(, { router: false }); + const folders = ["src", "src/ui", "docs"].map((path) => ({ path, kind: "directory" as const })); + const listing = (path: string) => + folders.filter((folder) => folder.path.slice(0, folder.path.lastIndexOf("/") + 1) === path); + await state.settle(0, listing("")); + await act(async () => { + for (const folder of folders) void state.view.load(folder.path); + }); + await state.settle(1, listing("src/")); + await state.settle(2); + await state.settle(3); + + await act(async () => { + state.view.refresh(); + state.view.refresh(); + }); + expect(state.calls.slice(4).map((call) => call.path)).toEqual([""]); + await act(async () => { + state.view.revalidate("src/ui"); + state.view.revalidate("src/ui"); + }); + expect(state.calls.slice(4).map((call) => call.path)).toEqual(["", "src/ui", "src"]); + await state.settle(4, listing("")); + await state.settle(5); + await state.settle(6, listing("src/")); + await state.settle(7, listing("")); + expect(state.calls).toHaveLength(8); // The second refresh reads the root once more; `docs` is never read. + expect(state.view.entries.map((entry) => entry.path)).toEqual(["src", "src/ui", "docs"]); + expect(state.view.isPending).toBe(false); +}); + it("does not start a queued follow-up after unmount", async () => { const state = setup(); // The hook probe does not navigate. diff --git a/apps/web/src/components/files/useDirectoryEntries.ts b/apps/web/src/components/files/useDirectoryEntries.ts index fc3a984c4788a..ce210315d073c 100644 --- a/apps/web/src/components/files/useDirectoryEntries.ts +++ b/apps/web/src/components/files/useDirectoryEntries.ts @@ -25,6 +25,8 @@ export function useDirectoryEntries(environmentId: EnvironmentId, cwd: string) { const followUpRefreshes = useRef(new Map>()); const loaded = useRef(new Set()); const requested = useRef(new Set()); + // Listed folders a refresh has not read again yet. `revalidate` reads one once it is on screen. + const stale = useRef(new Set()); const active = useRef(true); const running = useRef(0); const waiting = useRef void>>([]); @@ -32,6 +34,7 @@ export function useDirectoryEntries(environmentId: EnvironmentId, cwd: string) { const startRequest = (directoryPath: string, refresh: boolean): Promise => { loaded.current.add(directoryPath); requested.current.add(directoryPath); + stale.current.delete(directoryPath); const atom = projectEnvironment.listEntries({ environmentId, input: { cwd, directoryPath } }); const detached = detachedRequests.current.get(directoryPath); const request = (async () => { @@ -59,6 +62,7 @@ export function useDirectoryEntries(environmentId: EnvironmentId, cwd: string) { (entry) => entry.path.slice(0, Math.max(0, entry.path.lastIndexOf("/"))) === directoryPath, ); + const listed = listings.current.get(directoryPath); const next = new Map(listings.current).set(directoryPath, children); const childDirectories = new Set( children.filter((entry) => entry.kind === "directory").map((entry) => entry.path), @@ -73,13 +77,28 @@ export function useDirectoryEntries(environmentId: EnvironmentId, cwd: string) { next.delete(path); loaded.current.delete(path); requested.current.delete(path); + stale.current.delete(path); const detachedRequest = requests.current.get(path); if (detachedRequest) detachedRequests.current.set(path, detachedRequest); requests.current.delete(path); followUpRefreshes.current.delete(path); } - listings.current = next; - setDirectories(next); + // A refresh that finds a folder as it was publishes nothing, so the tree is not rebuilt. + const unchanged = + removed.length === 0 && + listed?.length === children.length && + children.every((entry, index) => { + const known = listed[index]!; + return ( + entry.path === known.path && + entry.kind === known.kind && + entry.ignored === known.ignored + ); + }); + if (!unchanged) { + listings.current = next; + setDirectories(next); + } if (removed.length > 0) setLoadingDirectories((previous) => { const remaining = new Set(previous); @@ -87,8 +106,10 @@ export function useDirectoryEntries(environmentId: EnvironmentId, cwd: string) { return remaining; }); setErrors((previous) => { + const cleared = [directoryPath, ...removed].filter((path) => previous.has(path)); + if (cleared.length === 0) return previous; const remaining = new Map(previous); - for (const path of [directoryPath, ...removed]) remaining.delete(path); + for (const path of cleared) remaining.delete(path); return remaining; }); } else { @@ -174,11 +195,24 @@ export function useDirectoryEntries(environmentId: EnvironmentId, cwd: string) { ...entries.filter((entry) => entry.kind === "directory").map((entry) => entry.path), ]); + // Reads the root again and leaves every other listed folder to `revalidate`, so a refresh costs + // what is on screen rather than every folder the tree has listed. const refresh = () => { - const paths = [...requested.current].filter((path) => reachableDirectories.has(path)); - for (const path of paths) { - if (!active.current) break; - void load(path, true); + if (!active.current) return; + for (const path of requested.current) if (path !== "") stale.current.add(path); + void load("", true); + }; + + /** Reads again the stale listings that put a row on screen: `directoryPath` and its ancestors. */ + const revalidate = (directoryPath: string) => { + if (!active.current) return; + for ( + let end = directoryPath.length; + end > 0 && stale.current.size > 0; + end = directoryPath.lastIndexOf("/", end - 1) + ) { + const path = directoryPath.slice(0, end); + if (stale.current.delete(path)) void load(path, true); } }; @@ -186,6 +220,7 @@ export function useDirectoryEntries(environmentId: EnvironmentId, cwd: string) { entries, load, refresh, + revalidate, isPending: pending > 0, loadingDirectories, ready: directories.has(""), From 8bd0763b90c6348c34bd4374071b29bce3761356 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 25 Nov 2026 06:46:10 -0800 Subject: [PATCH 094/880] fix(mobile): / menu ranks an exact skill name above description matches (#42879) (cherry picked from commit 9301770ae9e595a65e23d83702b86121c380e919) --- .../threads/composerSlashSkillSearch.ts | 47 ++++++++++++++++--- .../use-composer-command-menu.select.test.tsx | 43 +++++++++++++++++ .../threads/use-composer-command-menu.ts | 10 ++-- 3 files changed, 91 insertions(+), 9 deletions(-) diff --git a/apps/mobile/src/features/threads/composerSlashSkillSearch.ts b/apps/mobile/src/features/threads/composerSlashSkillSearch.ts index 7cd81f036fdd4..ed6ff7ae909ec 100644 --- a/apps/mobile/src/features/threads/composerSlashSkillSearch.ts +++ b/apps/mobile/src/features/threads/composerSlashSkillSearch.ts @@ -1,7 +1,9 @@ import type { ServerProviderSkill } from "@t3tools/contracts"; +import { scoreQueryMatch } from "@t3tools/shared/searchRanking"; -export function matchesSlashSkillQuery(skill: ServerProviderSkill, query: string): boolean { - if (!skill.enabled) return false; +/** Lower is better; `null` when the skill does not match. */ +export function scoreSlashSkillQuery(skill: ServerProviderSkill, query: string): number | null { + if (!skill.enabled) return null; const normalizedQuery = query.toLowerCase(); const skillQuery = normalizedQuery === "skill" @@ -9,8 +11,41 @@ export function matchesSlashSkillQuery(skill: ServerProviderSkill, query: string : normalizedQuery.startsWith("skill:") ? normalizedQuery.slice("skill:".length) : normalizedQuery; - if (!skillQuery) return true; - return [skill.name, skill.displayName, skill.shortDescription, skill.description].some((value) => - value?.toLowerCase().includes(skillQuery), - ); + if (!skillQuery) return 0; + const scores = [ + scoreQueryMatch({ + value: skill.name.toLowerCase(), + query: skillQuery, + exactBase: 0, + prefixBase: 2, + boundaryBase: 4, + includesBase: 6, + boundaryMarkers: ["-", "_", "/"], + }), + scoreQueryMatch({ + value: skill.displayName?.toLowerCase() ?? "", + query: skillQuery, + exactBase: 1, + prefixBase: 3, + boundaryBase: 5, + includesBase: 7, + }), + scoreQueryMatch({ + value: skill.shortDescription?.toLowerCase() ?? "", + query: skillQuery, + exactBase: 20, + prefixBase: 22, + boundaryBase: 24, + includesBase: 26, + }), + scoreQueryMatch({ + value: skill.description?.toLowerCase() ?? "", + query: skillQuery, + exactBase: 30, + prefixBase: 32, + boundaryBase: 34, + includesBase: 36, + }), + ].filter((score): score is number => score !== null); + return scores.length > 0 ? Math.min(...scores) : null; } diff --git a/apps/mobile/src/features/threads/use-composer-command-menu.select.test.tsx b/apps/mobile/src/features/threads/use-composer-command-menu.select.test.tsx index 395961bd91ec7..21e5a88f82fdb 100644 --- a/apps/mobile/src/features/threads/use-composer-command-menu.select.test.tsx +++ b/apps/mobile/src/features/threads/use-composer-command-menu.select.test.tsx @@ -53,3 +53,46 @@ it("/model clears only its trigger and opens the model picker", async () => { expect(onChangeDraftMessage).toHaveBeenCalledWith("fix this "); act(() => root.unmount()); }); + +it("/ ranks a skill whose name matches exactly above skills that only mention it", async () => { + (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + const skill = (name: string, description: string) => ({ + name, + description, + path: `/skills/${name}/SKILL.md`, + enabled: true, + }); + const provider = { + instanceId: "codex", + driver: "codex", + slashCommands: [], + skills: [ + skill("lint", "Run lint before review"), + skill("ship", "Open a pull request after review"), + skill("review", "Review the current diff"), + ], + } as unknown as NonNullable< + Parameters[0]["selectedProviderStatus"] + >; + let menu: ReturnType | undefined; + function Probe() { + menu = useComposerCommandMenu({ + draftMessage: "/review", + ownerKey: "draft", + environmentId: null, + projectCwd: null, + selectedProviderStatus: provider, + hasThread: true, + hasCompactableConversation: false, + onChangeDraftMessage: vi.fn(), + onOpenModelPicker: vi.fn(), + }); + return null; + } + + const root = createRoot(document.createElement("div")); + await act(async () => root.render()); + + expect(menu?.items[0]?.id).toBe("skill:review"); + act(() => root.unmount()); +}); diff --git a/apps/mobile/src/features/threads/use-composer-command-menu.ts b/apps/mobile/src/features/threads/use-composer-command-menu.ts index b5b6ce681c018..3fa3e9d8860b0 100644 --- a/apps/mobile/src/features/threads/use-composer-command-menu.ts +++ b/apps/mobile/src/features/threads/use-composer-command-menu.ts @@ -68,7 +68,7 @@ import { import type { ModelOption } from "../../lib/modelOptions"; import { m, type MessageResolver } from "../../i18n/messages"; import type { ComposerCommandItem } from "./ComposerCommandPopover"; -import { matchesSlashSkillQuery } from "./composerSlashSkillSearch"; +import { scoreSlashSkillQuery } from "./composerSlashSkillSearch"; const idleWorkspaceSnapshotRefreshAtom: Atom.Atom = Atom.make(undefined).pipe( Atom.withLabel("mobile:provider-workspace-snapshot-refresh:idle"), @@ -422,8 +422,12 @@ export function useComposerCommandMenu({ ); const skillItems = visibleSkills - .filter((skill) => matchesSlashSkillQuery(skill, q)) - .map((skill) => ({ + .flatMap((skill) => { + const score = scoreSlashSkillQuery(skill, q); + return score === null ? [] : [{ skill, score }]; + }) + .sort((left, right) => left.score - right.score) + .map(({ skill }) => ({ id: `skill:${skill.name}`, type: "skill" as const, skill, From 2848f9a65219eb3b55a8c3e38d4cd71b6f3fe921 Mon Sep 17 00:00:00 2001 From: Victor Date: Wed, 25 Nov 2026 08:51:24 -0600 Subject: [PATCH 095/880] fix(web,mobile): mixed add/delete review selections no longer show backwards line ranges (#42863) Co-authored-by: Julius Marminge (cherry picked from commit b61af8a5d2af5e514674bd85fe5a62e4ea8f9918) --- .../review/ReviewCommentComposerSheet.tsx | 2 +- .../review/reviewCommentSelection.test.ts | 35 +++++++++++++++ .../features/review/reviewCommentSelection.ts | 2 +- apps/web/src/reviewCommentContext.test.ts | 45 +++++++++++++++++++ apps/web/src/reviewCommentContext.ts | 2 +- 5 files changed, 83 insertions(+), 3 deletions(-) diff --git a/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx b/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx index bbb40e82a50a8..ec253f07704e5 100644 --- a/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx +++ b/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx @@ -100,7 +100,7 @@ export function ReviewCommentComposerSheet(props: ReviewCommentComposerSheetProp ? firstNumber !== null ? gt("Line {line}", { line: firstNumber }) : gt("File comment") - : firstNumber !== null && lastNumber !== null + : firstNumber !== null && lastNumber !== null && firstNumber < lastNumber ? gt("Lines {first}-{last}", { first: firstNumber, last: lastNumber }) : gt("{count, plural, one {{count} lines selected} other {{count} lines selected}}", { count: selectedLines.length, diff --git a/apps/mobile/src/features/review/reviewCommentSelection.test.ts b/apps/mobile/src/features/review/reviewCommentSelection.test.ts index 81eb0bba4083a..e5c3e17e92e59 100644 --- a/apps/mobile/src/features/review/reviewCommentSelection.test.ts +++ b/apps/mobile/src/features/review/reviewCommentSelection.test.ts @@ -8,6 +8,7 @@ import { clearReviewCommentTarget, completeReviewCommentRange, formatReviewCommentContext, + formatReviewSelectedRangeLabel, getReviewCommentSelection, reviewCommentSelectionScope, selectReviewCommentSelection, @@ -224,6 +225,40 @@ describe("review comment serialization", () => { }); }); +describe("review selected range label", () => { + it("falls back to line count when unified endpoints decrease across old and new numbers", () => { + expect( + formatReviewSelectedRangeLabel({ + ...makeTarget(), + lines: [ + { + kind: "line", + id: "line-1", + change: "context", + oldLineNumber: 10, + newLineNumber: 13, + content: "line 10 of the original file", + additionTokenIndex: null, + deletionTokenIndex: null, + comparison: null, + }, + { + kind: "line", + id: "line-2", + change: "delete", + oldLineNumber: 11, + newLineNumber: null, + content: "line 11 of the original file", + additionTokenIndex: null, + deletionTokenIndex: 0, + comparison: null, + }, + ], + }), + ).toBe("2 lines"); + }); +}); + describe("review comment selection store", () => { const changes = { id: "git:branch-range", content: "hash-1" }; const scope = reviewCommentSelectionScope(1, "env:thread", changes)!; diff --git a/apps/mobile/src/features/review/reviewCommentSelection.ts b/apps/mobile/src/features/review/reviewCommentSelection.ts index b5f852331acec..741f330375d3f 100644 --- a/apps/mobile/src/features/review/reviewCommentSelection.ts +++ b/apps/mobile/src/features/review/reviewCommentSelection.ts @@ -212,7 +212,7 @@ export function formatReviewSelectedRangeLabel(target: ReviewCommentTarget): str const firstNumber = getReviewUnifiedLineNumber(firstLine); const lastNumber = getReviewUnifiedLineNumber(lastLine); - if (firstNumber === null || lastNumber === null) { + if (firstNumber === null || lastNumber === null || firstNumber > lastNumber) { return lines.length === 1 ? "line" : `${lines.length} lines`; } diff --git a/apps/web/src/reviewCommentContext.test.ts b/apps/web/src/reviewCommentContext.test.ts index a92e3c7ceb5df..486b77248dfce 100644 --- a/apps/web/src/reviewCommentContext.test.ts +++ b/apps/web/src/reviewCommentContext.test.ts @@ -85,6 +85,51 @@ describe("review comment context parsing", () => { expect(new Set(ids).size).toBe(ids.length); }); + it("falls back to a line-count label when mixed diff-side line numbers decrease", () => { + const [fileDiff] = parsePatchFiles( + [ + "diff --git a/notes.txt b/notes.txt", + "--- a/notes.txt", + "+++ b/notes.txt", + "@@ -1,3 +1,6 @@", + "+added A", + "+added B", + "+added C", + " line 1", + " line 2", + " line 3", + "@@ -8,4 +11,3 @@", + " line 8", + " line 9", + " line 10", + "-line 11", + ].join("\n"), + { cacheKeyPrefix: "review-comment-test" }, + )[0]!.files; + + const comment = buildDiffReviewComment({ + id: "comment-inverted", + sectionId: "turn:2", + sectionTitle: "Turn 2", + filePath: "notes.txt", + fileDiff: fileDiff!, + range: { + start: 13, + side: "additions", + end: 11, + endSide: "deletions", + }, + text: "Check this deletion.", + }); + + expect(comment).toEqual( + expect.objectContaining({ + rangeLabel: "2 lines", + diff: "@@ -10,2 +13,1 @@\n line 10\n-line 11", + }), + ); + }); + it("keeps a selection's trailing blank line and whitespace in the rendered excerpt", () => { const fileDiff = parsePatchFiles( [ diff --git a/apps/web/src/reviewCommentContext.ts b/apps/web/src/reviewCommentContext.ts index 81b51fd7a1bf7..a4f3f93e51053 100644 --- a/apps/web/src/reviewCommentContext.ts +++ b/apps/web/src/reviewCommentContext.ts @@ -440,7 +440,7 @@ function formatDiffReviewRangeLabel(lines: ReadonlyArray): strin if (!firstLine || !lastLine) return "line"; const firstNumber = firstLine.newLineNumber ?? firstLine.oldLineNumber; const lastNumber = lastLine.newLineNumber ?? lastLine.oldLineNumber; - if (firstNumber === null || lastNumber === null) { + if (firstNumber === null || lastNumber === null || firstNumber > lastNumber) { return lines.length === 1 ? "line" : `${lines.length} lines`; } From a6fc6d6b8b2219be1b4397105cbe18077d9c3b83 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 25 Nov 2026 07:33:57 -0800 Subject: [PATCH 096/880] fix(web): web search result links follow Open links in (#42882) (cherry picked from commit e045a127e783c41b7ed91fcbc1d17810c7b8c459) --- .../chat/MessagesTimeline.browser.test.tsx | 57 +++++++++++++++++++ .../src/components/chat/V2ItemInspector.tsx | 56 +++++++++++++++--- 2 files changed, 106 insertions(+), 7 deletions(-) diff --git a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx index e21246e19c2be..bfb2fec35a1b2 100644 --- a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx @@ -29,6 +29,7 @@ import { import * as DateTime from "effect/DateTime"; import { Atom, AsyncResult } from "effect/reactivity"; import { describe, expect, it, onTestFinished, vi } from "vite-plus/test"; +import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings"; import "~/index.css"; @@ -54,6 +55,7 @@ import { searchableMessageSegments } from "@t3tools/shared/threadFindText"; import { countThreadSearchOccurrences } from "@t3tools/shared/threadSearch"; import { collectThreadFindRanges } from "./threadFindHighlights"; import { toastManager } from "../ui/toast"; +import { __setClientSettingsForTests } from "../../hooks/useSettings"; import type { CitedHistory } from "./citationProcedure"; import type { TimelineNavigation } from "./timelineViewport"; import { rememberTimelinePosition } from "./timelineScrollAnchoring"; @@ -98,6 +100,26 @@ vi.mock(import("~/assets/assetUrls"), async (original) => { }; }); +const previewAccess = vi.hoisted(() => ({ granted: false })); +vi.mock(import("~/browser/previewRuntime"), async (original) => { + const actual = await original(); + return { + ...actual, + isPreviewAvailableFor: ((...args) => + previewAccess.granted || + actual.isPreviewAvailableFor(...args)) as typeof actual.isPreviewAvailableFor, + }; +}); +vi.mock(import("~/state/session"), async (original) => { + const actual = await original(); + return { + ...actual, + readEnvironmentScope: ((...args) => + previewAccess.granted || + actual.readEnvironmentScope(...args)) as typeof actual.readEnvironmentScope, + }; +}); + const ENVIRONMENT_ID = EnvironmentId.make("environment-local"); const CREATED_AT = "2026-03-17T19:12:28.000Z"; @@ -481,6 +503,41 @@ describe("MessagesTimeline work rows", () => { expect(output!.closest('[role="button"]')).toBeNull(); expect(document.getElementById(toggle.getAttribute("aria-controls") ?? "")).toContain(output); }); + it("opens a web search result in the thread's Browser when links open in T3 Code", async () => { + setup(); + previewAccess.granted = true; + __setClientSettingsForTests({ ...DEFAULT_CLIENT_SETTINGS, browserLinkTarget: "app" }); + onTestFinished(() => { + previewAccess.granted = false; + __setClientSettingsForTests(DEFAULT_CLIENT_SETTINGS); + }); + await using screen = await renderTimeline([ + work("web-search", { + label: "https://example.com/", + tone: "tool", + itemType: "web_search", + projectedItem: v2Item("web_search", { + id: "web-search", + patterns: ["https://example.com/"], + results: [{ url: "https://example.com/", title: "Example Domain" }], + }), + }), + ]); + await click(screen.button("Web search")); + const link = [...screen.container.querySelectorAll("a")].find( + (anchor) => anchor.textContent === "Example Domain", + ); + expect(link).toBeDefined(); + // A _blank click the app leaves to the browser goes to Electron's popup handler, which + // sends it to the system browser. + let followedNatively = true; + await act(async () => { + followedNatively = link!.dispatchEvent( + new MouseEvent("click", { bubbles: true, cancelable: true, button: 0 }), + ); + }); + expect(followedNatively).toBe(false); + }); }); describe("MessagesTimeline messages", () => { diff --git a/apps/web/src/components/chat/V2ItemInspector.tsx b/apps/web/src/components/chat/V2ItemInspector.tsx index f1cea52d8bd8a..82009fca19092 100644 --- a/apps/web/src/components/chat/V2ItemInspector.tsx +++ b/apps/web/src/components/chat/V2ItemInspector.tsx @@ -1,6 +1,10 @@ import { T, Var, useGT } from "gt-react"; import type { ToolCallDiffTarget } from "../../diffPanelStore"; -import type { EnvironmentId, OrchestrationV2ProjectedTurnItem } from "@t3tools/contracts"; +import type { + EnvironmentId, + OrchestrationV2ProjectedTurnItem, + ScopedThreadRef, +} from "@t3tools/contracts"; import { isJsonToolText, toolCallLines, @@ -14,6 +18,9 @@ import { isJavaScriptReplTool } from "@t3tools/shared/toolActivity"; import { ExternalLinkIcon } from "lucide-react"; import { memo, type ReactNode, Suspense, use } from "react"; +import { canOpenLinksInApp, resolveLinkTarget } from "../../browser/browserLinkTarget"; +import { useOpenLink } from "../../browser/useOpenLink"; +import { useClientSettings } from "../../hooks/useSettings"; import { useRenderedAppearance } from "../../hooks/useTheme"; import { cn } from "../../lib/utils"; import { resolveDiffThemeName } from "../../lib/diffRendering"; @@ -196,6 +203,41 @@ export function FetchedToolOutput(props: { ); } +function WebSearchResultLink(props: { + readonly href: string; + readonly threadRef: ScopedThreadRef; + readonly children: ReactNode; +}) { + const openLink = useOpenLink(props.threadRef); + // Subscribe so the synchronous _blank decision sees hydrated settings, as ChatMarkdown does. + const linkTargetPreference = useClientSettings((settings) => settings.browserLinkTarget); + return ( + { + if ( + resolveLinkTarget({ + url: props.href, + event, + preference: linkTargetPreference, + canOpenInApp: canOpenLinksInApp(props.threadRef), + }) !== "app" + ) { + return; + } + event.preventDefault(); + void openLink(props.href, { event }).catch(console.error); + }} + > + {props.children} + + + ); +} + function ToolCallBody( props: ToolOutputState & { readonly command?: string; @@ -370,15 +412,15 @@ export const V2ItemInspector = memo(function V2ItemInspector(props: V2ItemInspec return (

  • {safeHref ? ( - {result.title ?? result.url} - - + ) : (

    {result.title ?? result.url ?? gt("Search result")} From f7f83805296727362959b70f4c49cbd5ad22d2d0 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Wed, 25 Nov 2026 16:34:28 +0100 Subject: [PATCH 097/880] fix(web): update terminal labels when the language changes (#42872) Co-authored-by: Julius Marminge (cherry picked from commit 3373a78606296baa9bb6e386c242da2f9ae32e04) --- apps/web/src/terminal/ghostty/surface.ts | 80 ++++++++++++------- ...minal-input-follows-language-change.e2e.ts | 57 +++++++++++++ 2 files changed, 106 insertions(+), 31 deletions(-) create mode 100644 scripts/scenarios/pending-terminal-input-follows-language-change.e2e.ts diff --git a/apps/web/src/terminal/ghostty/surface.ts b/apps/web/src/terminal/ghostty/surface.ts index b06a77f490742..b104e749b4756 100644 --- a/apps/web/src/terminal/ghostty/surface.ts +++ b/apps/web/src/terminal/ghostty/surface.ts @@ -23,6 +23,7 @@ import { isMonospaceFamily } from "../../appearanceFonts"; import { observeResize } from "../../lib/observeResize"; import { msg } from "gt-react"; import { m } from "../../i18n/messages"; +import { subscribeI18n } from "../../i18n/runtime"; const DEFAULT_TERMINAL_FONT_SIZE = 12; const MIN_TERMINAL_FONT_SIZE = 6; @@ -667,6 +668,7 @@ export class GhosttyTerminalSurface { metrics: GhosttyCellMetrics, fontFamily: string, options: GhosttyTerminalSurfaceOptions, + private readonly stopObservingI18n: () => void, ) { this.mount = mount; this.canvas = canvas; @@ -703,7 +705,6 @@ export class GhosttyTerminalSurface { const input = document.createElement("textarea"); input.className = "t3-ghostty-input"; - input.setAttribute("aria-label", m(msg("Terminal input"))); input.autocapitalize = "off"; input.autocomplete = "off"; input.spellcheck = false; @@ -714,7 +715,6 @@ export class GhosttyTerminalSurface { scrollbar.className = "group absolute top-1 right-px bottom-1 z-1 w-[var(--app-scrollbar-width)] cursor-default touch-none"; scrollbar.setAttribute("role", "scrollbar"); - scrollbar.setAttribute("aria-label", m(msg("Terminal scrollback"))); scrollbar.setAttribute("aria-orientation", "vertical"); scrollbar.tabIndex = 0; scrollbar.hidden = true; @@ -722,42 +722,59 @@ export class GhosttyTerminalSurface { scrollbarThumb.className = "absolute inset-x-px top-0 rounded-[3px] bg-[var(--app-scrollbar-thumb)] transition-[background-color] duration-[120ms] ease-[ease-out] group-hover:bg-[var(--app-scrollbar-thumb-hover)] group-focus-visible:bg-[var(--app-scrollbar-thumb-hover)]"; scrollbar.append(scrollbarThumb); + const updateAccessibleNames = () => { + input.setAttribute("aria-label", m(msg("Terminal input"))); + scrollbar.setAttribute("aria-label", m(msg("Terminal scrollback"))); + }; + updateAccessibleNames(); mount.replaceChildren(canvas, input, scrollbar); const context = canvas.getContext("2d", { alpha: false }); if (!context) throw new Error("Canvas 2D is unavailable"); context.fillStyle = `rgb(${options.theme.background.r}, ${options.theme.background.g}, ${options.theme.background.b})`; context.fillRect(0, 0, canvas.width, canvas.height); - const fontSize = terminalFontSize(options.font?.size); + const stopObservingI18n = subscribeI18n(updateAccessibleNames); try { - // Load bundled fonts before measuring; fallback metrics would size the wrong grid. - await ensureTerminalSymbolsFont(); - } catch {} - const fontFamily = await loadTerminalFontFamily(options.font?.family, fontSize); - const metrics = measureGhosttyCell(context, fontSize, fontFamily); - const grid = terminalGridSize(mount.clientWidth, mount.clientHeight, metrics, CONTENT_PADDING); - const core = await GhosttyTerminalCore.create( - grid.cols, - grid.rows, - metrics.width, - metrics.height, - options.theme, - options.onReply, - ); - const surface = new GhosttyTerminalSurface( - mount, - canvas, - input, - scrollbar, - scrollbarThumb, - context, - core, - metrics, - fontFamily, - options, - ); - surface.fit(); - return surface; + const fontSize = terminalFontSize(options.font?.size); + try { + // Load bundled fonts before measuring; fallback metrics would size the wrong grid. + await ensureTerminalSymbolsFont(); + } catch {} + const fontFamily = await loadTerminalFontFamily(options.font?.family, fontSize); + const metrics = measureGhosttyCell(context, fontSize, fontFamily); + const grid = terminalGridSize( + mount.clientWidth, + mount.clientHeight, + metrics, + CONTENT_PADDING, + ); + const core = await GhosttyTerminalCore.create( + grid.cols, + grid.rows, + metrics.width, + metrics.height, + options.theme, + options.onReply, + ); + const surface = new GhosttyTerminalSurface( + mount, + canvas, + input, + scrollbar, + scrollbarThumb, + context, + core, + metrics, + fontFamily, + options, + stopObservingI18n, + ); + surface.fit(); + return surface; + } catch (error) { + stopObservingI18n(); + throw error; + } } setVisible(visible: boolean): void { @@ -1079,6 +1096,7 @@ export class GhosttyTerminalSurface { this.disposed = true; this.clearHoveredLink(); this.stopObservingResize(); + this.stopObservingI18n(); document.fonts.removeEventListener("loadingdone", this.onFontsLoaded); this.dprMedia?.removeEventListener("change", this.onDevicePixelRatioChange); this.dprMedia = null; diff --git a/scripts/scenarios/pending-terminal-input-follows-language-change.e2e.ts b/scripts/scenarios/pending-terminal-input-follows-language-change.e2e.ts new file mode 100644 index 0000000000000..05e8abbe98849 --- /dev/null +++ b/scripts/scenarios/pending-terminal-input-follows-language-change.e2e.ts @@ -0,0 +1,57 @@ +import { expect } from "e2e"; + +import { test, WEB } from "./t3.ts"; + +test( + "Language changes update the same terminal input during and after setup", + WEB, + async ({ t3, app, browser, screen }) => { + const project = await t3.project("demo"); + const thread = await t3.thread({ project, title: "Terminal work", messages: ["Start"] }); + await t3.open(thread); + + await browser.evaluate(() => { + const load = FontFace.prototype.load; + const ready = new Promise((resolve) => { + window.addEventListener("release-terminal-font", () => resolve(), { once: true }); + }); + FontFace.prototype.load = function () { + return this.family.includes("Symbols Nerd Font Mono") + ? ready.then(() => load.call(this)) + : load.call(this); + }; + return null; + }); + + await screen.getByRole("button", "Toggle terminal drawer").tap(); + const input = browser.locator(".t3-ghostty-input:not([data-workspace-focus-default])"); + await expect(input).toHaveAttribute("aria-label", "Terminal input"); + await browser.evaluate(() => { + document.querySelector(".t3-ghostty-input")!.setAttribute("data-original-terminal", ""); + return null; + }); + + await screen.getByRole("button", "Settings", { exact: true }).tap(); + await screen.getByLabel("Language", { exact: true }).tap(); + await screen.getByText("日本語", { exact: true }).tap(); + await screen.getByLabel("言語", { exact: true }).waitFor(); + + const originalInput = browser.locator( + ".t3-ghostty-input[data-original-terminal]:not([data-workspace-focus-default])", + ); + await app.screenshot("pending-terminal-input-after-language-change"); + await expect(originalInput).toHaveAttribute("aria-label", "ターミナルの入力"); + await browser.evaluate(() => window.dispatchEvent(new Event("release-terminal-font"))); + + const readyInput = browser.locator( + ".t3-ghostty-input[data-original-terminal][data-workspace-focus-default]", + ); + await expect(readyInput).toHaveAttribute("aria-label", "ターミナルの入力"); + await screen.getByLabel("言語", { exact: true }).tap(); + await screen.getByText("English", { exact: true }).tap(); + await screen.getByLabel("Language", { exact: true }).waitFor(); + await browser.keyboard.press("Escape"); + + await expect(readyInput).toHaveAttribute("aria-label", "Terminal input"); + }, +); From bae84ca63f51bd12ea878c3773f559cf32681694 Mon Sep 17 00:00:00 2001 From: Marcus Takagi Date: Wed, 25 Nov 2026 23:34:42 +0800 Subject: [PATCH 098/880] fix(web): show Labs device preferences read-only for projects (#42884) Co-authored-by: huyuetian Co-authored-by: Julius Marminge (cherry picked from commit acd4fc67b930b0a9be7799f3f986e0ec46bf7a14) --- .../LabsSettingsPanel.scope.browser.test.tsx | 129 ++++++++++++++++++ .../components/settings/LabsSettingsPanel.tsx | 2 + docs/user/project-settings.md | 10 +- ...boring-sidebar-read-only-in-project.e2e.ts | 26 ++++ 4 files changed, 162 insertions(+), 5 deletions(-) create mode 100644 apps/web/src/components/settings/LabsSettingsPanel.scope.browser.test.tsx create mode 100644 scripts/scenarios/labs-boring-sidebar-read-only-in-project.e2e.ts diff --git a/apps/web/src/components/settings/LabsSettingsPanel.scope.browser.test.tsx b/apps/web/src/components/settings/LabsSettingsPanel.scope.browser.test.tsx new file mode 100644 index 0000000000000..bce95490d461e --- /dev/null +++ b/apps/web/src/components/settings/LabsSettingsPanel.scope.browser.test.tsx @@ -0,0 +1,129 @@ +import { PrimaryConnectionTarget } from "@t3tools/client-runtime/connection"; +import { EnvironmentId, ProjectId, ServerConfig } from "@t3tools/contracts"; +import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; +import { expect, it, vi } from "vite-plus/test"; + +import { render } from "../../../test/render"; +import "../../index.css"; +import { ensureClientSettingsHydrated, persistClientSettingsPatch } from "../../hooks/useSettings"; +import { buildSidebarProjectSnapshots } from "../../sidebarProjectGrouping"; +import type { EnvironmentPresentation } from "../../state/environments"; +import type { Project } from "../../types"; + +const environmentId = EnvironmentId.make("labs-settings"); +const config = Schema.decodeSync(ServerConfig)({ + environment: { + environmentId, + label: "Desk", + platform: { os: "linux", arch: "x64" }, + serverVersion: "1.0.0", + orchestrationProtocolVersion: 2, + capabilities: {}, + }, + auth: { + policy: "loopback-browser", + bootstrapMethods: ["one-time-token"], + sessionMethods: ["browser-session-cookie"], + sessionCookieName: "t3_session", + }, + cwd: "/workspace/labs", + keybindingsConfigPath: "/workspace/keybindings.json", + keybindings: [], + issues: [], + providers: [], + availableEditors: [], + observability: { + logsDirectoryPath: "/workspace/logs", + localTracingEnabled: false, + otlpTracesEnabled: false, + otlpMetricsEnabled: false, + }, + settings: {}, +}); +const environments: EnvironmentPresentation[] = [ + { + environmentId, + label: "Desk", + displayUrl: "http://localhost:12345", + relayManaged: false, + entry: { + target: new PrimaryConnectionTarget({ + environmentId, + label: "Desk", + httpBaseUrl: "http://localhost:12345", + wsBaseUrl: "ws://localhost:12345/ws", + }), + profile: Option.none(), + enabled: true, + }, + connection: { phase: "connected", error: null, traceId: null }, + refusedRouteIds: [], + serverConfig: config, + }, +]; +const projects: Project[] = [ + { + id: ProjectId.make("labs-project"), + environmentId, + title: "Labs project", + workspaceRoot: "/workspace/labs", + repositoryIdentity: null, + defaultModelSelection: null, + scripts: [], + createdAt: "2026-11-14T00:00:00.000Z", + updatedAt: "2026-11-14T00:00:00.000Z", + }, +]; + +vi.mock(import("../../state/environments"), async (original) => ({ + ...(await original()), + useEnvironments: () => ({ + isReady: true, + networkStatus: "online" as const, + environments, + presentationById: new Map(), + }), + usePrimaryEnvironmentId: () => environmentId, + usePrimaryEnvironment: () => environments[0]!, + readEnvironment: () => environments[0]!, +})); +vi.mock(import("../../state/session"), async (original) => ({ + ...(await original()), + useEnvironmentScope: () => true, + useEnvironmentsWithScope: () => new Set([environmentId]), +})); +vi.mock(import("../../state/entities"), async (original) => ({ + ...(await original()), + useProjects: () => projects, + useServerConfigs: () => new Map([[environmentId, config]]), +})); + +import { LabsSettingsPanel } from "./LabsSettingsPanel"; +import { SettingsScopeProvider } from "./SettingsScopeContext"; + +const [group] = buildSidebarProjectSnapshots({ + projects, + settings: DEFAULT_CLIENT_SETTINGS, + primaryEnvironmentId: environmentId, + resolveEnvironmentLabel: () => "Desk", +}); + +it("shows Boring sidebar device preferences read-only while a project is selected", async () => { + await ensureClientSettingsHydrated(); + await persistClientSettingsPatch( + { boringSidebarEnabled: true, boringSidebarMultilineRows: false }, + async () => {}, + ); + await using screen = await render( + {}}> + + , + { router: "/settings/labs" }, + ); + + for (const name of ["Boring sidebar (group by project)", "Two-line folder rows"]) { + expect(screen.getByRole("switch", { name }).element().closest("[inert]")).not.toBeNull(); + } +}); diff --git a/apps/web/src/components/settings/LabsSettingsPanel.tsx b/apps/web/src/components/settings/LabsSettingsPanel.tsx index da8bbd6e172bd..1d422b0c0bdfb 100644 --- a/apps/web/src/components/settings/LabsSettingsPanel.tsx +++ b/apps/web/src/components/settings/LabsSettingsPanel.tsx @@ -56,6 +56,7 @@ function BoringSidebarRow() { return ( { + await t3.project("demo"); + await t3.open("/settings/labs"); + + await screen.getByRole("switch", "Boring sidebar (group by project)").check(); + await expect(screen.getByRole("switch", "Two-line folder rows")).toBeVisible(); + + await screen.getByRole("button", "Project scope: All projects").tap(); + await screen.getByRole("menuitemradio").filter({ hasText: "demo" }).tap(); + await expect(screen.getByRole("button", "Project scope: demo")).toBeVisible(); + await app.screenshot("project-selected"); + + // A project cannot override a device preference, so neither switch may offer an edit. + await expect( + browser.locator('[inert] [aria-label="Boring sidebar (group by project)"]'), + ).toBeVisible(); + await expect(browser.locator('[inert] [aria-label="Two-line folder rows"]')).toBeVisible(); + }, +); From d8168245cd1f741b2efc680bbe431bdd81c28ef1 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 25 Nov 2026 07:34:55 -0800 Subject: [PATCH 099/880] fix(server): t3 connect link says to restart a running server, not start t3 serve (#42904) (cherry picked from commit aef22ed239b5947300d03d0d487c5d32cb4e5d7f) --- apps/server/src/cli/connect.test.ts | 62 +++++++++++++++++++++++++++++ apps/server/src/cli/connect.ts | 17 +++++--- 2 files changed, 73 insertions(+), 6 deletions(-) diff --git a/apps/server/src/cli/connect.test.ts b/apps/server/src/cli/connect.test.ts index 630fe7cbfbb63..d591cb311fc61 100644 --- a/apps/server/src/cli/connect.test.ts +++ b/apps/server/src/cli/connect.test.ts @@ -278,3 +278,65 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer, NetService.layer)) ); }, ); + +it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer, NetService.layer))( + "t3 connect link next step", + (it) => { + it.effect("tells the user to restart a server that is already running, not to start one", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-connect-link-test-" }); + const relayClientPath = `${baseDir}/bin/cloudflared`; + yield* fs.makeDirectory(`${baseDir}/bin`, { recursive: true }); + yield* fs.writeFileString( + relayClientPath, + `#!/bin/sh\necho "cloudflared version ${RelayClient.CLOUDFLARED_VERSION}"\n`, + ); + yield* fs.chmod(relayClientPath, 0o755); + yield* fs.makeDirectory(`${baseDir}/userdata/secrets`, { recursive: true }); + yield* fs.writeFileString( + `${baseDir}/userdata/secrets/cloud-cli-oauth-token.bin`, + JSON.stringify({ + accessToken: "access", + refreshToken: "refresh", + expiresAtEpochMs: 4_102_444_800_000, + identity: "user@example.com", + }), + ); + const state = yield* makePersistedServerRuntimeState({ + config: { host: "127.0.0.1", devUrl: undefined }, + port: 3773, + }); + yield* persistServerRuntimeState({ + path: `${baseDir}/userdata/server-runtime.json`, + state: { ...state, pid: process.pid }, + }); + + yield* Command.runWith(makeCli({ cloudEnabled: true }), { version: "0.0.0" })([ + "connect", + "link", + "--headless", + "--base-dir", + baseDir, + ]).pipe( + Effect.provide( + ConfigProvider.layer( + ConfigProvider.fromEnv({ env: { T3CODE_CLOUDFLARED_PATH: relayClientPath } }), + ), + ), + ); + + const printed = (yield* TestConsole.logLines).join("\n"); + const restart = yield* resolveHostCliCommand("service restart", ["--base-dir", baseDir]); + const serve = yield* resolveHostCliCommand("serve", ["--base-dir", baseDir]); + assert.include(printed, "✓ Authorized as user@example.com"); + assert.include(printed, `\`${restart.command}\``); + assert.notInclude(printed, `\`${serve.command}\``); + }).pipe( + Effect.scoped, + Effect.provideService(HostProcess.Environment, {}), + Effect.provide(Layer.fresh(TestConsole.layer)), + ), + ); + }, +); diff --git a/apps/server/src/cli/connect.ts b/apps/server/src/cli/connect.ts index 9236348cd6a72..0dc3d8ccad2d3 100644 --- a/apps/server/src/cli/connect.ts +++ b/apps/server/src/cli/connect.ts @@ -645,12 +645,17 @@ const connectLinkCommand = Command.make("link", { yield* Console.log("T3 Connect\n"); const linked = yield* linkEnvironmentForConnect(flags); if (linked) { - const serveCommand = yield* resolveHostCliHint("serve", flags.baseDir); - yield* Console.log( - flags.publishOnly - ? `✓ Authorized${connectedAs(linked.identity)}\n\nNext\n Start T3 to publish agent activity (no managed tunnel).` - : `✓ Authorized${connectedAs(linked.identity)}\n\nNext\n Start the server with \`${serveCommand}\` to make this machine reachable.`, - ); + const config = yield* ServerConfig.ServerConfig; + const running = yield* readLiveServerRuntimeState(config.serverRuntimeStatePath); + const purpose = flags.publishOnly + ? "publish agent activity (no managed tunnel)" + : "make this machine reachable"; + const next = Option.isSome(running) + ? `A T3 Code server is already running. Restart it to ${purpose}: run \`${yield* resolveHostCliHint("service restart", flags.baseDir)}\` for the background service, or stop the server and start it again.` + : flags.publishOnly + ? `Start T3 to ${purpose}.` + : `Start the server with \`${yield* resolveHostCliHint("serve", flags.baseDir)}\` to ${purpose}.`; + yield* Console.log(`✓ Authorized${connectedAs(linked.identity)}\n\nNext\n ${next}`); } }), ), From 4be42e787a62c7e76ad7523938fa771578e8f153 Mon Sep 17 00:00:00 2001 From: Victor Date: Wed, 25 Nov 2026 09:35:09 -0600 Subject: [PATCH 100/880] fix(server): extensionless empty ZIP files are detected as application/zip (#42899) Co-authored-by: Julius Marminge (cherry picked from commit 831f2408825c1c79ddb4e1256d8fe9ba9234befc) --- apps/server/src/workspace/WorkspaceFileSystem.test.ts | 7 ++++++- apps/server/src/workspace/fileHeaderMimeType.ts | 3 ++- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/apps/server/src/workspace/WorkspaceFileSystem.test.ts b/apps/server/src/workspace/WorkspaceFileSystem.test.ts index 7fd184a1f1e9b..98b34bba97ac9 100644 --- a/apps/server/src/workspace/WorkspaceFileSystem.test.ts +++ b/apps/server/src/workspace/WorkspaceFileSystem.test.ts @@ -153,11 +153,16 @@ it.layer(layerTest, { excludeTestServices: true })("WorkspaceFileSystemLive", (i image, new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), ); + const archive = path.join(cwd, "archive"); + const emptyZip = new Uint8Array(22); + emptyZip.set([0x50, 0x4b, 0x05, 0x06]); + yield* fs.writeFile(archive, emptyZip); expect( - (yield* service.getMetadata({ paths: [path.join(cwd, "run"), image] })).entries, + (yield* service.getMetadata({ paths: [path.join(cwd, "run"), image, archive] })).entries, ).toEqual([ { kind: "file", byteLength: script.length, mimeType: "text/x-python" }, { kind: "file", byteLength: 8, mimeType: "image/png" }, + { kind: "file", byteLength: 22, mimeType: "application/zip" }, ]); }), ); diff --git a/apps/server/src/workspace/fileHeaderMimeType.ts b/apps/server/src/workspace/fileHeaderMimeType.ts index 0c31a734ca730..889f101ac2d81 100644 --- a/apps/server/src/workspace/fileHeaderMimeType.ts +++ b/apps/server/src/workspace/fileHeaderMimeType.ts @@ -3,7 +3,8 @@ export function fileHeaderMimeType(bytes: Uint8Array): string | undefined { signature.every((byte, index) => bytes[offset + index] === byte); if (startsWith([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])) return "image/png"; if (startsWith([0xff, 0xd8, 0xff])) return "image/jpeg"; - if (startsWith([0x50, 0x4b, 0x03, 0x04])) return "application/zip"; + if (startsWith([0x50, 0x4b, 0x03, 0x04]) || startsWith([0x50, 0x4b, 0x05, 0x06])) + return "application/zip"; if (startsWith([0x52, 0x49, 0x46, 0x46]) && startsWith([0x57, 0x45, 0x42, 0x50], 8)) return "image/webp"; const header = new TextDecoder().decode(bytes); From c302a3ae951bff5f9e375e0d7898c08ba5633c66 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Wed, 25 Nov 2026 16:35:57 +0100 Subject: [PATCH 101/880] fix(web): localize terminal excerpt line ranges (#42886) Co-authored-by: Julius Marminge (cherry picked from commit 2891419b9301d89109c86814aeae639428705508) --- .../chat/ComposerPendingTerminalContexts.tsx | 8 +----- ...TerminalContextInlineChip.browser.test.tsx | 27 +++++++++++++++++++ .../chat/TerminalContextInlineChip.tsx | 7 +++-- .../chat/UserMessageContextChips.tsx | 1 - apps/web/src/i18n/translations/de.json | 2 ++ apps/web/src/i18n/translations/en.json | 2 ++ apps/web/src/i18n/translations/es.json | 2 ++ apps/web/src/i18n/translations/fr.json | 2 ++ apps/web/src/i18n/translations/ja.json | 2 ++ apps/web/src/i18n/translations/ko.json | 2 ++ apps/web/src/i18n/translations/pt-BR.json | 2 ++ apps/web/src/i18n/translations/ru.json | 2 ++ apps/web/src/i18n/translations/sv.json | 2 ++ apps/web/src/i18n/translations/zh.json | 2 ++ 14 files changed, 53 insertions(+), 10 deletions(-) create mode 100644 apps/web/src/components/chat/TerminalContextInlineChip.browser.test.tsx diff --git a/apps/web/src/components/chat/ComposerPendingTerminalContexts.tsx b/apps/web/src/components/chat/ComposerPendingTerminalContexts.tsx index 0e2aa6e27ad96..196b5b37be832 100644 --- a/apps/web/src/components/chat/ComposerPendingTerminalContexts.tsx +++ b/apps/web/src/components/chat/ComposerPendingTerminalContexts.tsx @@ -1,8 +1,4 @@ -import { - type TerminalContextDraft, - formatTerminalContextLabel, - isTerminalContextExpired, -} from "~/lib/terminalContext"; +import { type TerminalContextDraft, isTerminalContextExpired } from "~/lib/terminalContext"; import type { ContextPresentationCapability } from "../contextPresentationRegistry"; import { TerminalContextInlineChip } from "./TerminalContextInlineChip"; @@ -15,12 +11,10 @@ export function ComposerPendingTerminalContextChip({ context, detailsMode, }: ComposerPendingTerminalContextChipProps) { - const label = formatTerminalContextLabel(context); const expired = isTerminalContextExpired(context); return ( { + initializeI18n(() => {}); + const translations = await getTranslationsSnapshot("ja"); + await using screen = await render( + + + , + ); + + await expect.element(screen.getByText(label, { exact: true })).toBeVisible(); +}); diff --git a/apps/web/src/components/chat/TerminalContextInlineChip.tsx b/apps/web/src/components/chat/TerminalContextInlineChip.tsx index ea2b353b5be03..db048410f9a97 100644 --- a/apps/web/src/components/chat/TerminalContextInlineChip.tsx +++ b/apps/web/src/components/chat/TerminalContextInlineChip.tsx @@ -5,7 +5,6 @@ import type { ContextPresentationCapability } from "../contextPresentationRegist import { ContextChipPopover, ContextChipShell } from "../contextChipParts"; interface TerminalContextInlineChipProps { - label: string; terminalLabel: string; lineStart: number; lineEnd: number; @@ -15,8 +14,12 @@ interface TerminalContextInlineChipProps { } export function TerminalContextInlineChip(props: TerminalContextInlineChipProps) { - const { label, terminalLabel, lineStart, lineEnd, text, detailsMode, expired = false } = props; + const { terminalLabel, lineStart, lineEnd, text, detailsMode, expired = false } = props; const gt = useGT(); + const label = + lineStart === lineEnd + ? gt("{terminalLabel} line {lineStart}", { terminalLabel, lineStart }) + : gt("{terminalLabel} lines {lineStart}-{lineEnd}", { terminalLabel, lineStart, lineEnd }); if (!expired && text.length > 0 && detailsMode === "popover") { return ( diff --git a/apps/web/src/components/chat/UserMessageContextChips.tsx b/apps/web/src/components/chat/UserMessageContextChips.tsx index 56363dfafb3f4..891bce5296265 100644 --- a/apps/web/src/components/chat/UserMessageContextChips.tsx +++ b/apps/web/src/components/chat/UserMessageContextChips.tsx @@ -444,7 +444,6 @@ const userMessageContextPresentationRegistry = createContextPresentationRegistry record.kind === "terminal" ? ( Date: Wed, 25 Nov 2026 07:52:14 -0800 Subject: [PATCH 102/880] fix(client-runtime): a composer send right after Stop queues instead of failing to steer (#42918) (cherry picked from commit 9e385083d6255d4f4a94153ed25533f309f0da16) --- .../src/state/use-thread-composer-state.ts | 10 +++- .../src/state/threadWorkflows.test.ts | 59 ++++++++++--------- .../src/state/threadWorkflows.ts | 12 ++++ 3 files changed, 52 insertions(+), 29 deletions(-) diff --git a/apps/mobile/src/state/use-thread-composer-state.ts b/apps/mobile/src/state/use-thread-composer-state.ts index 6aa6d406e2f0f..cebccf5b4d72e 100644 --- a/apps/mobile/src/state/use-thread-composer-state.ts +++ b/apps/mobile/src/state/use-thread-composer-state.ts @@ -7,7 +7,10 @@ import { readEnvironmentScope } from "./session"; import { useAtomValue } from "@effect/atom-react"; import { compactBeforeSendTokens } from "@t3tools/client-runtime/state/context-window"; import { threadRuntimeIsActive } from "@t3tools/client-runtime/state/shell"; -import { threadSteersDuringCompaction } from "@t3tools/client-runtime/state/thread-workflows"; +import { + runStopRequested, + threadSteersDuringCompaction, +} from "@t3tools/client-runtime/state/thread-workflows"; import { resolvePendingHandoff } from "@t3tools/client-runtime/handoff"; import { announcedRun, @@ -400,7 +403,10 @@ export function useThreadComposerState(input: { run: selectedThreadProjection?.projection.runs.find((run) => run.id === activeRunId), messages: selectedThreadMessages, }); - const canSteerActiveTurn = queueWorkflow?.canPromoteToSteer === true && !compactionBlocksSteer; + const canSteerActiveTurn = + queueWorkflow?.canPromoteToSteer === true && + !compactionBlocksSteer && + !runStopRequested(selectedThreadProjection?.projection, activeRunId); // A stop or a restart holds the queue, completion wakes included, until it // is resumed; the queue sheet lists only the user's own messages. const queueHeld = queueWorkflow?.isHeld === true; diff --git a/packages/client-runtime/src/state/threadWorkflows.test.ts b/packages/client-runtime/src/state/threadWorkflows.test.ts index fd8092a996a66..d3e522e3cd7cb 100644 --- a/packages/client-runtime/src/state/threadWorkflows.test.ts +++ b/packages/client-runtime/src/state/threadWorkflows.test.ts @@ -35,33 +35,38 @@ const capabilities = (input?: { describe("thread workflows", () => { it.each([ - ["queue only", { queued: true }, false, false], - ["session still attaching", undefined, false, true], - ["native steering", { steer: true }, false, true], - ["interrupt and restart", { interrupt: true, restartSteer: true }, false, true], - ["restart without interrupt", { restartSteer: true }, false, false], - ["explicit compaction", { steer: true }, true, false], - ] as const)("gates composer steering for %s", (_, turns, compactCommandIsActive, expected) => { - const projection = { - thread: { id: "thread", activeProviderThreadId: "provider-thread" }, - runs: [{ id: "active", status: "running", providerThreadId: "provider-thread" }], - providerThreads: [{ id: "provider-thread", providerSessionId: "session" }], - providerSessions: [ - ...(turns === undefined - ? [] - : [{ id: "session", status: "running", capabilities: capabilities(turns) }]), - { id: "other", status: "ready", capabilities: capabilities({ steer: true }) }, - ], - messages: [], - } as unknown as OrchestrationV2ThreadProjection; - expect( - threadCanSteer(projection, { - compactCommandIsActive, - compactionRunning: false, - activeRunId: projection.runs[0]!.id, - }), - ).toBe(expected); - }); + ["queue only", { queued: true }, false, false, false], + ["session still attaching", undefined, false, false, true], + ["native steering", { steer: true }, false, false, true], + ["interrupt and restart", { interrupt: true, restartSteer: true }, false, false, true], + ["restart without interrupt", { restartSteer: true }, false, false, false], + ["explicit compaction", { steer: true }, true, false, false], + ["a run Stop has reached", { steer: true }, false, true, false], + ] as const)( + "gates composer steering for %s", + (_, turns, compactCommandIsActive, stopRequested, expected) => { + const projection = { + thread: { id: "thread", activeProviderThreadId: "provider-thread" }, + runs: [{ id: "active", status: "running", providerThreadId: "provider-thread" }], + providerThreads: [{ id: "provider-thread", providerSessionId: "session" }], + providerSessions: [ + ...(turns === undefined + ? [] + : [{ id: "session", status: "running", capabilities: capabilities(turns) }]), + { id: "other", status: "ready", capabilities: capabilities({ steer: true }) }, + ], + messages: [], + turnItems: stopRequested ? [{ runId: "active", type: "run_interrupt_request" }] : [], + } as unknown as OrchestrationV2ThreadProjection; + expect( + threadCanSteer(projection, { + compactCommandIsActive, + compactionRunning: false, + activeRunId: projection.runs[0]!.id, + }), + ).toBe(expected); + }, + ); it("skips message history classification when no runs are queued", () => { let metadataReads = 0; diff --git a/packages/client-runtime/src/state/threadWorkflows.ts b/packages/client-runtime/src/state/threadWorkflows.ts index 9e3d1eb4512b2..2931a93ec8fdb 100644 --- a/packages/client-runtime/src/state/threadWorkflows.ts +++ b/packages/client-runtime/src/state/threadWorkflows.ts @@ -110,6 +110,17 @@ function supportsSteering(turns: OrchestrationV2ProviderCapabilities["turns"]): ); } +/** The server rejects a steer into a run that Stop has reached, though the run still reads as running. */ +export function runStopRequested( + projection: Pick | null | undefined, + runId: Run["id"] | null | undefined, +): boolean { + if (projection == null || runId == null) return false; + return projection.turnItems.some( + (item) => item.runId === runId && item.type === "run_interrupt_request", + ); +} + export function threadCanSteer( projection: Projection | null, input: { @@ -121,6 +132,7 @@ export function threadCanSteer( const turns = projection && resolveThreadProviderSession(projection)?.capabilities.turns; // A steer submitted before the session attaches can wait for its provider turn. if (turns && !supportsSteering(turns)) return false; + if (runStopRequested(projection, input.activeRunId)) return false; return !compactionBlocksSteering({ compactCommandIsActive: input.compactCommandIsActive, compactionRunning: input.compactionRunning, From 34357edb1fbff3a6e4fe45639112976edcc3e4fe Mon Sep 17 00:00:00 2001 From: Victor Date: Wed, 25 Nov 2026 10:47:09 -0600 Subject: [PATCH 103/880] fix(web): unsupported file preview no longer calls extensionless filenames a file type (#42932) Co-authored-by: Julius Marminge (cherry picked from commit 4568a1b7414585f9eae82a955a0d123da3d1ed47) --- .../AttachmentFilePreview.browser.test.tsx | 19 +++++++++++++++++++ .../files/AttachmentFilePreview.tsx | 11 ++++++++--- apps/web/src/i18n/translations/de.json | 2 +- apps/web/src/i18n/translations/en.json | 2 +- apps/web/src/i18n/translations/es.json | 2 +- apps/web/src/i18n/translations/fr.json | 2 +- apps/web/src/i18n/translations/ja.json | 2 +- apps/web/src/i18n/translations/ko.json | 2 +- apps/web/src/i18n/translations/pt-BR.json | 2 +- apps/web/src/i18n/translations/ru.json | 2 +- apps/web/src/i18n/translations/sv.json | 2 +- apps/web/src/i18n/translations/zh.json | 2 +- 12 files changed, 37 insertions(+), 13 deletions(-) diff --git a/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx b/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx index 83da950e44993..c7e56bacb50f7 100644 --- a/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx +++ b/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx @@ -2313,3 +2313,22 @@ it.each([ `Unsupported PDF ${directory} asset.`, ); }); + +it.each([ + ["firmware", "Save it to open in an app that supports this format."], + [".cache", "Save it to open in an app that supports this format."], + ["a.dir/firmware", "Save it to open in an app that supports this format."], + ["blob.foo", "Save it to open in an app that supports foo files."], +] as const)( + "describes unsupported binary attachment %s without misreading its name as an extension", + async (name, expected) => { + const file = new Blob([new Uint8Array([0, 1, 2, 3])], { type: "application/octet-stream" }); + await using screen = await render( + , + ); + await expect + .element(screen.getByText("No preview for this file", { exact: true })) + .toBeVisible(); + await expect.element(screen.getByText(expected, { exact: true })).toBeVisible(); + }, +); diff --git a/apps/web/src/components/files/AttachmentFilePreview.tsx b/apps/web/src/components/files/AttachmentFilePreview.tsx index ba2b69ad7c783..4c7abcc34e0df 100644 --- a/apps/web/src/components/files/AttachmentFilePreview.tsx +++ b/apps/web/src/components/files/AttachmentFilePreview.tsx @@ -284,6 +284,11 @@ export function AttachmentFilePreview(props: { }); }; + const basename = props.name.split(/[\\/]/).at(-1) ?? ""; + const dotIndex = basename.lastIndexOf("."); + const extension = + dotIndex > 0 && dotIndex < basename.length - 1 ? basename.slice(dotIndex + 1) : null; + const body = failure ? ( No preview for this file

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

  • diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 45bd6429082af..0ca317d994a3f 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -5501,7 +5501,7 @@ }, "-Dateien unterstützt." ], - "774654575f014b55": "Speichere sie, um sie in einer App zu öffnen, die dieses Dateiformat unterstützt.", + "d3170aa2bb08efbd": "Speichere sie, um sie in einer App zu öffnen, die dieses Dateiformat unterstützt.", "46f943a30e259620": "Audio nicht verfügbar. {name} öffnen", "e2cf6b944d1d095d": "Audio nicht verfügbar. {name} erneut versuchen", "f08fb460ad4617d6": "{name} wird geladen", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index 6d6c38bcd8b11..526c8f2c42e47 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -5502,7 +5502,7 @@ }, " files." ], - "774654575f014b55": "Save it to open in an app that supports this format files.", + "d3170aa2bb08efbd": "Save it to open in an app that supports this format.", "46f943a30e259620": "Audio unavailable. Open {name}", "e2cf6b944d1d095d": "Audio unavailable. Retry {name}", "f08fb460ad4617d6": "Loading {name}", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index efd2777961224..28eecd72a1f59 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -5500,7 +5500,7 @@ }, "." ], - "774654575f014b55": "Guárdalo para abrirlo en una app compatible con este formato de archivo.", + "d3170aa2bb08efbd": "Guárdalo para abrirlo en una app compatible con este formato de archivo.", "46f943a30e259620": "Audio no disponible. Abrir {name}", "e2cf6b944d1d095d": "Audio no disponible. Reintentar {name}", "f08fb460ad4617d6": "Cargando {name}", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index 101a97d3e2ac8..42df4ac4591c3 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -5501,7 +5501,7 @@ }, "." ], - "774654575f014b55": "Enregistrez-le pour l’ouvrir dans une app qui prend en charge ce format de fichier.", + "d3170aa2bb08efbd": "Enregistrez-le pour l’ouvrir dans une app qui prend en charge ce format de fichier.", "46f943a30e259620": "Audio indisponible. Ouvrir {name}", "e2cf6b944d1d095d": "Audio indisponible. Réessayer {name}", "f08fb460ad4617d6": "Chargement de {name}", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index 5276729abdc2e..523622ce7b22b 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -5487,7 +5487,7 @@ }, " ファイルに対応したアプリで開くには、保存してください。" ], - "774654575f014b55": "この形式のファイルに対応したアプリで開くには、保存してください。", + "d3170aa2bb08efbd": "この形式のファイルに対応したアプリで開くには、保存してください。", "46f943a30e259620": "音声を利用できません。{name} を開く", "e2cf6b944d1d095d": "音声を利用できません。{name} を再試行", "f08fb460ad4617d6": "{name} を読み込んでいます", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index fa0c3f6f164f8..9395f5640bf43 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -5486,7 +5486,7 @@ }, " 파일을 지원하는 앱에서 여세요." ], - "774654575f014b55": "저장한 후 이 형식을 지원하는 앱에서 여세요.", + "d3170aa2bb08efbd": "저장한 후 이 형식을 지원하는 앱에서 여세요.", "46f943a30e259620": "오디오를 사용할 수 없음. {name} 열기", "e2cf6b944d1d095d": "오디오를 사용할 수 없음. {name} 다시 시도", "f08fb460ad4617d6": "{name} 불러오는 중", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index 80759228ba4e0..acc8f9d6b9323 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -5500,7 +5500,7 @@ }, "." ], - "774654575f014b55": "Salve-o para abrir em um app compatível com este formato.", + "d3170aa2bb08efbd": "Salve-o para abrir em um app compatível com este formato.", "46f943a30e259620": "Áudio indisponível. Abrir {name}", "e2cf6b944d1d095d": "Áudio indisponível. Tentar {name} novamente", "f08fb460ad4617d6": "Carregando {name}", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 0ad6166d9aa51..96af87211dc26 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -5500,7 +5500,7 @@ }, "." ], - "774654575f014b55": "Сохраните его, чтобы открыть в приложении, поддерживающем файлы этого формата.", + "d3170aa2bb08efbd": "Сохраните его, чтобы открыть в приложении, поддерживающем файлы этого формата.", "46f943a30e259620": "Аудио недоступно. Открыть {name}", "e2cf6b944d1d095d": "Аудио недоступно. Повторить {name}", "f08fb460ad4617d6": "Загрузка {name}", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index 9d1ea357ac80e..a12133d069082 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -5501,7 +5501,7 @@ }, "-filer." ], - "774654575f014b55": "Spara den för att öppna den i en app som stöder det här filformatet.", + "d3170aa2bb08efbd": "Spara den för att öppna den i en app som stöder det här filformatet.", "46f943a30e259620": "Ljudet är inte tillgängligt. Öppna {name}", "e2cf6b944d1d095d": "Ljudet är inte tillgängligt. Försök igen med {name}", "f08fb460ad4617d6": "Läser in {name}", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index 25eed0632e75c..bcad88a187a0c 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -5507,7 +5507,7 @@ }, " 文件的应用中打开。" ], - "774654575f014b55": "保存后可在支持此格式文件的应用中打开。", + "d3170aa2bb08efbd": "保存后可在支持此格式文件的应用中打开。", "46f943a30e259620": "音频不可用。打开 {name}", "e2cf6b944d1d095d": "音频不可用。重试 {name}", "f08fb460ad4617d6": "正在加载 {name}", From 6453058ffee1b6be08c10f99c1ae0910701872d8 Mon Sep 17 00:00:00 2001 From: xandev641 <143331243+xandev641@users.noreply.github.com> Date: Wed, 25 Nov 2026 18:02:29 +0100 Subject: [PATCH 104/880] fix(mobile): keep CSV headings below the iPad navigation bar (#42928) Co-authored-by: Xander von Itzenplitz Co-authored-by: Julius Marminge (cherry picked from commit 1c4622955aa6f961eddf7e024a741c0993013cbe) --- apps/mobile/src/features/files/DelimitedFilePreview.tsx | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/apps/mobile/src/features/files/DelimitedFilePreview.tsx b/apps/mobile/src/features/files/DelimitedFilePreview.tsx index 281f4a3a8fdaa..c07cce86bb78c 100644 --- a/apps/mobile/src/features/files/DelimitedFilePreview.tsx +++ b/apps/mobile/src/features/files/DelimitedFilePreview.tsx @@ -3,6 +3,7 @@ import { useGT } from "gt-react-native"; import { ScrollView, View } from "react-native"; import type { parseDelimitedPreview } from "@t3tools/shared/delimitedPreview"; import { AppText as Text } from "../../components/ui/AppText"; +import { NativeScrollView } from "../../native/NativeScrollViewMarker"; import { FilePreviewNotice } from "./FilePreviewFeedback"; export function DelimitedFilePreview(props: { @@ -10,7 +11,7 @@ export function DelimitedFilePreview(props: { }) { const gt = useGT(); return ( - + {props.table.truncated ? ( {gt("Table limited to the first 100 rows and 30 columns. Source shows the rest.")} @@ -38,6 +39,6 @@ export function DelimitedFilePreview(props: { ))} - + ); } From 27ebe24e2d370e7ee484a8aca4cd932ef83573a2 Mon Sep 17 00:00:00 2001 From: Victor Date: Wed, 25 Nov 2026 11:13:34 -0600 Subject: [PATCH 105/880] fix(web): SQLite 1-byte BLOB previews show "[blob: 1 byte]" (#42950) Co-authored-by: Julius Marminge (cherry picked from commit e36800e61babed824d055393d62fedc961e26e3b) --- .../files/binaryPreview.worker.test.ts | 55 ++++++++++++++----- .../components/files/binaryPreview.worker.ts | 2 +- 2 files changed, 43 insertions(+), 14 deletions(-) diff --git a/apps/web/src/components/files/binaryPreview.worker.test.ts b/apps/web/src/components/files/binaryPreview.worker.test.ts index caaef354c51a0..99e089ff0ce79 100644 --- a/apps/web/src/components/files/binaryPreview.worker.test.ts +++ b/apps/web/src/components/files/binaryPreview.worker.test.ts @@ -6,6 +6,22 @@ import { type BinaryWorkerResult, } from "./binaryPreviewProtocol"; +async function startWorker() { + const worker = new EventTarget(); + let receive = (_result: BinaryWorkerResult) => {}; + vi.stubGlobal( + "self", + Object.assign(worker, { postMessage: (result: BinaryWorkerResult) => receive(result) }), + ); + vi.resetModules(); + await import("./binaryPreview.worker"); + return (input: BinaryWorkerRequest) => + new Promise((resolve) => { + receive = resolve; + worker.dispatchEvent(new MessageEvent("message", { data: input })); + }); +} + it.each([ARCHIVE_ENTRY_MAX_BYTES, ARCHIVE_ENTRY_MAX_BYTES + 1])( "only copies previewable TAR payloads with a %i-byte entry", async (size) => { @@ -47,20 +63,8 @@ it.each([ARCHIVE_ENTRY_MAX_BYTES, ARCHIVE_ENTRY_MAX_BYTES + 1])( offset += 512 + Math.ceil(entry.bytes.length / 512) * 512; } - const worker = new EventTarget(); - let receive = (_result: BinaryWorkerResult) => {}; - vi.stubGlobal( - "self", - Object.assign(worker, { postMessage: (result: BinaryWorkerResult) => receive(result) }), - ); try { - vi.resetModules(); - await import("./binaryPreview.worker"); - const request = (input: BinaryWorkerRequest) => - new Promise((resolve) => { - receive = resolve; - worker.dispatchEvent(new MessageEvent("message", { data: input })); - }); + const request = await startWorker(); using copies = vi.spyOn(Uint8Array.prototype, "slice"); expect( await request({ type: "open", kind: "archive", name: "mixed.tar", bytes: bytes.buffer }), @@ -104,3 +108,28 @@ it.each([ARCHIVE_ENTRY_MAX_BYTES, ARCHIVE_ENTRY_MAX_BYTES + 1])( } }, ); + +it("formats singular and plural byte labels for SQLite BLOB cells", async () => { + const { default: initSqlJs } = await import("sql.js"); + const SQL = await initSqlJs(); + const db = new SQL.Database(); + db.run( + "CREATE TABLE blobs(empty BLOB, one BLOB, four BLOB); INSERT INTO blobs VALUES (X'', X'FF', X'DEADBEEF');", + ); + const bytes = db.export().slice().buffer; + db.close(); + + try { + const request = await startWorker(); + await request({ type: "open", kind: "sqlite", name: "blobs.sqlite", bytes }); + expect(await request({ type: "rows", table: "blobs", page: 0 })).toEqual({ + type: "rows", + table: "blobs", + page: 0, + columns: ["empty", "one", "four"], + rows: [["[blob: 0 bytes]", "[blob: 1 byte]", "[blob: 4 bytes]"]], + }); + } finally { + vi.unstubAllGlobals(); + } +}); diff --git a/apps/web/src/components/files/binaryPreview.worker.ts b/apps/web/src/components/files/binaryPreview.worker.ts index 4c67d2826976f..d661c4eade9f3 100644 --- a/apps/web/src/components/files/binaryPreview.worker.ts +++ b/apps/web/src/components/files/binaryPreview.worker.ts @@ -180,7 +180,7 @@ async function handle(input: BinaryWorkerRequest) { .slice(0, 50) ?? []; const fields = columns.map((name) => { const field = quote(name); - return `CASE WHEN typeof(${field}) = 'blob' THEN '[blob: ' || length(${field}) || ' bytes]' ELSE substr(CAST(${field} AS TEXT), 1, 1024) END`; + return `CASE WHEN typeof(${field}) = 'blob' THEN '[blob: ' || length(${field}) || CASE length(${field}) WHEN 1 THEN ' byte]' ELSE ' bytes]' END ELSE substr(CAST(${field} AS TEXT), 1, 1024) END`; }); const result = database.exec( `SELECT ${fields.join(",")} FROM ${quote(input.table)} LIMIT ${SQLITE_PAGE_SIZE} OFFSET ${input.page * SQLITE_PAGE_SIZE}`, From e9a29153e34cd7691b8aeaaaa2832ffe0dca1d31 Mon Sep 17 00:00:00 2001 From: Victor Date: Wed, 25 Nov 2026 11:27:55 -0600 Subject: [PATCH 106/880] fix(server): DOCX merged table cells no longer shift later columns in attachment text (#42955) Co-authored-by: Julius Marminge (cherry picked from commit b1360538c1c8a01329c2bc816a8a45a7fc325517) --- .../server/src/provider/documentTextWorker.ts | 11 +++++++++-- .../src/provider/userInputAttachments.test.ts | 19 +++++++++++++++++++ 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/apps/server/src/provider/documentTextWorker.ts b/apps/server/src/provider/documentTextWorker.ts index 230e5d22c144c..2ba8613843d2c 100644 --- a/apps/server/src/provider/documentTextWorker.ts +++ b/apps/server/src/provider/documentTextWorker.ts @@ -324,11 +324,18 @@ function* table(node: XmlNode): Generator { for (let index = 0; index < repeat; index++) { if (++rowCount > 10_000) throw new Truncation("Row limit"); let column = 0; + let gap = 0; for (const cell of cells) { const count = repeatCount(cell.attrs["number-columns-repeated"]); + // Word emits no cell for columns covered by w:gridSpan; pad before the next cell. + const tcPr = cell.name === "tc" ? children(cell).find((c) => c.name === "tcPr") : undefined; + const val = tcPr && children(tcPr).find((c) => c.name === "gridSpan")?.attrs.val; + const span = val ? Math.max(1, Number.parseInt(val, 10) || 1) : 1; for (let i = 0; i < count; i++) { - if (column >= 512) throw new Truncation("Column limit"); - if (column++) yield "\t"; + column += span; + if (column > 512) throw new Truncation("Column limit"); + if (gap) yield "\t".repeat(gap); + gap = span; // LibreOffice hides the contents a merge covers; the cell still holds its column. if (covered(cell)) continue; yield CELL_START; diff --git a/apps/server/src/provider/userInputAttachments.test.ts b/apps/server/src/provider/userInputAttachments.test.ts index 6aad293a35ec9..e61ccafccca77 100644 --- a/apps/server/src/provider/userInputAttachments.test.ts +++ b/apps/server/src/provider/userInputAttachments.test.ts @@ -961,6 +961,25 @@ describe("question answer paths", () => { "Before Inner After\tNeighbor\t\u2011\n\u2011\nDemoted\nIntro. # Box title", ], }, + { + ext: "docx", + bounded: true, + parts: { + "word/document.xml": + '' + + "ABC" + + 'TailEnd' + + 'MergedTotal' + + 'ZeroNext' + + 'Wide' + + "", + }, + expected: [ + "A\tB\tC\nTail\tEnd\nMerged\t\tTotal\nZero\tNext", + "[Extracted text truncated at document extraction limits.]", + ], + absent: ["Wide"], + }, { ext: "docx", bounded: true, From 611205e2bd025628b34be476b014dffe0e0d12eb Mon Sep 17 00:00:00 2001 From: "Paul Dupuy, Jr." <70114489+pauldupuyjr@users.noreply.github.com> Date: Wed, 25 Nov 2026 11:47:55 -0600 Subject: [PATCH 107/880] test(scripts): WSL archive fixture works with Git Bash tar on Windows (#42962) Co-authored-by: Julius Marminge (cherry picked from commit f84c7168394eb8541ca928f09177bcd7b5495d1d) --- scripts/build-desktop-artifact.test.ts | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/scripts/build-desktop-artifact.test.ts b/scripts/build-desktop-artifact.test.ts index c872e86ba0a01..11cd2de9077a5 100644 --- a/scripts/build-desktop-artifact.test.ts +++ b/scripts/build-desktop-artifact.test.ts @@ -104,16 +104,18 @@ const makeLinuxCliArchiveFixture = Effect.fn("test.makeLinuxCliArchiveFixture")( yield* fs.makeDirectory(path.dirname(memberPath), { recursive: true }); yield* fs.writeFileString(memberPath, member); } - const archivePath = path.join(input.root, `${input.stem}.tar.gz`); + const archiveName = `${input.stem}.tar.gz`; const tar = yield* spawner.spawn( - ChildProcess.make("tar", ["-czf", archivePath, "-C", contentRoot, "."], { + // GNU tar reads a drive letter in an absolute archive path as a remote host. + ChildProcess.make("tar", ["-czf", archiveName, "-C", contentRoot, "."], { + cwd: input.root, stdin: "ignore", stdout: "ignore", stderr: "pipe", }), ); assert.equal(Number(yield* tar.exitCode), 0); - return archivePath; + return path.join(input.root, archiveName); }); function mockProcess(exitCode: number, stdout = "") { From 73279441b5d28fab85206d36bfe37aa5e46d929d Mon Sep 17 00:00:00 2001 From: Dara Adedeji <76637177+SunkenInTime@users.noreply.github.com> Date: Wed, 25 Nov 2026 13:00:34 -0500 Subject: [PATCH 108/880] fix(web): Antigravity settings show only the fields the chosen sign-in method uses (#40494) Co-authored-by: shivam <91240327+shivamhwp@users.noreply.github.com> (cherry picked from commit 93b8dc3465ef829c8aa3b375190822550387d33f) --- .../settings/ProviderSettingsForm.test.ts | 35 ++++++++++++++ .../settings/ProviderSettingsForm.tsx | 46 +++++++++++++++++-- apps/web/src/i18n/translations/de.json | 2 +- apps/web/src/i18n/translations/en.json | 2 +- apps/web/src/i18n/translations/es.json | 2 +- apps/web/src/i18n/translations/fr.json | 2 +- apps/web/src/i18n/translations/ja.json | 2 +- apps/web/src/i18n/translations/ko.json | 2 +- apps/web/src/i18n/translations/pt-BR.json | 2 +- apps/web/src/i18n/translations/ru.json | 2 +- apps/web/src/i18n/translations/sv.json | 2 +- apps/web/src/i18n/translations/zh.json | 2 +- packages/contracts/src/settings.ts | 23 ++++++++-- 13 files changed, 107 insertions(+), 17 deletions(-) diff --git a/apps/web/src/components/settings/ProviderSettingsForm.test.ts b/apps/web/src/components/settings/ProviderSettingsForm.test.ts index 49aa7c30b567d..91b0962a5c32b 100644 --- a/apps/web/src/components/settings/ProviderSettingsForm.test.ts +++ b/apps/web/src/components/settings/ProviderSettingsForm.test.ts @@ -52,6 +52,41 @@ describe("ProviderSettingsForm helpers", () => { expect(next).toEqual({ forkOwned: 1 }); }); + it("shows Antigravity credential fields only for the sign-in methods that read them, or while set", () => { + const antigravity = providerClients.get(ProviderDriverKind.make("antigravity")); + expect(antigravity).toBeDefined(); + const keysFor = (value?: unknown) => + deriveProviderSettingsFields(antigravity!, value).map((field) => field.key); + + expect(keysFor({})).toEqual(["authMethod", "binaryPath"]); + expect( + keysFor({ + authMethod: "oauth-personal", + apiKey: { provider: "vault", reference: "antigravity" }, + gcpLocation: "us-central1", + }), + ).toEqual(["authMethod", "apiKey", "gcpLocation", "binaryPath"]); + expect(keysFor({ authMethod: "oauth-business" })).toEqual([ + "authMethod", + "gcpProject", + "gcpLocation", + "binaryPath", + ]); + expect(keysFor({ authMethod: "gemini-api-key" })).toEqual([ + "authMethod", + "apiKey", + "binaryPath", + ]); + expect(keysFor({ authMethod: "agent-platform" })).toEqual([ + "authMethod", + "apiKey", + "gcpProject", + "gcpLocation", + "binaryPath", + ]); + expect(keysFor()).toEqual(["authMethod", "apiKey", "gcpProject", "gcpLocation", "binaryPath"]); + }); + it("does not store a text value its field's schema rejects", () => { const claude = providerClients.get(ProviderDriverKind.make("claudeAgent")); expect(claude).toBeDefined(); diff --git a/apps/web/src/components/settings/ProviderSettingsForm.tsx b/apps/web/src/components/settings/ProviderSettingsForm.tsx index b542918f62485..6577dd17700fa 100644 --- a/apps/web/src/components/settings/ProviderSettingsForm.tsx +++ b/apps/web/src/components/settings/ProviderSettingsForm.tsx @@ -162,8 +162,10 @@ const PACKAGE_FIELD_TEXT: ReadonlyMap = new Map([ ), ], [ - "Google accounts use your subscription; API keys and Agent Platform bill usage.", - msg("Google accounts use your subscription; API keys and Agent Platform bill usage."), + "Google account and Gemini Enterprise use your existing plan. Gemini API key and Agent Platform charge per use to your key or Google Cloud project.", + msg( + "Google account and Gemini Enterprise use your existing plan. Gemini API key and Agent Platform charge per use to your key or Google Cloud project.", + ), ], [ "Gemini or Vertex AI express key. Stored separately on the host.", @@ -259,6 +261,25 @@ function packageFieldText(text: string, resolve: MessageResolver): string { return entry === undefined ? text : resolve(entry); } +/** An unset select shows, and acts as, its first option. */ +function readSelectValue( + config: unknown, + key: string, + options: ReadonlyArray | undefined, +): string { + return readProviderConfigString(config, key) || (options?.[0]?.value ?? ""); +} + +function hasConfiguredValue(config: unknown, key: string): boolean { + if (config === null || typeof config !== "object") return false; + const value = (config as Record)[key]; + return value !== undefined && value !== ""; +} + +/** + * Without a `value`, lists every field. With one, a `visibleWhen` field is hidden only while empty: + * a leftover value still reaches the server, so it stays visible and clearable. + */ export function deriveProviderSettingsFields( definition: SettingsFormDefinition, value?: unknown, @@ -285,6 +306,23 @@ export function deriveProviderSettingsFields( const fieldSchema = definition.settingsSchema.fields[key]!; const formAnnotation = readProviderSettingsFormAnnotation(fieldSchema); if (formAnnotation.hidden) return []; + const visibleWhen = formAnnotation.visibleWhen; + const controller = + visibleWhen === undefined ? undefined : definition.settingsSchema.fields[visibleWhen.field]; + if ( + visibleWhen !== undefined && + value !== undefined && + !hasConfiguredValue(value, key) && + !visibleWhen.values.includes( + readSelectValue( + value, + visibleWhen.field, + controller && readProviderSettingsFormAnnotation(controller).options, + ), + ) + ) { + return []; + } if (isLocalAcp && key !== "source" && key !== "commandPath") return []; const annotatedTitle = readFieldAnnotationString(fieldSchema, "title"); @@ -592,7 +630,7 @@ function ProviderSettingsSelect({ }) { const options = field.options ?? []; const fallback = options[0]?.value ?? ""; - const current = readProviderConfigString(value, field.key) || fallback; + const current = readSelectValue(value, field.key, options); const label = options.find((option) => option.value === current)?.label ?? current; return (