From 70e4319da82f75240cba6b47956e77b5bde611ee Mon Sep 17 00:00:00 2001 From: Pouya Rezvani <32917154+pouyarezvani@users.noreply.github.com> Date: Tue, 17 Nov 2026 22:36:46 -0800 Subject: [PATCH 01/25] fix(web): switching back to a thread no longer jumps through its HTML renders (#38458) Co-authored-by: Julius Marminge --- .../chat/HtmlRenderFrame.browser.test.tsx | 46 ++++++++++++++++++- .../src/components/chat/HtmlRenderFrame.tsx | 22 ++++++++- 2 files changed, 64 insertions(+), 4 deletions(-) diff --git a/apps/web/src/components/chat/HtmlRenderFrame.browser.test.tsx b/apps/web/src/components/chat/HtmlRenderFrame.browser.test.tsx index 9c00f0d3581ea..4acf8803ad80b 100644 --- a/apps/web/src/components/chat/HtmlRenderFrame.browser.test.tsx +++ b/apps/web/src/components/chat/HtmlRenderFrame.browser.test.tsx @@ -3,12 +3,14 @@ import { describe, expect, it, vi } from "vite-plus/test"; import { userEvent } from "vite-plus/test/browser"; import "~/index.css"; -import { render } from "../../../test/render"; +import { render, type Screen } from "../../../test/render"; + +const assetUrl = vi.hoisted(() => ({ current: "about:blank" })); vi.mock(import("~/assets/longLivedAssetUrls"), () => ({ useLongLivedAssetUrl: () => ({ _tag: "Success", - url: "about:blank", + url: assetUrl.current, expiresAt: Date.now() + 60 * 60_000, }), })); @@ -19,8 +21,19 @@ vi.mock(import("~/assets/assetUrls"), async (importOriginal) => ({ import { HtmlRenderFrame } from "./HtmlRenderFrame"; +function setup() { + assetUrl.current = "about:blank"; +} + +const sizeChanged = (height: number) => ({ + jsonrpc: "2.0", + method: "ui/notifications/size-changed", + params: { height }, +}); + describe("HtmlRenderFrame", () => { it("reports leaving full screen when it unmounts while expanded", async () => { + setup(); const onFullscreenChange = vi.fn(); await using screen = await render( { await screen.unmount(); expect(onFullscreenChange).toHaveBeenLastCalledWith(false); }); + + it("reopens at the page height it last measured", async () => { + setup(); + using page = (() => { + const html = ``; + const url = URL.createObjectURL(new Blob([html], { type: "text/html" })); + return { url, [Symbol.dispose]: () => URL.revokeObjectURL(url) }; + })(); + const frame = () => ( + + ); + const frameHeight = (screen: Screen) => + screen.getByTitle("Mockup").element().parentElement?.style.height; + + assetUrl.current = page.url; + { + await using first = await render(frame()); + await vi.waitFor(() => expect(frameHeight(first)).toBe("1500px")); + } + + // A page that never reports its height, so only the remembered measurement can size the frame. + assetUrl.current = "about:blank"; + await using second = await render(frame()); + expect(frameHeight(second)).toBe("1500px"); + }); }); diff --git a/apps/web/src/components/chat/HtmlRenderFrame.tsx b/apps/web/src/components/chat/HtmlRenderFrame.tsx index 25967a96b7b91..8191e5fad6186 100644 --- a/apps/web/src/components/chat/HtmlRenderFrame.tsx +++ b/apps/web/src/components/chat/HtmlRenderFrame.tsx @@ -20,6 +20,19 @@ import { HtmlRenderDialog } from "./HtmlRenderDialog"; import { observeResize } from "~/lib/observeResize"; const MIN_URL_LIFE_MS = 5 * 60_000; +const MAX_MEASURED_CONTENT_HEIGHTS = 200; + +// The height each render's page last reported, so a remounted frame opens at it before its page loads. +const measuredContentHeights = new Map(); + +function rememberContentHeight(attachmentId: string, height: number) { + measuredContentHeights.delete(attachmentId); + measuredContentHeights.set(attachmentId, height); + if (measuredContentHeights.size > MAX_MEASURED_CONTENT_HEIGHTS) { + const oldest = measuredContentHeights.keys().next().value; + if (oldest !== undefined) measuredContentHeights.delete(oldest); + } +} export function HtmlRenderFrame(props: { readonly environmentId: EnvironmentId; @@ -37,7 +50,9 @@ export function HtmlRenderFrame(props: { }); }; // Client fonts can exceed the server-measured height and cause nested scrolling. - const [contentHeight, setContentHeight] = useState(); + const [contentHeight, setContentHeight] = useState(() => + measuredContentHeights.get(attachmentId), + ); const height = htmlRenderFrameHeight(props.htmlRender, width, contentHeight); const fileName = htmlRenderFileName(title); const resource = { @@ -77,7 +92,10 @@ export function HtmlRenderFrame(props: { title={title} threadRef={props.threadRef} className="block size-full" - onContentHeight={setContentHeight} + onContentHeight={(height) => { + rememberContentHeight(attachmentId, height); + setContentHeight(height); + }} onFullscreenChange={onFullscreenChange} />
From a93e61a3438d43eeee99da857270da2222767cd5 Mon Sep 17 00:00:00 2001 From: Mike Olson Date: Wed, 18 Nov 2026 01:49:02 -0500 Subject: [PATCH 02/25] fix(mobile): A document whose upload failed can be retried in the composer (#38443) Co-authored-by: Julius Marminge --- .../src/components/ComposerAttachmentStrip.tsx | 4 +++- .../src/features/threads/ThreadComposer.tsx | 8 +++++++- apps/mobile/src/lib/composerImages.test.ts | 16 +++++++++++----- apps/mobile/src/lib/composerImages.ts | 9 +++++++-- 4 files changed, 28 insertions(+), 9 deletions(-) diff --git a/apps/mobile/src/components/ComposerAttachmentStrip.tsx b/apps/mobile/src/components/ComposerAttachmentStrip.tsx index 8e5a954501d8e..767a689568131 100644 --- a/apps/mobile/src/components/ComposerAttachmentStrip.tsx +++ b/apps/mobile/src/components/ComposerAttachmentStrip.tsx @@ -215,6 +215,8 @@ function ComposerFileAttachment( const canPreview = isPdfFile(attachment) && props.onPressPreview !== undefined; const sourceIdentifier = `draft-file:${attachment.id}`; const onPressDocument = props.onPressDocument; + const upload = useComposerAttachmentUploadState(props.environmentId, attachment.id); + const showsUploadBadge = upload !== undefined && upload.status !== "ready"; return ( <> @@ -235,7 +237,7 @@ function ComposerFileAttachment( className={ props.compact ? "items-center justify-center bg-subtle" - : "items-center justify-center gap-1 bg-subtle px-2" + : `items-center justify-center gap-1 bg-subtle px-2${showsUploadBadge ? " pb-4" : ""}` } style={style} > diff --git a/apps/mobile/src/features/threads/ThreadComposer.tsx b/apps/mobile/src/features/threads/ThreadComposer.tsx index 76bb79d608682..19ca8397aa64e 100644 --- a/apps/mobile/src/features/threads/ThreadComposer.tsx +++ b/apps/mobile/src/features/threads/ThreadComposer.tsx @@ -84,6 +84,7 @@ import { composerStripAttachments, type DraftComposerFileAttachment, } from "../../lib/composerImages"; +import { composerAttachmentUploadKey } from "../../lib/composerAttachmentUploadQueue"; import { buildModelOptions, isModelSelectionUnavailable, @@ -303,7 +304,6 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps draftMessage.trim().length > 0 || draftAttachments.length > 0 || (queuedEdit?.existingAttachments.length ?? 0) > 0; - const stripAttachments = composerStripAttachments(draftAttachments); const showStopAction = !hasContent && props.canStopThread && queuedEdit === null; const onResumeQueue = props.onResumeQueue; const [resumingQueue, setResumingQueue] = useState(false); @@ -321,6 +321,12 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps AuthOrchestrationOperateScope, ); const uploadStates = useAtomValue(composerAttachmentUploadsAtom); + const stripAttachments = composerStripAttachments( + draftAttachments, + (attachment) => + uploadStates[composerAttachmentUploadKey(props.environmentId, attachment.id)]?.status === + "failed", + ); const attachmentsUploading = props.connectionState === "connected" && composerAttachmentsStillUploading({ diff --git a/apps/mobile/src/lib/composerImages.test.ts b/apps/mobile/src/lib/composerImages.test.ts index b5b10ac02c7bb..367c6cf3896eb 100644 --- a/apps/mobile/src/lib/composerImages.test.ts +++ b/apps/mobile/src/lib/composerImages.test.ts @@ -332,10 +332,16 @@ describe("composerStripAttachments", () => { it("keeps media beside a document rather than dropping the whole strip", async () => { const { composerStripAttachments } = await import("./composerImages"); - expect(composerStripAttachments([doc, image, video] as never).map((a) => a.id)).toEqual([ - "img-1", - "vid-1", - ]); + expect( + composerStripAttachments([doc, image, video] as never, () => false).map((a) => a.id), + ).toEqual(["img-1", "vid-1"]); + }); + + it("shows a document whose upload failed, so it can be retried", async () => { + const { composerStripAttachments } = await import("./composerImages"); + expect( + composerStripAttachments([doc, image] as never, (a) => a.id === "doc-1").map((a) => a.id), + ).toEqual(["doc-1", "img-1"]); }); it("keeps oversized document-picked images visible while sending them as files", async () => { @@ -350,7 +356,7 @@ describe("composerStripAttachments", () => { sizeBytes: PROVIDER_SEND_TURN_MAX_IMAGE_BYTES + 1, }; - expect(composerStripAttachments([oversizedImage])).toEqual([oversizedImage]); + expect(composerStripAttachments([oversizedImage], () => false)).toEqual([oversizedImage]); expect(isComposerImageAttachment(oversizedImage)).toBe(false); }); }); diff --git a/apps/mobile/src/lib/composerImages.ts b/apps/mobile/src/lib/composerImages.ts index 34abd9f9456ec..3ca64eef41fe8 100644 --- a/apps/mobile/src/lib/composerImages.ts +++ b/apps/mobile/src/lib/composerImages.ts @@ -80,15 +80,20 @@ export async function createPastedTextComposerAttachment(input: { export type DraftComposerAttachment = DraftComposerImageAttachment | DraftComposerFileAttachment; -/** Non-media attachments require chip references; missing references mean lost draft files. */ +/** + * Non-media attachments require chip references; missing references mean lost draft files. + * A chip cannot retry an upload, so a document whose upload failed joins the strip. + */ export function composerStripAttachments( attachments: ReadonlyArray, + uploadFailed: (attachment: DraftComposerAttachment) => boolean, ): ReadonlyArray { return attachments.filter( (attachment) => attachment.type === "image" || imageMimeType(attachment) !== null || - videoMimeType(attachment) !== null, + videoMimeType(attachment) !== null || + uploadFailed(attachment), ); } From 281d3e1cbe9e6dd6ed2d11b23caaccf3069509bb Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 17 Nov 2026 22:57:24 -0800 Subject: [PATCH 03/25] fix(server): running a paused one-time task by hand no longer deletes it (#38463) --- .../ScheduledTaskService.test.ts | 66 +++++++++++++++++++ .../scheduledTasks/ScheduledTaskService.ts | 4 +- 2 files changed, 69 insertions(+), 1 deletion(-) diff --git a/apps/server/src/scheduledTasks/ScheduledTaskService.test.ts b/apps/server/src/scheduledTasks/ScheduledTaskService.test.ts index 3edf786b15ec6..98a5bc040c238 100644 --- a/apps/server/src/scheduledTasks/ScheduledTaskService.test.ts +++ b/apps/server/src/scheduledTasks/ScheduledTaskService.test.ts @@ -580,6 +580,72 @@ it.effect("a one-time task is removed once its turn completes", () => }).pipe(Effect.provide(SqlitePersistence.layerMemory)), ); +it.effect("a paused one-time task run by hand before its time is kept", () => + Effect.gen(function* () { + yield* TestClock.setTime(Date.parse("2026-11-01T07:00:00.000Z")); + const projectId = ProjectId.make("project:test"); + const ended = yield* Deferred.make(); + const outcomeRead = yield* Deferred.make(); + const sent = yield* Ref.make(""); + const run = { id: "run:1", status: "completed", rootNodeId: "node:root" }; + const layer = ScheduledTaskService.layer.pipe( + Layer.provide( + Layer.mergeAll( + ManagedPolicy.layerTest(), + Layer.mock(ThreadLaunchService.ThreadLaunchService)({}), + Layer.mock(ThreadManagementService.ThreadManagementService)({ + sendToThread: (input) => Ref.set(sent, input.messageId).pipe(Effect.as({} as never)), + getThreadShell: () => Effect.succeed(threadShell(projectId)), + getProjectThreadRecords: () => + Effect.map( + Ref.get(sent), + (userMessageId) => ({ runs: [{ ...run, userMessageId }] }) as never, + ), + waitForThread: (input) => + Deferred.await(ended).pipe( + Effect.tap(() => Deferred.succeed(outcomeRead, undefined)), + Effect.as({ threadId: input.threadId, run, timedOut: false } as never), + ), + }), + Layer.mock(SecretRequests.SecretRequests)({}), + Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({ + namedProjectsRoot: "/projects", + isScratchProject: () => Effect.succeed(false), + }), + NodeCrypto.layer, + Scheduler.layer, + ), + ), + ); + yield* Effect.gen(function* () { + const service = yield* ScheduledTaskService.ScheduledTaskService; + const { task } = yield* service.upsert({ + id: ScheduledTaskId.make("task:paused-once"), + title: "Release notes", + prompt: "Draft the release notes", + enabled: true, + schedule: { type: "once", runAt: "2026-11-01T08:00:00.000Z" }, + projectId, + threadId: ThreadId.make("thread:once"), + workspaceStrategy: { type: "root" }, + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" }, + runtimeMode: "full-access", + interactionMode: "default", + }); + yield* service.setEnabled({ id: task.id, enabled: false }); + yield* service.runNow({ id: task.id }); + yield* Deferred.succeed(ended, undefined); + yield* Deferred.await(outcomeRead); + yield* TestClock.adjust("1 second"); + const [kept] = (yield* service.list()).tasks; + assert.equal(kept?.id, task.id); + assert.equal(kept?.runCount, 1); + const resumed = yield* service.setEnabled({ id: task.id, enabled: true }); + assert.equal(resumed.task.nextRunAt, "2026-11-01T08:00:00.000Z"); + }).pipe(Effect.provide(layer)); + }).pipe(Effect.provide(SqlitePersistence.layerMemory)), +); + it.effect("a bound run follows its thread when promotion moves it mid-send", () => Effect.gen(function* () { const scratch = ProjectId.make("project:scratch"); diff --git a/apps/server/src/scheduledTasks/ScheduledTaskService.ts b/apps/server/src/scheduledTasks/ScheduledTaskService.ts index 17840c50bf499..35e0e5c77fb86 100644 --- a/apps/server/src/scheduledTasks/ScheduledTaskService.ts +++ b/apps/server/src/scheduledTasks/ScheduledTaskService.ts @@ -885,7 +885,8 @@ export const layer = Layer.effect( // A dispatch is recorded once the message is accepted; the provider can still // reject the turn after that, so follow the run and record its failure. A one-time - // task whose turn completed is spent, so it is removed; its thread stays. + // task whose turn completed at or after its runAt is spent, so it is removed; its + // thread stays. A paused task always has a NULL next_run_at, so that alone proves nothing. const recordRunOutcome = Effect.fn("ScheduledTaskService.recordRunOutcome")(function* ( taskId: ScheduledTaskId, startedAtIso: string, @@ -910,6 +911,7 @@ export const layer = Layer.effect( WHERE task_id = ${taskId} AND last_run_at = ${startedAtIso} AND last_run_status = 'succeeded' AND next_run_at IS NULL AND json_extract(schedule_json, '$.type') = 'once' + AND julianday(last_run_at) >= julianday(json_extract(schedule_json, '$.runAt')) RETURNING task_id `; if (removed.length > 0) yield* notifyChanged; From a1b1a6388c33716d5909e63a48d3ccc67734452c Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 17 Nov 2026 23:01:44 -0800 Subject: [PATCH 04/25] fix(server): codex text generation identifies as T3 Code (#38464) --- .../CodexTextGeneration.test.ts | 20 +++++++++++++++++++ .../src/textGeneration/CodexTextGeneration.ts | 3 ++- 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/apps/server/src/textGeneration/CodexTextGeneration.test.ts b/apps/server/src/textGeneration/CodexTextGeneration.test.ts index 1a1a5c43b0a0d..5d0fd95b455f0 100644 --- a/apps/server/src/textGeneration/CodexTextGeneration.test.ts +++ b/apps/server/src/textGeneration/CodexTextGeneration.test.ts @@ -59,6 +59,7 @@ interface FakeCodexInput { requiredCwd?: string; requireInstructions?: string; requireMcpServersOff?: ReadonlyArray; + requireOriginator?: string; } function makeFakeCodexBinary(dir: string, input: FakeCodexInput) { @@ -75,6 +76,7 @@ function makeFakeCodexBinary(dir: string, input: FakeCodexInput) { requiredCwd: input.requiredCwd ?? null, requireInstructions: input.requireInstructions ?? null, requireMcpServersOff: input.requireMcpServersOff ?? [], + requireOriginator: input.requireOriginator ?? null, stderr: input.stderr ?? null, output: input.output, exitCode: input.exitCode ?? 0, @@ -158,6 +160,9 @@ function makeFakeCodexBinary(dir: string, input: FakeCodexInput) { "for (const name of check.requireMcpServersOff) {", ' if (!offServers.has(name)) fail("MCP server left on: " + name, 13);', "}", + "if (check.requireOriginator !== null && process.env.CODEX_INTERNAL_ORIGINATOR_OVERRIDE !== check.requireOriginator) {", + ' fail("unexpected originator: " + process.env.CODEX_INTERNAL_ORIGINATOR_OVERRIDE, 14);', + "}", 'if (check.requiredCwd !== null && process.cwd() !== check.requiredCwd) fail("cannot inspect checkout", 10);', 'if (check.requireInstructions !== null && !instructions.includes(check.requireInstructions)) fail("missing writer task", 11);', "if (check.requireArg !== null && !originalArgs.includes(` ${check.requireArg} `)) {", @@ -519,6 +524,21 @@ it.layer(layerCodexTextGenerationTest)("CodexTextGeneration", (it) => { ), ); + it.effect("identifies codex exec as T3 Code", () => + withFakeCodexEnv( + { output: JSON.stringify({ title: "Live title" }), requireOriginator: "T3 Code" }, + (textGeneration) => + Effect.gen(function* () { + const result = yield* textGeneration.generateThreadTitle({ + cwd: process.cwd(), + message: "Name this thread", + modelSelection: DEFAULT_TEST_MODEL_SELECTION, + }); + expect(result.title).toBe("Live title"); + }), + ), + ); + it.effect("passes exec-safe launch args into codex exec", () => withFakeCodexEnv( { diff --git a/apps/server/src/textGeneration/CodexTextGeneration.ts b/apps/server/src/textGeneration/CodexTextGeneration.ts index fc741aaaeb262..c9810e3cfe360 100644 --- a/apps/server/src/textGeneration/CodexTextGeneration.ts +++ b/apps/server/src/textGeneration/CodexTextGeneration.ts @@ -23,6 +23,7 @@ import { codexMcpListLaunchArgs, resolveCodexLaunchArgs, } from "../provider/codexLaunchArgs.ts"; +import { codexAppServerEnvironment } from "../provider/CodexProvider.ts"; import * as TextGenerationOperations from "@t3tools/provider-core/server/textGenerationOperations"; import { normalizeCliError, @@ -286,7 +287,7 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func resolved || fellBack ? undefined : getCodexServiceTierOptionValue(modelSelection); const binary = effectiveConfig.binaryPath || "codex"; const env = { - ...effectiveEnvironment, + ...codexAppServerEnvironment(effectiveEnvironment), ...(effectiveConfig.homePath ? { CODEX_HOME: expandHomePath( From 7c67d196c57f55b0897f450bfb693fc36e1a426e Mon Sep 17 00:00:00 2001 From: Alex Vallone <39172404+amv146@users.noreply.github.com> Date: Tue, 17 Nov 2026 23:17:18 -0800 Subject: [PATCH 05/25] fix(server): review diff previews reuse the cached repository layout (#38451) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Co-authored-by: Julius Marminge --- apps/server/src/vcs/GitVcsDriverCore.test.ts | 51 ++++++++++++++------ apps/server/src/vcs/GitVcsDriverCore.ts | 35 +++++++++----- 2 files changed, 58 insertions(+), 28 deletions(-) diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.ts index 6cb91ad2dd042..f4eb10810503e 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.test.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts @@ -766,7 +766,7 @@ it.effect.each(["an existing", "a new"] as const)( ); it.effect.each(["on a branch", "detached", "unborn"] as const)( - "reads only the repository root for review requests that ignore the branch when %s", + "reuses the cached repository layout for review requests when %s", (state) => Effect.scoped( Effect.gen(function* () { @@ -780,15 +780,18 @@ it.effect.each(["on a branch", "detached", "unborn"] as const)( Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), ); const discoveries = () => { - const commands = spawnedArgs.filter( - (args) => - args.includes("--show-toplevel") || - args.includes("--git-common-dir") || - (args.includes("symbolic-ref") && args.includes("HEAD")), - ); + const spawned = (matches: (args: ReadonlyArray) => boolean) => + spawnedArgs.filter(matches).length; + const counts = { + commonDir: spawned((args) => args.includes("--git-common-dir")), + worktreeRoot: spawned((args) => args.includes("--show-toplevel")), + branch: spawned((args) => args.includes("symbolic-ref") && args.includes("HEAD")), + }; spawnedArgs.length = 0; - return commands.length; + return counts; }; + const warm = { commonDir: 0, worktreeRoot: 0, branch: 0 }; + const branchRead = { ...warm, branch: 1 }; const cwd = yield* makeTmpDir(); if (state === "unborn") { yield* git(cwd, ["init", "-b", "main"]); @@ -802,36 +805,54 @@ it.effect.each(["on a branch", "detached", "unborn"] as const)( yield* writeTextFile(cwd, "new.txt", "new\n"); spawnedArgs.length = 0; - const workingTree = yield* driver.getReviewDiffPreview({ + const workingTreeFile = { cwd, file: { path: "new.txt", previousPath: null, sourceKind: "working-tree" }, - }); - assert.equal(discoveries(), 1); + } as const; + const workingTree = yield* driver.getReviewDiffPreview(workingTreeFile); + assert.deepStrictEqual(discoveries(), { commonDir: 1, worktreeRoot: 1, branch: 1 }); assert.deepStrictEqual( workingTree.sources .find((source) => source.kind === "working-tree")! .files!.map((file) => file.path), ["new.txt"], ); + yield* driver.getReviewDiffPreview(workingTreeFile); + assert.deepStrictEqual(discoveries(), warm); if (state !== "unborn") { const commitSha = yield* git(cwd, ["rev-parse", "HEAD"]); - spawnedArgs.length = 0; const commit = yield* driver.getReviewDiffPreview({ cwd, commitSha, file: { path: "committed.txt", previousPath: null, sourceKind: "commit" }, }); - assert.equal(discoveries(), 1); + assert.deepStrictEqual(discoveries(), warm); assert.include(commit.sources[0]!.diff, "+committed"); } + const headRef = (preview: Effect.Success>) => + preview.sources.find((entry) => entry.kind === "branch-range")!.headRef; const general = yield* driver.getReviewDiffPreview({ cwd }); - assert.equal(discoveries(), 3); + assert.deepStrictEqual(discoveries(), branchRead); assert.equal( - general.sources.find((source) => source.kind === "branch-range")!.headRef, + headRef(general), state === "detached" ? "HEAD" : yield* git(cwd, ["branch", "--show-current"]), ); + + // A checkout made outside the driver is visible to the next request. + if (state !== "detached") yield* git(cwd, ["checkout", "-b", "outside-checkout"]); + const afterCheckout = yield* driver.getReviewDiffPreview({ cwd }); + assert.deepStrictEqual(discoveries(), branchRead); + if (state !== "detached") assert.equal(headRef(afterCheckout), "outside-checkout"); + + yield* driver.getReviewBranchCommits({ cwd }); + assert.deepStrictEqual(discoveries(), branchRead); + + // A cached layout must not outlive a removed cwd. + yield* (yield* FileSystem.FileSystem).remove(cwd, { recursive: true }); + assert.isEmpty((yield* driver.getReviewDiffPreview(workingTreeFile)).sources); + assert.isEmpty((yield* driver.getReviewDiffPreview({ cwd })).sources); }), ).pipe(Effect.provide(layerTest)), ); diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index 48664332e760c..0d6ef4631327d 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -1620,13 +1620,6 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* } satisfies GitRepositoryPaths; }); - const resolveReviewWorktreeRoot = Effect.fn("resolveReviewWorktreeRoot")(function* (cwd: string) { - const worktreeRoot = yield* readWorktreeRoot(cwd); - if (worktreeRoot !== null) return { worktreeRoot, currentBranch: null }; - // Full discovery tells bare and non-repository directories apart from real Git failures. - return yield* resolveRepositoryPathsUncached(cwd); - }); - const repositoryPathsCache = yield* Cache.makeWith( (cwd: string) => resolveRepositoryPathsUncached(cwd), { @@ -1660,6 +1653,26 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* return Cache.get(refresh ? repositoryPathsRefreshCache : repositoryPathsCache, cacheKey); }; + const resolveReviewRepository = Effect.fn("resolveReviewRepository")(function* ( + cwd: string, + needsCurrentBranch: boolean, + ) { + // A cached layout outlives a removed cwd, which must still read as a missing cwd. + if ( + !needsCurrentBranch && + !(yield* fileSystem.exists(cwd).pipe(Effect.orElseSucceed(() => true))) + ) { + return null; + } + const repository = yield* resolveRepositoryPaths(cwd); + if (repository?.worktreeRoot == null) return null; + // The cached branch outlives a checkout made outside T3 Code, so it is read fresh. + const currentBranch = needsCurrentBranch + ? yield* readCurrentBranch("GitVcsDriver.review.currentBranch", cwd) + : null; + return { worktreeRoot: repository.worktreeRoot, currentBranch }; + }); + const defaultBranchCache = yield* Cache.makeWith( (gitCommonDir: string) => Effect.gen(function* () { @@ -4064,7 +4077,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const getReviewBranchCommits = Effect.fn("getReviewBranchCommits")(function* ( input: ReviewBranchCommitsInput, ) { - const repository = yield* resolveRepositoryPathsUncached(input.cwd); + const repository = yield* resolveReviewRepository(input.cwd, true); if (!repository?.worktreeRoot) return { commits: [], truncated: false }; const cwd = repository.worktreeRoot; const head = yield* executeGit( @@ -4150,11 +4163,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* input.commitSha === undefined && input.file?.sourceKind !== "commit" && sourceKind !== "working-tree"; - const repository = yield* ( - needsCurrentBranch - ? resolveRepositoryPathsUncached(input.cwd) - : resolveReviewWorktreeRoot(input.cwd) - ).pipe( + const repository = yield* resolveReviewRepository(input.cwd, needsCurrentBranch).pipe( Effect.catchTags({ GitCommandError: (error) => isMissingGitCwdError(error) ? Effect.succeed(null) : Effect.fail(error), From 01cfac429d9854bb6a37a96735b5b2d9baf23b81 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 17 Nov 2026 23:41:03 -0800 Subject: [PATCH 06/25] fix(web): Paste as Text pastes text when the clipboard also holds an image (#38475) --- apps/web/src/components/chat/ChatComposer.tsx | 2 +- .../web/src/components/chat/composerAttachmentFiles.test.ts | 6 ++++++ apps/web/src/components/chat/composerAttachmentFiles.ts | 3 +++ 3 files changed, 10 insertions(+), 1 deletion(-) diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index 3c2919c7606d2..fb4ed5eb0f626 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -2836,7 +2836,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) (!pastedContext && activeThreadId && files.length > 0 && - shouldHandleComposerAttachmentPaste({ files, plainText })) + shouldHandleComposerAttachmentPaste({ files, plainText, bypassAutoAttachment })) ) { event.preventDefault(); event.stopPropagation(); diff --git a/apps/web/src/components/chat/composerAttachmentFiles.test.ts b/apps/web/src/components/chat/composerAttachmentFiles.test.ts index c9eb37def6152..2a487b1f237de 100644 --- a/apps/web/src/components/chat/composerAttachmentFiles.test.ts +++ b/apps/web/src/components/chat/composerAttachmentFiles.test.ts @@ -121,6 +121,12 @@ describe("composer attachment files", () => { ).toBe(true); }); + it("leaves an image-and-text clipboard to the text path under Paste as Text", () => { + const image = new File(["png"], "image.png", { type: "image/png" }); + const input = { files: [image], plainText: "Hello from Word", bypassAutoAttachment: true }; + expect(shouldHandleComposerAttachmentPaste(input)).toBe(false); + }); + it("preserves text when the clipboard also includes generic image files", () => { const image = new File(["tiff"], "photo.tiff", { type: "image/tiff" }); expect( diff --git a/apps/web/src/components/chat/composerAttachmentFiles.ts b/apps/web/src/components/chat/composerAttachmentFiles.ts index d60688d92b31f..041db7193d2e2 100644 --- a/apps/web/src/components/chat/composerAttachmentFiles.ts +++ b/apps/web/src/components/chat/composerAttachmentFiles.ts @@ -242,7 +242,10 @@ export function attachmentsToReleaseOnUploadCapabilityLoss( export function shouldHandleComposerAttachmentPaste(input: { readonly files: ReadonlyArray; readonly plainText: string; + readonly bypassAutoAttachment?: boolean; }): boolean { + // Paste as Text keeps the text even when the source also put an image of it on the clipboard. + if (input.bypassAutoAttachment && input.plainText.length > 0) return false; if ( input.files.some((file) => { if (isDngFile(file)) return true; From f5f8c8d18baf6a194fea9c7a3734158c2b7ea57b Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 17 Nov 2026 23:42:07 -0800 Subject: [PATCH 07/25] fix(web): opening a file in the preview browser shows its current contents (#38470) --- .../files/FilePreviewPanel.browser.test.tsx | 76 +++++++++++++++++++ .../src/components/files/FilePreviewPanel.tsx | 1 + 2 files changed, 77 insertions(+) diff --git a/apps/web/src/components/files/FilePreviewPanel.browser.test.tsx b/apps/web/src/components/files/FilePreviewPanel.browser.test.tsx index 670154a009f6e..3d50db17ee3c6 100644 --- a/apps/web/src/components/files/FilePreviewPanel.browser.test.tsx +++ b/apps/web/src/components/files/FilePreviewPanel.browser.test.tsx @@ -19,6 +19,8 @@ const state = vi.hoisted(() => ({ writeFile: vi.fn(), assetUrl: { _tag: "Loading" } as import("~/assets/assetUrls").AssetUrlState, mintUrl: vi.fn<() => Promise>(), + browserAssetMints: 0, + openedBrowserUrls: [] as string[], })); vi.mock(import("@t3tools/client-runtime/state/runtime"), async (original) => ({ @@ -65,6 +67,56 @@ vi.mock(import("~/assets/assetUrls"), async (original) => ({ useAssetUrlRefresh: () => state.mintUrl, useAssetUrlState: () => state.assetUrl, })); +vi.mock(import("~/browser/previewRuntime"), async (original) => ({ + ...(await original()), + usePreviewAvailable: () => true, +})); +vi.mock(import("~/state/environments"), async (original) => ({ + ...(await original()), + useEnvironmentHttpBaseUrl: () => "http://environment.test", +})); +vi.mock(import("~/state/assets"), async (original) => { + const actual = await original(); + const { Atom } = await import("effect/reactivity"); + const Effect = await import("effect/Effect"); + // Like the real query family, a minted URL stays cached until the atom is refreshed. + const createUrl = Atom.family((_key: string) => + Atom.make( + Effect.sync(() => ({ + relativeUrl: `/api/assets/mint-${++state.browserAssetMints}/page.html`, + expiresAt: Number.MAX_SAFE_INTEGER, + })), + ).pipe(Atom.keepAlive), + ); + return { + ...actual, + assetEnvironment: { + ...actual.assetEnvironment, + createUrl: ((target: { input: { resource: { path: string } } }) => + createUrl(target.input.resource.path)) as never, + }, + }; +}); +vi.mock(import("~/browser/openFileInPreview"), async (original) => { + const actual = await original(); + return { + ...actual, + openFileInPreview: (async (input: Parameters[0]) => { + const result = await input.createAssetUrl({ + environmentId: input.threadRef.environmentId, + input: { + resource: { + _tag: "workspace-file", + threadId: input.threadRef.threadId, + path: input.filePath, + }, + }, + }); + if (result._tag === "Success") state.openedBrowserUrls.push(result.value.relativeUrl); + return AsyncResult.success(undefined); + }) as never, + }; +}); // The Word engine compiles a large WebAssembly bundle; these tests only need the URL it loads. vi.mock(import("./OfficeFilePreview"), () => ({ OfficeFilePreview: ({ src }: { src: string }) =>
{src}
, @@ -121,6 +173,7 @@ function setup() { state.file = null; state.optimistic = null; state.assetUrl = { _tag: "Loading" }; + state.openedBrowserUrls = []; let mints = 0; state.mintUrl.mockReset().mockImplementation(async () => `/assets/report.docx?mint=${++mints}`); state.writeFile.mockReset().mockResolvedValue(AsyncResult.success(undefined)); @@ -409,6 +462,29 @@ describe("workspace document previews", () => { }); }); +describe("open file in preview browser", () => { + it("mints a fresh asset URL on every click so the browser cannot reuse cached bytes", async () => { + using _settings = setup(); + state.file = { + relativePath: "page.html", + contents: "

page

", + byteLength: 13, + truncated: false, + }; + await using screen = await render(filePreview("page.html")); + const button = screen.getByRole("button", { name: "Open file in preview browser" }); + + await userEvent.click(button); + await vi.waitFor(() => expect(state.openedBrowserUrls).toHaveLength(1)); + await userEvent.click(button); + await vi.waitFor(() => expect(state.openedBrowserUrls).toHaveLength(2)); + + expect(state.openedBrowserUrls[1], "the second click reused the first signed URL").not.toBe( + state.openedBrowserUrls[0], + ); + }); +}); + describe("rendered Markdown select all", () => { it("selects only the rendered file, including after a task toggle", async () => { using _settings = setup(); diff --git a/apps/web/src/components/files/FilePreviewPanel.tsx b/apps/web/src/components/files/FilePreviewPanel.tsx index bf2f9b9a43ce6..18c8067c8163c 100644 --- a/apps/web/src/components/files/FilePreviewPanel.tsx +++ b/apps/web/src/components/files/FilePreviewPanel.tsx @@ -1202,6 +1202,7 @@ export default function FilePreviewPanel({ const previewAvailable = usePreviewAvailable(environmentId); const createAssetUrl = useAtomQueryRunner(assetEnvironment.createUrl, { reportFailure: false, + refresh: true, }); const openPreview = useAtomCommand(previewEnvironment.open, { reportFailure: false, From 77f87ea4c191de3533567ee90ed67998b5ca4a5d Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Wed, 18 Nov 2026 09:21:11 +0100 Subject: [PATCH 08/25] fix(github): page closing pull requests past the first twenty on issues (#38487) --- .../src/server/GitHubIssueTracker.test.ts | 28 ++- .../src/server/GitHubIssueTracker.ts | 88 +++++-- .../src/server/issues.graphql | 32 ++- .../src/server/issues.graphql.ts | 24 +- .../github-closing-pr-after-first-page.e2e.ts | 222 ++++++++++++++++++ 5 files changed, 367 insertions(+), 27 deletions(-) create mode 100644 scripts/scenarios/github-closing-pr-after-first-page.e2e.ts diff --git a/packages/source-control-github/src/server/GitHubIssueTracker.test.ts b/packages/source-control-github/src/server/GitHubIssueTracker.test.ts index 1760511cabcd4..3ddcd024f8b35 100644 --- a/packages/source-control-github/src/server/GitHubIssueTracker.test.ts +++ b/packages/source-control-github/src/server/GitHubIssueTracker.test.ts @@ -80,6 +80,7 @@ const DETAIL_RESPONSE = JSON.stringify({ viewerCanReopen: true, reactionGroups: [], closedByPullRequestsReferences: { + pageInfo: { hasNextPage: true, endCursor: "links-next" }, nodes: [ { number: 50, @@ -186,9 +187,18 @@ function tracker(onRequest: (variables: unknown) => void, templateRepository?: u pageInfo: { hasNextPage: false, endCursor: null }, nodes: [{ name: "needs repro", color: "ffffff" }], }, - assignees: { + closedByPullRequestsReferences: { pageInfo: { hasNextPage: false, endCursor: null }, - nodes: [], + nodes: [ + { + number: 61, + title: "fix(web): restore focus after paste", + url: "https://github.com/acme/web/pull/61", + state: "OPEN", + isDraft: true, + repository: { nameWithOwner: "acme/web" }, + }, + ], }, }, }, @@ -549,6 +559,10 @@ Redact secrets before uploading.`); number: 42, labelsCursor: "labels-next", assigneesCursor: null, + closingPullRequestsCursor: "links-next", + withLabels: true, + withAssignees: false, + withClosingPullRequests: true, }, ]); expect(issue).toMatchObject({ @@ -600,6 +614,16 @@ Redact secrets before uploading.`); isDraft: false, closesIssue: true, }, + // A closing reference past the first page, with no timeline sighting, still shows. + { + repository: "acme/web", + number: 61, + title: "fix(web): restore focus after paste", + url: "https://github.com/acme/web/pull/61", + state: "open", + isDraft: true, + closesIssue: true, + }, ]); // An event kind this page has no vocabulary for is dropped rather than guessed at. expect(issue.events.map((event) => [event.kind, event.detail])).toEqual([ diff --git a/packages/source-control-github/src/server/GitHubIssueTracker.ts b/packages/source-control-github/src/server/GitHubIssueTracker.ts index eed4578ff389c..bf1c20abae4e3 100644 --- a/packages/source-control-github/src/server/GitHubIssueTracker.ts +++ b/packages/source-control-github/src/server/GitHubIssueTracker.ts @@ -4,7 +4,9 @@ import { GraphQLClient, GraphQLClientError, GraphQLGroup } from "effect/graphql" import { IssueTrackerKind, type IssueCapabilities, + type IssueActor, type IssueInvolvement, + type IssueLabel, type IssueListSort, } from "@t3tools/contracts"; import { @@ -227,51 +229,75 @@ export const make = Effect.gen(function* () { const result = yield* client .IssueDetail({ owner, name, number }) .pipe(graphql(input.host, "getIssue")); - const detail = toIssueDetail(result); - const raw = result.repository?.issue; - if (detail === null || raw == null) return yield* notFound("getIssue"); - // Editing replaces these sets. Finish their pages before handing them to a client. + const repository = result.repository; + const raw = repository?.issue; + if (repository == null || raw == null) return yield* notFound("getIssue"); + // Editing replaces labels and assignees, and a closing reference can sit past the first + // page. Finish their pages before handing the issue to a client. let labels = raw.labels; let assignees = raw.assignees; + let closing = raw.closedByPullRequestsReferences; const seen = new Set(); - const allLabels = [...detail.labels]; - const allAssignees = [...detail.assignees]; - while (labels?.pageInfo.hasNextPage === true || assignees.pageInfo.hasNextPage) { + const moreLabels: IssueLabel[] = []; + const moreAssignees: IssueActor[] = []; + const allClosing = [...(closing?.nodes ?? [])]; + while ( + labels?.pageInfo.hasNextPage === true || + assignees.pageInfo.hasNextPage || + closing?.pageInfo.hasNextPage === true + ) { const labelsCursor = labels?.pageInfo.hasNextPage ? labels.pageInfo.endCursor : null; const assigneesCursor = assignees.pageInfo.hasNextPage ? assignees.pageInfo.endCursor : null; - const key = `${labelsCursor ?? ""} ${assigneesCursor ?? ""}`; + const closingPullRequestsCursor = closing?.pageInfo.hasNextPage + ? closing.pageInfo.endCursor + : null; + const key = `${labelsCursor ?? ""} ${assigneesCursor ?? ""} ${closingPullRequestsCursor ?? ""}`; if ( (labels?.pageInfo.hasNextPage && labelsCursor === null) || (assignees.pageInfo.hasNextPage && assigneesCursor === null) || + (closing?.pageInfo.hasNextPage && closingPullRequestsCursor === null) || seen.has(key) ) { return yield* invalid( "getIssue", - "GitHub did not return complete issue labels or assignees.", + "GitHub did not return complete issue labels, assignees or linked pull requests.", ); } seen.add(key); const page = yield* client - .IssueCollections({ owner, name, number, labelsCursor, assigneesCursor }) + .IssueCollections({ + owner, + name, + number, + labelsCursor, + assigneesCursor, + closingPullRequestsCursor, + withLabels: labelsCursor !== null, + withAssignees: assigneesCursor !== null, + withClosingPullRequests: closingPullRequestsCursor !== null, + }) .pipe(graphql(input.host, "getIssue")); const next = page.repository?.issue; if (next == null) return yield* notFound("getIssue"); - if (labels?.pageInfo.hasNextPage) { - labels = next.labels; - if (next.labels === null) { + if (labelsCursor !== null) { + if (next.labels == null) { return yield* invalid("getIssue", "GitHub did not return complete issue labels."); } - allLabels.push( + labels = next.labels; + moreLabels.push( ...(next.labels.nodes ?? []).flatMap((node) => node === null ? [] : [{ name: node.name, color: node.color }], ), ); } - if (assignees.pageInfo.hasNextPage) { + if (assigneesCursor !== null) { + if (next.assignees === undefined) { + return yield* invalid("getIssue", "GitHub did not return complete issue assignees."); + } assignees = next.assignees; - allAssignees.push( + moreAssignees.push( ...(next.assignees.nodes ?? []).flatMap((node) => node === null ? [] @@ -279,8 +305,36 @@ export const make = Effect.gen(function* () { ), ); } + if (closingPullRequestsCursor !== null) { + if (next.closedByPullRequestsReferences == null) { + return yield* invalid( + "getIssue", + "GitHub did not return complete linked pull requests.", + ); + } + closing = next.closedByPullRequestsReferences; + allClosing.push(...(closing.nodes ?? [])); + } } - return { ...detail, labels: allLabels, assignees: allAssignees }; + const detail = toIssueDetail({ + ...result, + repository: { + ...repository, + issue: { + ...raw, + closedByPullRequestsReferences: + raw.closedByPullRequestsReferences === null + ? null + : { ...raw.closedByPullRequestsReferences, nodes: allClosing }, + }, + }, + }); + if (detail === null) return yield* notFound("getIssue"); + return { + ...detail, + labels: [...detail.labels, ...moreLabels], + assignees: [...detail.assignees, ...moreAssignees], + }; }), getComments: (input) => diff --git a/packages/source-control-github/src/server/issues.graphql b/packages/source-control-github/src/server/issues.graphql index a0ca800e34ca5..42dc67a98a123 100644 --- a/packages/source-control-github/src/server/issues.graphql +++ b/packages/source-control-github/src/server/issues.graphql @@ -99,6 +99,10 @@ query IssueDetail($owner: String!, $name: String!, $number: Int!) { } } closedByPullRequestsReferences(first: 20, includeClosedPrs: true) { + pageInfo { + hasNextPage + endCursor + } nodes { number title @@ -363,10 +367,14 @@ query IssueCollections( $number: Int! $labelsCursor: String $assigneesCursor: String + $closingPullRequestsCursor: String + $withLabels: Boolean! + $withAssignees: Boolean! + $withClosingPullRequests: Boolean! ) { repository(owner: $owner, name: $name) { issue(number: $number) { - labels(first: 100, after: $labelsCursor) { + labels(first: 100, after: $labelsCursor) @include(if: $withLabels) { pageInfo { hasNextPage endCursor @@ -376,7 +384,7 @@ query IssueCollections( color } } - assignees(first: 100, after: $assigneesCursor) { + assignees(first: 100, after: $assigneesCursor) @include(if: $withAssignees) { pageInfo { hasNextPage endCursor @@ -387,6 +395,26 @@ query IssueCollections( avatarUrl } } + closedByPullRequestsReferences( + first: 100 + after: $closingPullRequestsCursor + includeClosedPrs: true + ) @include(if: $withClosingPullRequests) { + pageInfo { + hasNextPage + endCursor + } + nodes { + number + title + url + state + isDraft + repository { + nameWithOwner + } + } + } } } } diff --git a/packages/source-control-github/src/server/issues.graphql.ts b/packages/source-control-github/src/server/issues.graphql.ts index e71768b4fb2e3..d99defc174a5c 100644 --- a/packages/source-control-github/src/server/issues.graphql.ts +++ b/packages/source-control-github/src/server/issues.graphql.ts @@ -332,6 +332,8 @@ export interface NodesPullRequest extends Schema.Struct.Type {} @@ -1001,10 +1005,14 @@ export const IssueCollections = GraphQL.query("IssueCollections", { { name: "name", body: "String!" }, { name: "number", body: "Int!" }, { name: "labelsCursor", body: "String" }, - { name: "assigneesCursor", body: "String" } + { name: "assigneesCursor", body: "String" }, + { name: "closingPullRequestsCursor", body: "String" }, + { name: "withLabels", body: "Boolean!" }, + { name: "withAssignees", body: "Boolean!" }, + { name: "withClosingPullRequests", body: "Boolean!" } ], selections: [ - { name: "repository", body: ["(owner:$", "owner", " name:$", "name", "){issue(number:$", "number", "){labels(first:100 after:$", "labelsCursor", "){pageInfo{hasNextPage endCursor}nodes{name color}}assignees(first:100 after:$", "assigneesCursor", "){pageInfo{hasNextPage endCursor}nodes{login name avatarUrl}}}}"] } + { name: "repository", body: ["(owner:$", "owner", " name:$", "name", "){issue(number:$", "number", "){labels(first:100 after:$", "labelsCursor", ")@include(if:$", "withLabels", "){pageInfo{hasNextPage endCursor}nodes{name color}}assignees(first:100 after:$", "assigneesCursor", ")@include(if:$", "withAssignees", "){pageInfo{hasNextPage endCursor}nodes{login name avatarUrl}}closedByPullRequestsReferences(first:100 after:$", "closingPullRequestsCursor", " includeClosedPrs:true)@include(if:$", "withClosingPullRequests", "){pageInfo{hasNextPage endCursor}nodes{number title url state isDraft repository{nameWithOwner}}}}}"] } ], fragments: [] }, @@ -1013,7 +1021,11 @@ export const IssueCollections = GraphQL.query("IssueCollections", { name: Schema.String, number: Shared.Int, labelsCursor: Schema.optional(Schema.NullOr(Schema.String)), - assigneesCursor: Schema.optional(Schema.NullOr(Schema.String)) + assigneesCursor: Schema.optional(Schema.NullOr(Schema.String)), + closingPullRequestsCursor: Schema.optional(Schema.NullOr(Schema.String)), + withLabels: Schema.Boolean, + withAssignees: Schema.Boolean, + withClosingPullRequests: Schema.Boolean }, result: Schema.Struct({ /** Lookup a given repository by the owner and repository name. */ diff --git a/scripts/scenarios/github-closing-pr-after-first-page.e2e.ts b/scripts/scenarios/github-closing-pr-after-first-page.e2e.ts new file mode 100644 index 0000000000000..13797e21179e2 --- /dev/null +++ b/scripts/scenarios/github-closing-pr-after-first-page.e2e.ts @@ -0,0 +1,222 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import * as NetService from "@t3tools/shared/Net"; +import { expect } from "e2e"; +import * as Deferred from "effect/Deferred"; +import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; +import * as Path from "effect/Path"; +import * as Schema from "effect/Schema"; +import { FetchHttpClient, HttpClient, HttpClientResponse } from "effect/http"; + +import { APP_DIR, T3_HOME } from "../e2e.config.ts"; +import { run, ScenarioError } from "./shell.ts"; +import { prepareHome, start } from "./start-app.ts"; +import { makeState, runPromise, test, WEB } from "./t3.ts"; + +const HOST = "github.scenario.invalid"; +const SCOPE = "scenario/demo"; +const HOME = `${T3_HOME}-github-issue-links`; + +// Install only on the isolated server. The real GitHub adapter still builds and decodes requests. +const upstream = String.raw` +const host = "${HOST}"; +const scope = "${SCOPE}"; +const viewer = { login: "scenario-user" }; +const createdAt = "2026-10-01T00:00:00Z"; +const updatedAt = "2026-10-05T00:00:00Z"; +const row = { + __typename: "Issue", number: 42, title: "Release preparation", + url: "https://" + host + "/" + scope + "/issues/42", + state: "OPEN", stateReason: null, author: null, createdAt, updatedAt, closedAt: null, +}; +const empty = { nodes: [], totalCount: 0, pageInfo: { hasNextPage: false, endCursor: null } }; +const links = Array.from({ length: 21 }, (_, i) => ({ + number: 100 + i, + title: i === 20 ? "Backfill release metadata" : "Fix release check " + (i + 1), + url: "https://" + host + "/" + scope + "/pull/" + (100 + i), + state: "OPEN", + isDraft: false, + repository: { nameWithOwner: scope }, +})); +const timeline = [ + ...links.map((link) => ({ + __typename: "CrossReferencedEvent", id: "ref-" + link.number, createdAt, actor: null, + source: { ...link, __typename: "PullRequest" }, + })), + ...Array.from({ length: 100 }, (_, i) => ({ + __typename: "RenamedTitleEvent", id: "rename-" + i, + createdAt: new Date(Date.parse(updatedAt) - (99 - i) * 60_000).toISOString(), + actor: null, currentTitle: i === 99 ? row.title : "Release draft " + i, + })), +]; +function arg(query, field, argument, vars) { + const args = query.match(new RegExp("\\b" + field + "\\s*\\(([^)]*)\\)"))?.[1] ?? ""; + const value = args.match(new RegExp("\\b" + argument + '\\s*:\\s*(\\$[\\w]+|[0-9]+|"[^"]*")'))?.[1]; + if (value === undefined) return undefined; + if (value.startsWith("$")) return vars[value.slice(1)]; + return JSON.parse(value); +} + +function page(nodes, query, field, vars) { + const filter = arg(query, field, "query", vars)?.toLowerCase(); + const matches = filter ? nodes.filter((node) => node.name?.toLowerCase().includes(filter)) : nodes; + const start = Number(arg(query, field, "after", vars) ?? 0); + const end = start + (arg(query, field, "first", vars) ?? 100); + const last = arg(query, field, "last", vars); + return { + nodes: last === undefined ? matches.slice(start, end) : matches.slice(-last), + totalCount: matches.length, + pageInfo: { hasNextPage: end < matches.length, endCursor: String(end) }, + }; +} + +const fetchActual = globalThis.fetch; +globalThis.fetch = async (input, init) => { + const request = new Request(input, init); + const url = new URL(request.url); + if (url.hostname !== host) return fetchActual(input, init); + if (url.pathname === "/api/v3/user") return Response.json({ ...viewer, name: null }); + if (url.pathname !== "/api/graphql") return new Response(null, { status: 404 }); + const { query, variables = {} } = await request.json(); + if (/\bsearch\s*\(/.test(query)) { + return Response.json({ data: { search: { ...empty, nodes: [ + { ...row, assignees: empty, labels: empty, comments: { totalCount: 0 } }, + ] } } }); + } + const repository = { + viewerPermission: "WRITE", + labels: empty, assignableUsers: empty, + issue: { + ...row, labels: empty, assignees: empty, body: "Check the release notes.", + viewerCanUpdate: true, viewerCanClose: true, viewerCanReopen: false, reactionGroups: [], + locked: false, activeLockReason: null, viewerCanComment: true, + comments: { nodes: [], totalCount: 0, pageInfo: { hasPreviousPage: false, startCursor: null } }, + closedByPullRequestsReferences: page(links, query, "closedByPullRequestsReferences", variables), + timelineItems: page(timeline, query, "timelineItems", variables), + }, + }; + return Response.json({ data: { viewer, repository } }); +}; +`; + +function startFixtureServer(webOrigin: string) { + const ready = Promise.withResolvers<{ origin: string; token: string }>(); + const server = Effect.runFork( + Effect.gen(function* () { + yield* prepareHome(HOME); + const port = yield* (yield* NetService.NetService).reserveLoopbackPort(); + const origin = `http://127.0.0.1:${port}`; + const token = yield* Deferred.make(); + const path = yield* Path.Path; + const searchPath = (yield* HostProcess.Environment).PATH ?? ""; + const node = yield* HostProcess.ExecutablePath; + const child = yield* start({ + cwd: APP_DIR, + command: node, + args: [ + `--import=data:text/javascript;base64,${Buffer.from(upstream).toString("base64")}`, + "apps/server/src/bin.ts", + "serve", + "--host", + "127.0.0.1", + "--port", + String(port), + "--base-dir", + HOME, + "--dev-url", + webOrigin, + ], + env: { + PATH: `${path.join(HOME, "bin")}:${searchPath}`, + HOME, + GH_HOST: HOST, + GH_ENTERPRISE_TOKEN: "scenario-only-token", + T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "0", + }, + onLine: (line) => { + const value = /^Token:\s*(\S+)/.exec(line)?.[1]; + return value === undefined + ? Effect.void + : Deferred.succeed(token, value).pipe(Effect.asVoid); + }, + }); + const exited = child.exitCode.pipe( + Effect.flatMap( + (code) => new ScenarioError({ message: `Fixture server exited (${code}).` }), + ), + ); + ready.resolve({ origin, token: yield* Effect.raceFirst(Deferred.await(token), exited) }); + return yield* exited; + }).pipe(Effect.scoped, Effect.provide([NodeServices.layer, NetService.layer])), + ); + void Effect.runPromise(Fiber.join(server)).catch(ready.reject); + return { ready: ready.promise, stop: () => Effect.runPromise(Fiber.interrupt(server)) }; +} + +test( + "A closing pull request remains visible after its timeline reference ages out", + WEB, + async ({ t3, app, browser, screen }) => { + const workspace = await t3.project("Release"); + const server = startFixtureServer(app.baseUrl ?? ""); + try { + const { origin, token } = await server.ready; + const repository = await runPromise( + Effect.map(Path.Path, (path) => path.join(HOME, "release")), + ); + await runPromise(run("git", ["clone", "--quiet", workspace, repository])); + await runPromise( + run("git", ["remote", "set-url", "origin", `https://${HOST}/${SCOPE}.git`], { + cwd: repository, + }), + ); + const added = await runPromise(makeState(HOME).cli(["project", "add", repository])); + const projectId = /Added project (\S+) /.exec(added.stdout)?.[1]; + if (!projectId) throw new Error("The fixture project was not added."); + const { environmentId } = await runPromise( + HttpClient.get(`${origin}/.well-known/t3/environment`).pipe( + Effect.flatMap(HttpClientResponse.filterStatusOk), + Effect.flatMap( + HttpClientResponse.schemaBodyJson(Schema.Struct({ environmentId: Schema.String })), + ), + Effect.provide(FetchHttpClient.layer), + ), + ); + const link = new URLSearchParams({ + key: "42", + tracker: "github", + scope: SCOPE, + selectedHost: HOST, + selectedEnvironmentId: environmentId, + selectedProjectId: projectId, + }); + + await t3.open("/settings/connections"); + await screen.getByRole("button", "Add environment").tap(); + const dialog = screen.getByRole("dialog"); + await dialog.getByPlaceholder("backend.example.com").fill(origin); + await dialog.getByPlaceholder("PAIRCODE").fill(token); + await dialog.getByRole("button", "Add environment").tap(); + await screen.getByRole("button", "More actions for Scenario").waitFor(); + await app.open(`/issues?${link}`); + + await screen.getByRole("button", /Fix release check 20/).waitFor(); + try { + await expect(screen.getByRole("button", /Backfill release metadata/)).toBeVisible(); + } finally { + await browser.evaluate(() => { + const rows = document.querySelectorAll("button"); + const row = + [...rows].find((button) => button.textContent?.includes("Backfill release metadata")) ?? + [...rows].find((button) => button.textContent?.includes("Fix release check 20")); + row?.scrollIntoView({ block: "center" }); + return null; + }); + await app.screenshot("last-linked-pull-request"); + } + } finally { + await server.stop(); + } + }, +); From b648395fa5afe9b017252436f7328c58b787d56e Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Wed, 18 Nov 2026 09:30:24 +0100 Subject: [PATCH 09/25] fix(web): older comments no longer reappear after refreshing an issue (#38489) Co-authored-by: Julius Marminge --- .../src/features/issues/IssueRouteScreen.tsx | 62 ++----- apps/mobile/src/state/use-pull-to-refresh.ts | 4 +- .../chat/RightPanelSurfaceContent.tsx | 2 +- .../src/components/issue/IssueDetailPanel.tsx | 50 ++--- apps/web/src/components/issue/IssuesPage.tsx | 2 +- .../client-runtime/src/state/issues.test.ts | 66 +++++-- packages/client-runtime/src/state/issues.ts | 88 ++++++++- ...esh-discards-pending-older-comments.e2e.ts | 175 ++++++++++++++++++ 8 files changed, 349 insertions(+), 100 deletions(-) create mode 100644 scripts/scenarios/issues-refresh-discards-pending-older-comments.e2e.ts diff --git a/apps/mobile/src/features/issues/IssueRouteScreen.tsx b/apps/mobile/src/features/issues/IssueRouteScreen.tsx index 354a86284dd3a..9f6ae1a7aaa7a 100644 --- a/apps/mobile/src/features/issues/IssueRouteScreen.tsx +++ b/apps/mobile/src/features/issues/IssueRouteScreen.tsx @@ -1,7 +1,8 @@ +import { RegistryContext, useAtomValue } from "@effect/atom-react"; import { StackActions, useNavigation, type StaticScreenProps } from "@react-navigation/native"; import { issueEventSentence } from "@t3tools/client-runtime/issue-presentation"; import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients"; -import { prependIssueComments } from "@t3tools/client-runtime/state/issues"; +import { createIssueCommentPager } from "@t3tools/client-runtime/state/issues"; import type { IssueComment, IssueEvent, @@ -12,7 +13,7 @@ import type { } from "@t3tools/contracts"; import { AsyncResult } from "effect/reactivity"; import { T, useGT, useMessages, Var } from "gt-react-native"; -import { useRef, useState } from "react"; +import { useContext, useState } from "react"; import { Linking, Platform, Pressable, Share, View } from "react-native"; import { KeyboardStickyView } from "react-native-keyboard-controller"; @@ -403,6 +404,9 @@ function IssueRoute({ params }: { readonly params: IssueParams }) { const detailAtom = issueEnvironment.detail(target); const detailQuery = useEnvironmentQuery(detailAtom); const pullRefresh = usePullToRefresh(detailAtom); + const registry = useContext(RegistryContext); + const [pager] = useState(() => createIssueCommentPager(detailAtom)); + const { comments, nextCursor, loadingOlder, canLoadOlder } = useAtomValue(pager.view); const detail = detailQuery.data; const issue: IssueSummary | null = detail ?? params.initialSummary ?? null; const access = useIssueAccess(params, detail); @@ -410,25 +414,13 @@ function IssueRoute({ params }: { readonly params: IssueParams }) { const loadComments = useAtomCommand(issueEnvironment.comments, { reportFailure: false }); const postComment = useAtomCommand(issueEnvironment.comment, { reportFailure: false }); const setState = useAtomCommand(issueEnvironment.setState, { reportFailure: false }); - const [older, setOlder] = useState<{ - readonly seed: string | null; - readonly comments: ReadonlyArray; - readonly cursor: string | null; - } | null>(null); - const [busy, setBusy] = useState<"older" | "comment" | "state" | null>(null); + const [busy, setBusy] = useState<"comment" | "state" | null>(null); const [error, setError] = useState(null); const [composerHeight, setComposerHeight] = useState(0); - // Older pages are tied to the cursor the detail was read with; a refreshed detail starts over. - const olderComments = detail && older?.seed === detail.commentsCursor ? older.comments : []; - const nextCursor = !detail - ? null - : older?.seed === detail.commentsCursor - ? older.cursor - : detail.commentsCursor; const timeline = detail ? [ - ...prependIssueComments(detail.comments, olderComments).map((comment) => ({ + ...comments.map((comment) => ({ key: `c:${comment.id}`, at: comment.createdAt, content: ( @@ -447,7 +439,7 @@ function IssueRoute({ params }: { readonly params: IssueParams }) { kind: NonNullable, command: () => Promise>, ) => { - if (busy !== null) return false; + if (busy !== null || registry.get(pager.view).loadingOlder) return false; setBusy(kind); setError(null); const failure = issueCommandError(await command()); @@ -457,28 +449,13 @@ function IssueRoute({ params }: { readonly params: IssueParams }) { if (failure === null) refreshIssueLists(target.environmentId); return failure === null; }; - // Counts refreshes, so a page asked for before one is not laid over the read that follows it. - const refreshes = useRef(0); const loadOlder = async () => { - if (!detail || nextCursor === null || busy !== null) return; - const asked = refreshes.current; - setBusy("older"); - setError(null); - const result = await loadComments({ - ...target, - input: { ...target.input, cursor: nextCursor }, - }); - setBusy(null); - if (asked !== refreshes.current) return; - if (AsyncResult.isFailure(result)) { - setError(gt("Older comments could not be read.")); - return; - } - setOlder({ - seed: detail.commentsCursor, - comments: prependIssueComments(olderComments, result.value.comments), - cursor: result.value.nextCursor, + if (busy !== null) return; + const failure = await pager.loadOlder(registry, (cursor) => { + setError(null); + return loadComments({ ...target, input: { ...target.input, cursor } }); }); + if (failure) setError(gt("Older comments could not be read.")); }; const submitComment = (body: string) => access?.comment === true @@ -575,12 +552,7 @@ function IssueRoute({ params }: { readonly params: IssueParams }) { refreshControl={ { - // Older pages are cached under the cursor, which a refresh can hand back unchanged. - refreshes.current += 1; - setOlder(null); - pullRefresh.onRefresh(); - }} + onRefresh={() => void pager.refresh(registry, pullRefresh.onRefresh)} /> } contentContainerStyle={{ @@ -652,8 +624,8 @@ function IssueRoute({ params }: { readonly params: IssueParams }) { {nextCursor !== null ? ( @@ -904,7 +882,7 @@ export function IssueDetailPanel({ size="sm" variant="outline" className="self-start" - disabled={loadingOlder} + disabled={!canLoadOlder} onClick={() => void loadOlder()} > {loadingOlder ? Loading… : Load older comments} diff --git a/apps/web/src/components/issue/IssuesPage.tsx b/apps/web/src/components/issue/IssuesPage.tsx index fb2d1b981e4e6..307aca3741398 100644 --- a/apps/web/src/components/issue/IssuesPage.tsx +++ b/apps/web/src/components/issue/IssuesPage.tsx @@ -772,7 +772,7 @@ export function IssuesPage() { > {renderedSurface.kind === "issue" ? ( & { key: string }): IssueListEntry { @@ -67,19 +68,56 @@ describe("mergeIssueListPage", () => { }); }); -describe("prependIssueComments", () => { - const comment = (id: string): IssueComment => ({ - id, - author: null, - body: id, - createdAt: "2026-10-01T00:00:00.000Z", - url: null, - }); +const comment = (id: string): IssueComment => ({ + id, + author: null, + body: id, + createdAt: "2026-10-01T00:00:00.000Z", + url: null, +}); + +describe("createIssueCommentPager", () => { + it("drops older pages on refresh, including one still loading, and pauses paging until it ends", async () => { + // The refreshed detail hands back the same cursor, so only the refresh itself can tell pages apart. + const detail = Atom.make( + AsyncResult.success({ comments: [comment("newest")], commentsCursor: "first-page" }), + ); + const pager = createIssueCommentPager(detail); + const registry = AtomRegistry.make(); + const unmount = registry.mount(pager.view); + const ids = () => registry.get(pager.view).comments.map(({ id }) => id); + const cursors: string[] = []; + const page = AsyncResult.success({ + comments: [comment("older"), comment("newest")], + nextCursor: "second-page", + }); + const read = async (cursor: string) => { + cursors.push(cursor); + return page; + }; + try { + await pager.loadOlder(registry, read); + expect(ids()).toEqual(["older", "newest"]); - it("puts older comments first and drops ones already shown", () => { - const current = [comment("c3"), comment("c4")]; - const older = [comment("c1"), comment("c2"), comment("c3")]; - expect(prependIssueComments(current, older).map((c) => c.id)).toEqual(["c1", "c2", "c3", "c4"]); + const pending = Promise.withResolvers(); + const inFlight = pager.loadOlder(registry, () => pending.promise); + const refreshed = Promise.withResolvers(); + const refresh = pager.refresh(registry, () => refreshed.promise); + pending.resolve(page); + await inFlight; + expect(ids()).toEqual(["newest"]); + + await pager.loadOlder(registry, read); + expect(registry.get(pager.view).canLoadOlder).toBe(false); + refreshed.resolve(); + await refresh; + await pager.loadOlder(registry, read); + expect(cursors).toEqual(["first-page", "first-page"]); + expect(ids()).toEqual(["older", "newest"]); + } finally { + unmount(); + registry.dispose(); + } }); }); diff --git a/packages/client-runtime/src/state/issues.ts b/packages/client-runtime/src/state/issues.ts index 31d23bc3ebe82..3175602dfaa42 100644 --- a/packages/client-runtime/src/state/issues.ts +++ b/packages/client-runtime/src/state/issues.ts @@ -4,6 +4,8 @@ import { type IssueAssigneeCandidate, type IssueCandidates, type IssueComment, + type IssueCommentsPage, + type IssueDetail, type IssueLabelCandidate, type IssueListEntry, type IssueListInput, @@ -17,6 +19,7 @@ import * as Option from "effect/Option"; import { AsyncResult, Atom, type AtomRegistry } from "effect/reactivity"; import { + type AtomCommandResult, createAtomCommandScheduler, createEnvironmentRpcCommand, createEnvironmentRpcQueryAtomFamily, @@ -49,7 +52,7 @@ export function mergeIssueListPage( } /** Older comments go in front: the detail carries the newest page and pages walk backwards. */ -export function prependIssueComments( +function prependIssueComments( current: ReadonlyArray, older: ReadonlyArray, ): ReadonlyArray { @@ -58,6 +61,89 @@ export function prependIssueComments( return [...older.filter((comment) => !seen.has(comment.id)), ...current]; } +export function createIssueCommentPager( + detailAtom: Atom.Atom< + AsyncResult.AsyncResult, E> + >, +) { + const state = Atom.make<{ + readonly older: (IssueCommentsPage & { readonly seed: string }) | null; + readonly loadingOlder: boolean; + readonly refreshing: boolean; + readonly refreshes: number; + }>({ older: null, loadingOlder: false, refreshing: false, refreshes: 0 }); + const page = Atom.make((get) => { + const detailResult = get(detailAtom); + const detail = AsyncResult.getOrElse(detailResult, () => null); + const current = get(state); + const seed = detail?.commentsCursor ?? null; + const older = current.older?.seed === seed ? current.older : null; + const nextCursor = older ? older.nextCursor : seed; + return { + comments: detail?.comments ?? [], + seed, + older, + nextCursor, + loadingOlder: current.loadingOlder, + unavailable: detailResult.waiting || current.refreshing || current.loadingOlder, + }; + }); + const view = Atom.make((get) => { + const { comments, older, nextCursor, loadingOlder, unavailable } = get(page); + return { + comments: prependIssueComments(comments, older?.comments ?? []), + nextCursor, + loadingOlder, + canLoadOlder: nextCursor !== null && !unavailable, + }; + }); + + return { + view, + async refresh(registry: AtomRegistry.AtomRegistry, read: () => void | Promise) { + const current = registry.get(state); + if (current.refreshing) return; + // The refreshed detail can return the same cursor, so invalidate outstanding pages explicitly. + registry.set(state, { + ...current, + older: null, + refreshing: true, + refreshes: current.refreshes + 1, + }); + try { + await read(); + } finally { + registry.set(state, { ...registry.get(state), refreshing: false }); + } + }, + async loadOlder( + registry: AtomRegistry.AtomRegistry, + read: (cursor: string) => Promise>, + ) { + const { seed, older, nextCursor, unavailable } = registry.get(page); + if (seed === null || nextCursor === null || unavailable) return; + const current = registry.get(state); + registry.set(state, { ...current, loadingOlder: true }); + try { + const result = await read(nextCursor); + const latest = registry.get(state); + if (latest.refreshes !== current.refreshes) return; + if (result._tag === "Failure") return result; + registry.set(state, { + ...latest, + older: { + seed, + comments: prependIssueComments(older?.comments ?? [], result.value.comments), + nextCursor: result.value.nextCursor, + }, + }); + } finally { + registry.set(state, { ...registry.get(state), loadingOlder: false }); + } + }, + }; +} + /** * Every read goes to a tracker API over the environment, so results are reused for a short while * and refreshed explicitly. Mutations run serially per environment: changes to one issue are diff --git a/scripts/scenarios/issues-refresh-discards-pending-older-comments.e2e.ts b/scripts/scenarios/issues-refresh-discards-pending-older-comments.e2e.ts new file mode 100644 index 0000000000000..220da5c4c82d7 --- /dev/null +++ b/scripts/scenarios/issues-refresh-discards-pending-older-comments.e2e.ts @@ -0,0 +1,175 @@ +/// +import type { IssueComment, IssueCommentsPage, IssueDetail, IssueRef } from "@t3tools/contracts"; +import { expect } from "e2e"; + +import { test, WEB } from "./t3.ts"; + +test( + "A page requested before refreshing an issue does not restore old comments", + WEB, + async ({ t3, app, browser, screen }) => { + await t3.project("demo"); + await browser.addInitScript(() => { + const pendingPage = new Promise((resolve) => { + Object.assign(window, { releaseOldIssuePage: () => resolve() }); + }); + const comment = (id: string, body: string, day: string): IssueComment => ({ + id, + body, + author: null, + createdAt: `2026-10-${day}T00:00:00.000Z`, + url: null, + }); + let refreshed = false; + let pendingRefresh: Promise | undefined; + Object.assign(window, { + armIssueRefresh: () => { + refreshed = true; + }, + holdIssueRefresh: () => { + const { promise, resolve } = Promise.withResolvers(); + pendingRefresh = promise; + Object.assign(window, { releaseIssueRefresh: resolve }); + }, + }); + // Keep the real socket for all other RPCs. Supply three pages of an unchanged GitHub + // comment history and hold the last page until the refreshed detail has rendered. + const send = WebSocket.prototype.send; + WebSocket.prototype.send = function (data) { + const request: { + _tag: string; + id: string; + tag: string; + payload: IssueRef & { cursor?: string }; + } | null = typeof data === "string" ? JSON.parse(data) : null; + if (request?._tag !== "Request") return send.call(this, data); + const reply = (value: IssueDetail | IssueCommentsPage) => + this.dispatchEvent( + new MessageEvent("message", { + data: JSON.stringify({ + _tag: "Exit", + requestId: request.id, + exit: { _tag: "Success", value }, + }), + }), + ); + if (request.tag === "issues.detail") { + const { projectId, tracker, scope, key } = request.payload; + const detail: IssueDetail = { + projectId, + tracker, + scope, + key, + host: "github.com", + displayKey: "#42", + projectTitle: "demo", + title: refreshed ? "Pagination issue after refresh" : "Pagination issue", + body: "Comment history", + url: "https://github.com/example/demo/issues/42", + author: null, + state: { category: "open", name: "Open" }, + createdAt: "2026-10-01T00:00:00.000Z", + updatedAt: "2026-10-04T00:00:00.000Z", + closedAt: null, + assignees: [], + labels: [], + commentCount: 201, + writable: false, + capabilities: { + create: false, + edit: false, + comment: false, + labels: false, + assignees: false, + reactions: false, + templates: false, + linkedPullRequests: false, + events: false, + search: true, + }, + viewerPermissions: { + setState: false, + comment: false, + edit: false, + labels: false, + assignees: false, + }, + states: [], + viewer: null, + comments: [comment("newest", "Newest comment", "04")], + commentsCursor: "first-older-page", + events: [], + linkedPullRequests: [], + }; + if (pendingRefresh) { + void pendingRefresh.then(() => reply(detail)); + pendingRefresh = undefined; + return; + } + queueMicrotask(() => reply(detail)); + } else if (request.tag === "issues.comments") { + if (request.payload.cursor === "first-older-page") { + queueMicrotask(() => + reply({ + comments: [comment("older", "First older comment", "03")], + nextCursor: "last-page", + }), + ); + } else if (request.payload.cursor === "last-page") { + void pendingPage.then(() => + reply({ + comments: [comment("oldest", "Oldest comment", "02")], + nextCursor: null, + }), + ); + } else return send.call(this, data); + } else return send.call(this, data); + }; + }); + + await t3.open("/issues?selectedProjectId=demo&tracker=github&scope=example/demo&key=42"); + const loadOlder = screen.getByRole("button", "Load older comments", { exact: true }); + // The issues route compiles on first open, which can outlast the 30 s action timeout. + await loadOlder.waitFor({ timeout: 60_000 }); + await loadOlder.tap(); + await screen.getByText("First older comment", { exact: true }).waitFor(); + await loadOlder.tap(); + const loading = screen.getByRole("button", "Loading…", { exact: true }); + await loading.waitFor(); + await browser.evaluate(() => { + (window as unknown as { armIssueRefresh: () => void }).armIssueRefresh(); + return null; + }); + await screen.getByRole("button", "Refresh issue", { exact: true }).tap(); + await screen.getByText("Pagination issue after refresh", { exact: true }).waitFor(); + + await browser.evaluate(() => { + (window as unknown as { releaseOldIssuePage: () => void }).releaseOldIssuePage(); + return null; + }); + const activity = 'section[aria-label^="Activity"]'; + await loading.waitFor({ state: "hidden" }); + await browser.evaluate((selector) => { + document.querySelector(selector)?.scrollIntoView({ block: "start" }); + return null; + }, activity); + await app.screenshot("activity-after-refresh-and-late-page"); + await expect(browser.locator(activity)).not.toContainText("First older comment"); + + await browser.evaluate(() => { + (window as unknown as { holdIssueRefresh: () => void }).holdIssueRefresh(); + return null; + }); + const refresh = screen.getByRole("button", "Refresh issue", { exact: true }); + await refresh.tap(); + await expect(refresh).toBeDisabled(); + await expect(loadOlder).toBeDisabled(); + await browser.evaluate(() => { + (window as unknown as { releaseIssueRefresh: () => void }).releaseIssueRefresh(); + return null; + }); + await expect(loadOlder).toBeEnabled(); + await loadOlder.tap(); + await screen.getByText("First older comment", { exact: true }).waitFor(); + }, +); From 9758cf9e13d74516bc872eebb154c0b4b3b8aa23 Mon Sep 17 00:00:00 2001 From: Illia Panasenko Date: Wed, 18 Nov 2026 09:38:52 +0100 Subject: [PATCH 10/25] fix(web): typing into a simulator no longer answers a waiting question (#38476) Co-authored-by: Julius Marminge --- .../ComposerPendingUserInputPanel.browser.test.tsx | 12 ++++++++++++ .../chat/ComposerPendingUserInputPanel.tsx | 2 +- 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/apps/web/src/components/chat/ComposerPendingUserInputPanel.browser.test.tsx b/apps/web/src/components/chat/ComposerPendingUserInputPanel.browser.test.tsx index 40022b45bc845..2bb38a3782f50 100644 --- a/apps/web/src/components/chat/ComposerPendingUserInputPanel.browser.test.tsx +++ b/apps/web/src/components/chat/ComposerPendingUserInputPanel.browser.test.tsx @@ -73,6 +73,18 @@ it.each<{ focus: string; control: ReactNode; toggles: boolean }>([ ), toggles: false, }, + { + focus: "a device screen that takes the key", + control: ( +
event.preventDefault()} + /> + ), + toggles: false, + }, ])( "digit shortcut with focus in $focus toggles an option: $toggles", async ({ control, toggles }) => { diff --git a/apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx b/apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx index 6598b8f1afed2..c637e3b7ef477 100644 --- a/apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx +++ b/apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx @@ -153,7 +153,7 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard( useEffect(() => { if (!activeQuestion || responseDisabled || isCollapsed || backgroundThread) return; const handler = (event: globalThis.KeyboardEvent) => { - if (event.metaKey || event.ctrlKey || event.altKey) return; + if (event.defaultPrevented || event.metaKey || event.ctrlKey || event.altKey) return; const target = event.target; if (isInSideChatPane(target)) return; if (target instanceof HTMLInputElement || target instanceof HTMLTextAreaElement) { From 8a6342e761357feff652a57d3dd16f0c78026c25 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 18 Nov 2026 00:39:46 -0800 Subject: [PATCH 11/25] fix(server): keep-awake logs a hold only once acquired and reports why the inhibitor failed (#38505) --- apps/server/src/background/KeepAwake.ts | 77 +++++++++++++++++-------- 1 file changed, 52 insertions(+), 25 deletions(-) diff --git a/apps/server/src/background/KeepAwake.ts b/apps/server/src/background/KeepAwake.ts index 429e49b9c9941..4fd31e59d00c5 100644 --- a/apps/server/src/background/KeepAwake.ts +++ b/apps/server/src/background/KeepAwake.ts @@ -1,7 +1,9 @@ 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 Ref from "effect/Ref"; import * as ChildProcess from "effect/process/ChildProcess"; import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; import * as Schedule from "effect/Schedule"; @@ -19,9 +21,12 @@ import * as Settings from "../serverSettings.ts"; const RELEASE_GRACE = Duration.seconds(60); // ES_CONTINUOUS | ES_SYSTEM_REQUIRED, held by the calling thread until the script ends. -const WINDOWS_HOLD_SCRIPT = `$t = Add-Type -Name Power -Namespace T3 -PassThru -MemberDefinition '[DllImport("kernel32.dll")] public static extern uint SetThreadExecutionState(uint f);'; [void]$t::SetThreadExecutionState([uint32]2147483649)`; +const WINDOWS_HOLD_SCRIPT = `$t = Add-Type -Name Power -Namespace T3 -PassThru -MemberDefinition '[DllImport("kernel32.dll")] public static extern uint SetThreadExecutionState(uint f);'; [void]$t::SetThreadExecutionState([uint32]2147483649); [Console]::Out.WriteLine()`; -/** Each command holds its inhibitor until it exits, and exits on its own if the server dies. */ +/** + * Each command writes a line to stdout once it holds its inhibitor, holds it until it exits, and + * exits on its own if the server dies. + */ function inhibitorCommand( platform: NodeJS.Platform, serverPid: number, @@ -49,7 +54,11 @@ function inhibitorCommand( } switch (platform) { case "darwin": - return { command: "caffeinate", args: ["-i", "-w", String(serverPid)], stdin: "ignore" }; + return { + command: "sh", + args: ["-c", 'echo && exec caffeinate -i -w "$0"', String(serverPid)], + stdin: "ignore", + }; case "linux": return { command: "systemd-inhibit", @@ -58,10 +67,11 @@ function inhibitorCommand( "--who=T3 Code", "--why=Agents are working", "--mode=block", - "tail", - `--pid=${serverPid}`, - "-f", - "/dev/null", + // systemd-inhibit starts this only after logind grants the lock. + "sh", + "-c", + 'echo && exec tail --pid="$0" -f /dev/null', + String(serverPid), ], stdin: "ignore", }; @@ -117,8 +127,12 @@ const retryWithBackoff = class KeepAwakeInhibitorExited extends Schema.TaggedError()( "KeepAwakeInhibitorExited", - { exitCode: Schema.Number }, -) {} + { exitCode: Schema.Number, stderr: Schema.String }, +) { + override get message(): string { + return `sleep inhibitor exited with code ${this.exitCode}${this.stderr ? `: ${this.stderr}` : ""}`; + } +} export const layer = Layer.effectDiscard( Effect.gen(function* () { @@ -188,29 +202,42 @@ export const layer = Layer.effectDiscard( }), ); - const holdOnce = spawner - .spawn( + const holdOnce = Effect.gen(function* () { + const child = yield* spawner.spawn( ChildProcess.make(command.command, command.args, { detached: false, shell: false, stdin: command.stdin, - stdout: "ignore", - stderr: "ignore", + stdout: "pipe", + stderr: "pipe", }), - ) - .pipe( - Effect.tap((child) => - Effect.logInfo("keep-awake holding sleep inhibitor", { pid: Number(child.pid) }), - ), - Effect.tap(() => - Effect.addFinalizer(() => Effect.logInfo("keep-awake released sleep inhibitor")), - ), - Effect.flatMap((child) => child.exitCode), - Effect.flatMap((exitCode) => - Effect.fail(new KeepAwakeInhibitorExited({ exitCode: Number(exitCode) })), + ); + const stderr = yield* child.stderr.pipe( + Stream.decodeText(), + Stream.mkString, + Effect.forkScoped, + ); + const held = yield* Ref.make(false); + yield* Effect.addFinalizer(() => + Effect.when(Effect.logInfo("keep-awake released sleep inhibitor"), Ref.get(held)), + ); + yield* child.stdout.pipe( + Stream.take(1), + Stream.runForEach(() => + Ref.set(held, true).pipe( + Effect.andThen( + Effect.logInfo("keep-awake holding sleep inhibitor", { pid: Number(child.pid) }), + ), + ), ), - Effect.scoped, + Effect.forkScoped, ); + const exitCode = yield* child.exitCode; + return yield* new KeepAwakeInhibitorExited({ + exitCode: Number(exitCode), + stderr: (yield* Fiber.join(stderr)).trim(), + }); + }).pipe(Effect.scoped); const hold = holdOnce.pipe( retryWithBackoff("keep-awake sleep inhibitor stopped"), Effect.ignore, From 37e9217b5696f33f347cdd282830e897a04c10ab Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 18 Nov 2026 00:46:23 -0800 Subject: [PATCH 12/25] fix(server): write the Windows service task as UTF-16LE so non-ASCII paths survive (#38494) --- apps/server/src/cli/update.ts | 5 +++- apps/server/src/cloud/bootService.test.ts | 7 +++-- apps/server/src/cloud/bootService.ts | 36 ++++++++++++++--------- apps/server/src/cloud/selfUpdate.ts | 4 +-- apps/server/src/cloud/serviceProtocol.ts | 10 +++++++ apps/server/src/serviceLauncher.test.ts | 3 +- apps/server/src/serviceLauncher.ts | 23 ++++++++++----- 7 files changed, 61 insertions(+), 27 deletions(-) diff --git a/apps/server/src/cli/update.ts b/apps/server/src/cli/update.ts index aaac21b6de514..b7b76f2f34223 100644 --- a/apps/server/src/cli/update.ts +++ b/apps/server/src/cli/update.ts @@ -38,6 +38,7 @@ import { } from "../cloud/pinnedRuntime.ts"; import { compareExactServiceVersions, + decodeServiceUnit, isExactServiceVersion, SERVICE_LAUNCHER_PROTOCOL, } from "../cloud/serviceProtocol.ts"; @@ -574,7 +575,9 @@ export const runUpdate = Effect.fn("cli.update.run")(function* (input: { // A handed-off service install rewrites the unit later, while the old launcher may be stopped. if (servicePlan?.handedOff !== true) { // A stopped service's unit still names the launcher runtime it will start. - const unit = yield* fs.readFileString(status.unitPath).pipe(Effect.option); + const unit = yield* fs + .readFile(status.unitPath) + .pipe(Effect.map(decodeServiceUnit), Effect.option); yield* prunePinnedRuntimes({ baseDir: input.baseDir, keep: [currentVersion, targetVersion], diff --git a/apps/server/src/cloud/bootService.test.ts b/apps/server/src/cloud/bootService.test.ts index 4d89805bb19d3..523f495a5d6e9 100644 --- a/apps/server/src/cloud/bootService.test.ts +++ b/apps/server/src/cloud/bootService.test.ts @@ -22,6 +22,7 @@ import { serviceLauncherLockPath } from "../serviceLauncher.ts"; import * as BootService from "./bootService.ts"; import { pinnedRuntimePaths } from "./pinnedRuntime.ts"; import { + decodeServiceUnit, disabledServiceTask, parseServiceState, serviceTaskIsDisabled, @@ -256,7 +257,7 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* ( input.command === "schtasks" && input.args[0] !== "/Create" && control.task === undefined; if (input.command === "schtasks" && !failed) { if (input.args[0] === "/Create") { - const xml = yield* fs.readFileString(input.args[2] ?? ""); + const xml = decodeServiceUnit(yield* fs.readFile(input.args[2] ?? "")); control.task = { xml, enabled: !serviceTaskIsDisabled(xml) }; } if (control.task !== undefined && input.args[0] === "/Change") { @@ -1443,7 +1444,7 @@ process.disconnect(); const { service, fs, statePath, commands, control, runtime } = yield* makeHarness("win32"); const path = yield* Path.Path; const plan = yield* service.install(); - const task = yield* fs.readFileString(plan.unitPath); + const task = decodeServiceUnit(yield* fs.readFile(plan.unitPath)); expect(plan.unitPath).toBe( path.join(path.dirname(plan.baseDir), "AppData", "Local", "t3code", "t3code-task.xml"), @@ -1452,6 +1453,8 @@ process.disconnect(); expect(BootService.bootServiceBaseDirOf(task)).toBe(plan.baseDir); expect(task).toContain("PC\\theo"); expect(task).toContain("IgnoreNew"); + // schtasks decodes undeclared UTF-8 with the ANSI code page; UTF-16LE with a BOM is read as is. + expect([...(yield* fs.readFile(plan.unitPath)).subarray(0, 2)]).toEqual([0xff, 0xfe]); expect(parseServiceState(yield* fs.readFileString(statePath))).toEqual({ protocol: SERVICE_LAUNCHER_PROTOCOL, activeVersion: "1.2.3", diff --git a/apps/server/src/cloud/bootService.ts b/apps/server/src/cloud/bootService.ts index 0f94aaad95bac..d624e02c7ecfb 100644 --- a/apps/server/src/cloud/bootService.ts +++ b/apps/server/src/cloud/bootService.ts @@ -38,7 +38,9 @@ import { SERVICE_STATE_FILE, SERVICE_UNIT_ENV, compareExactServiceVersions, + decodeServiceUnit, disabledServiceTask, + encodeServiceTask, serviceTaskIsDisabled, serviceUnitBaseDirOf as bootServiceBaseDirOf, serviceUnitEnvironmentValueOf, @@ -207,7 +209,7 @@ export function renderBootServicePlist( /** * Task Scheduler can neither set variables nor redirect output, so the launcher takes them as * flags. A console program started by a task opens a window unless a headless console hosts it. - * No XML declaration: schtasks rejects `encoding="UTF-8"` but reads undeclared XML as UTF-8. + * No XML declaration: the file is written as UTF-16LE with a BOM (see `encodeServiceTask`). */ export function renderBootServiceTask( plan: BootServicePlan, @@ -926,6 +928,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { (release) => Effect.sync(release), ), ); + const readUnit = () => fs.readFile(unitPath).pipe(Effect.map(decodeServiceUnit)); /** * Task Scheduler runs its own copy of the task, so an install that starts nothing still * registers the new one. A task that was disabled or absent stays stopped. @@ -955,7 +958,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { directory: path.dirname(unitPath), prefix: ".service-task-", }); - yield* fs.writeFileString(disabledPath, disabledServiceTask(unit)); + yield* fs.writeFile(disabledPath, encodeServiceTask(disabledServiceTask(unit))); yield* register(disabledPath); }), ); @@ -963,7 +966,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { // Ending the task closes the launcher's console, which the launcher takes as its SIGTERM. // Task Scheduler then reports the task stopped at once, so the lock says when it really is. const stopWindowsLauncher = Effect.gen(function* () { - const unit = yield* fs.readFileString(unitPath).pipe(Effect.option); + const unit = yield* readUnit().pipe(Effect.option); yield* runner.run({ command: "schtasks", args: ["/End", ...windowsTask] }).pipe(Effect.ignore); yield* Effect.tryPromise({ try: (signal) => waitForServiceLauncherExit(launcherLockPath(unit), signal), @@ -1014,13 +1017,15 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { ? installedBaseDir : undefined; }; - const writeDurably = (filePath: string, contents: string) => + const writeDurably = (filePath: string, contents: string | Uint8Array) => Effect.scoped( Effect.gen(function* () { const directory = path.dirname(filePath); yield* fs.makeDirectory(directory, { recursive: true }); const tempPath = yield* fs.makeTempFileScoped({ directory, prefix: ".service-write-" }); - yield* fs.writeFileString(tempPath, contents, { mode: 0o600 }); + yield* typeof contents === "string" + ? fs.writeFileString(tempPath, contents, { mode: 0o600 }) + : fs.writeFile(tempPath, contents, { mode: 0o600 }); // Opened read-write: Windows refuses to flush a handle without write access. yield* (yield* fs.open(tempPath, { flag: "r+" })).sync; yield* fs.rename(tempPath, filePath); @@ -1217,7 +1222,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { // The unit is per user. Rewriting one that serves another home moves the // service onto this home's data, which looks like every thread vanished. const refuseOtherBaseDir = Effect.gen(function* () { - const existingUnit = yield* fs.readFileString(unitPath).pipe(Effect.option); + const existingUnit = yield* readUnit().pipe(Effect.option); const installedBaseDir = Option.isSome(existingUnit) ? otherBaseDirOf(existingUnit.value) : undefined; @@ -1322,9 +1327,9 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { input.baseDir.replaceAll("$", () => "$$"), ...(options?.allowDowngrade === true ? ["--allow-downgrade"] : []), ]); - const unit = yield* fs - .readFileString(unitPath) - .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause }))); + const unit = yield* readUnit().pipe( + Effect.mapError((cause) => new BootServiceInstallError({ cause })), + ); return { ...planForUnit(unit), handedOff: true }; } // Task Scheduler restarts the task itself, so the files are written as for a deferred @@ -1378,7 +1383,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause }))); // Files can match the new version even when activation fails; keep that install retryable. yield* fs.writeFileString(restartPendingPath, `${input.cliVersion}\n`, { mode: 0o600 }); - const plan = planForUnit(currentlyInstalled ? yield* fs.readFileString(unitPath) : ""); + const plan = planForUnit(currentlyInstalled ? yield* readUnit() : ""); yield* writeDurably( statePath, // @effect-diagnostics-next-line globalJsonInEffect:off - fixed launcher-owned document. @@ -1398,7 +1403,10 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { } } const unit = manager.render(plan); - yield* writeDurably(unitPath, unit); + yield* writeDurably( + unitPath, + manager.kind === "schtasks" ? encodeServiceTask(unit) : unit, + ); if (!start && manager.kind === "schtasks") yield* refreshWindowsTask(unit); return plan; }), @@ -1437,7 +1445,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { const restart: BootService["Service"]["restart"] = Effect.gen(function* () { const manager = yield* requireManager; - const unit = yield* fs.readFileString(unitPath).pipe(Effect.option); + const unit = yield* readUnit().pipe(Effect.option); if (Option.isNone(unit)) return "skipped" as const; const installedBaseDir = bootServiceBaseDirOf(unit.value); if ( @@ -1470,7 +1478,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { ): Effect.fn.Return { if (detectedManager === undefined) return yield* operation; const manager = detectedManager; - const unit = yield* fs.readFileString(unitPath).pipe(Effect.option); + const unit = yield* readUnit().pipe(Effect.option); if (Option.isNone(unit)) return yield* operation; const installedBaseDir = bootServiceBaseDirOf(unit.value); if ( @@ -1546,7 +1554,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { return { supported: true, installed: false, current: false, unitPath, logPath }; } const [unit, runtimeEntryExists, runtimeSentinel, stateText] = yield* Effect.all([ - fs.readFileString(unitPath), + readUnit(), fs.exists(runtimePaths.entryPath), fs.readFileString(runtimePaths.sentinelPath).pipe(Effect.option), fs.readFileString(statePath).pipe(Effect.option), diff --git a/apps/server/src/cloud/selfUpdate.ts b/apps/server/src/cloud/selfUpdate.ts index f4ea7a110a8a4..1d1263b2ebf78 100644 --- a/apps/server/src/cloud/selfUpdate.ts +++ b/apps/server/src/cloud/selfUpdate.ts @@ -43,7 +43,7 @@ import { import { bootServiceProgramOf, bootServiceUnitPath } from "./bootService.ts"; import { runStagedServicePreflight } from "./servicePreflight.ts"; import * as ServiceLauncherClient from "./serviceLauncherClient.ts"; -import { isExactServiceVersion } from "./serviceProtocol.ts"; +import { decodeServiceUnit, isExactServiceVersion } from "./serviceProtocol.ts"; export function resolveServerSelfUpdateCapability(input: { readonly desktopManaged: boolean; @@ -92,7 +92,7 @@ export const pruneRuntimesOnStart = Effect.fn("cloud.server_self_update.prune_on const unit = unitPath === undefined ? Option.none() - : yield* fs.readFileString(unitPath).pipe(Effect.option); + : yield* fs.readFile(unitPath).pipe(Effect.map(decodeServiceUnit), Effect.option); const program = Option.flatMapNullishOr(unit, bootServiceProgramOf); // The unit may name it through another spelling of a symlinked T3 home. const references = Option.isNone(program) diff --git a/apps/server/src/cloud/serviceProtocol.ts b/apps/server/src/cloud/serviceProtocol.ts index 3800d58bdb1a8..18dbb5199e54a 100644 --- a/apps/server/src/cloud/serviceProtocol.ts +++ b/apps/server/src/cloud/serviceProtocol.ts @@ -43,6 +43,16 @@ const unquoteWindowsArgument = (raw: string) => export const serviceTaskIsDisabled = (taskXml: string): boolean => /[\s\S]*?<\/Settings>/.exec(taskXml)?.[0].includes("false") === true; +/** schtasks reads undeclared XML in the ANSI code page, but UTF-16LE with a BOM as written. */ +export const encodeServiceTask = (taskXml: string): Uint8Array => + Buffer.from(`\uFEFF${taskXml}`, "utf16le"); + +/** A unit file's text: UTF-16LE task files have a BOM, other units (and older tasks) are UTF-8. */ +export const decodeServiceUnit = (bytes: Uint8Array): string => + bytes[0] === 0xff && bytes[1] === 0xfe + ? Buffer.from(bytes.buffer, bytes.byteOffset + 2, bytes.byteLength - 2).toString("utf16le") + : Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString("utf8"); + /** A task as Task Scheduler should hold it while its service must stay stopped. */ export const disabledServiceTask = (taskXml: string): string => serviceTaskIsDisabled(taskXml) diff --git a/apps/server/src/serviceLauncher.test.ts b/apps/server/src/serviceLauncher.test.ts index 4bfe776a3aba8..c7259b4bd84fb 100644 --- a/apps/server/src/serviceLauncher.test.ts +++ b/apps/server/src/serviceLauncher.test.ts @@ -38,6 +38,7 @@ import { compareExactServiceVersions, decodeServiceState, isExactServiceVersion, + decodeServiceUnit, disabledServiceTask, SERVICE_ENV_FILE, SERVICE_LAUNCHER_PROTOCOL, @@ -469,7 +470,7 @@ setInterval(() => {}, 1_000); // Task Scheduler's copy: `t3 doctor` disabled it to keep the service stopped. let task = disabledServiceTask(unit.replace("1.1.0", "1.0.0")); const schtasks = async (...args: ReadonlyArray) => { - if (args[0] === "/Create") task = await NodeFSP.readFile(args[2] ?? "", "utf8"); + if (args[0] === "/Create") task = decodeServiceUnit(await NodeFSP.readFile(args[2] ?? "")); return { stdout: task }; }; diff --git a/apps/server/src/serviceLauncher.ts b/apps/server/src/serviceLauncher.ts index fad391896d307..51662f7be3309 100644 --- a/apps/server/src/serviceLauncher.ts +++ b/apps/server/src/serviceLauncher.ts @@ -23,7 +23,9 @@ import { decodeServiceLauncherChildMessage, isExactServiceVersion, parseLegacyServiceState, + decodeServiceUnit, disabledServiceTask, + encodeServiceTask, parseServiceState, serviceTaskIsDisabled, serviceUnitBaseDirOf, @@ -121,8 +123,8 @@ export async function registerServiceTask( } const disabledPath = `${unitPath}.${process.pid}.disabled`; try { - const unit = await NodeFSP.readFile(unitPath, "utf8"); - await NodeFSP.writeFile(disabledPath, disabledServiceTask(unit)); + const unit = decodeServiceUnit(await NodeFSP.readFile(unitPath)); + await NodeFSP.writeFile(disabledPath, encodeServiceTask(disabledServiceTask(unit))); await register(disabledPath); } finally { await NodeFSP.rm(disabledPath, { force: true }); @@ -256,7 +258,9 @@ async function serviceLogPath( ): Promise { if (options.logFile !== undefined) return options.logFile; if (serviceUnit === undefined) return undefined; - const contents = await NodeFSP.readFile(serviceUnit.path, "utf8").catch(() => undefined); + const contents = await NodeFSP.readFile(serviceUnit.path) + .then(decodeServiceUnit) + .catch(() => undefined); return contents === undefined ? undefined : serviceUnitLogPathOf(contents); } @@ -665,7 +669,7 @@ export async function writeServiceState(filePath: string, state: ServiceState): await replaceFileDurably(filePath, `${JSON.stringify(state, null, 2)}\n`); } -async function replaceFileDurably(filePath: string, contents: string): Promise { +async function replaceFileDurably(filePath: string, contents: string | Uint8Array): Promise { const directory = NodePath.dirname(filePath); const tempPath = NodePath.join( directory, @@ -674,7 +678,7 @@ async function replaceFileDurably(filePath: string, contents: string): Promise Date: Wed, 18 Nov 2026 20:07:40 +1100 Subject: [PATCH 13/25] fix(muse): failed Muse text generation explains Muse's error category (#29861) Co-authored-by: Claude Opus 5.5 Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: Julius Marminge --- .../src/server/textGeneration.test.ts | 56 +++++++++++++++++++ .../src/server/textGeneration.ts | 41 ++++++++++++-- 2 files changed, 93 insertions(+), 4 deletions(-) diff --git a/packages/provider-muse/src/server/textGeneration.test.ts b/packages/provider-muse/src/server/textGeneration.test.ts index 7876cac59a506..f0b1f1a300adb 100644 --- a/packages/provider-muse/src/server/textGeneration.test.ts +++ b/packages/provider-muse/src/server/textGeneration.test.ts @@ -226,6 +226,62 @@ it.layer(NodeServices.layer)("Muse text generation", (it) => { }), ); + it.effect("explains a failed turn by Muse's error category", () => + Effect.gen(function* () { + const message = "API error 429: raw provider text"; + const cases = [ + { + error: { kind: "modelError", quota: { limitKind: "tierLimit", resetsAtMs: 1 } }, + detail: "Muse Code usage limit reached. Try again after it resets.", + }, + { + // Credential proxies can refuse with a 429 quota message and no quota object. + error: { kind: "modelError", message: "upstream 429: quota exceeded for this key" }, + detail: "Muse Code usage limit reached. Try again after it resets.", + }, + { + error: { kind: "authRequired" }, + detail: "Muse Code is not signed in. Run `muse login` on this T3 server host.", + }, + { + error: { kind: "modelError" }, + detail: "Muse Code's model request failed. Try again or choose another Muse model.", + }, + { + error: { kind: "stepLimit" }, + detail: + "Muse Code text generation failed. Check Muse login and availability on this T3 server host.", + }, + { + reason: "upstream 429: quota exceeded for this key", + detail: "Muse Code usage limit reached. Try again after it resets.", + }, + { + reason: "raw provider refusal", + detail: + "Muse Code text generation failed. Check Muse login and availability on this T3 server host.", + }, + ]; + for (const { error, reason, detail } of cases) { + const raw = error === undefined ? reason : "message" in error ? error.message : message; + const test = fixture((emit) => + emit("turn/completed", { + terminal: "failed", + ...(error === undefined + ? { reason } + : { error: { message, ...error, retryable: false } }), + }), + ); + const service = yield* test.make; + const failure = yield* service.generateThreadTitle(titleInput).pipe(Effect.flip); + expect(failure).toMatchObject({ _tag: "TextGenerationError", detail }); + expect(failure.detail).not.toContain(raw); + expect(failure.cause).toMatchObject({ cause: { message: raw } }); + expect(test.host.close).toHaveBeenCalledOnce(); + } + }), + ); + it.effect("settles a completed turn even when its start acknowledgement never arrives", () => Effect.gen(function* () { const test = fixture(finish('{"title":"Fix login form"}'), false); diff --git a/packages/provider-muse/src/server/textGeneration.ts b/packages/provider-muse/src/server/textGeneration.ts index e36f4de9fbd18..dacaeae8bd033 100644 --- a/packages/provider-muse/src/server/textGeneration.ts +++ b/packages/provider-muse/src/server/textGeneration.ts @@ -21,6 +21,7 @@ import { type MuseSdkHost, } from "./sdk.ts"; import { museModelCapabilities, resolveMuseReasoningEffort } from "./modelCatalog.ts"; +import { isMuseUsageLimitFailure } from "./usageLimits.ts"; import type { ProviderTextGeneration } from "@t3tools/provider-core/server/textGeneration"; import { generatedThreadTitle, @@ -52,11 +53,17 @@ const ItemNotification = Schema.Struct({ truncated: Schema.optionalKey(Schema.Boolean), }), }); +const TurnError = Schema.Struct({ + kind: Schema.optionalKey(Schema.String), + message: Schema.String, + quota: Schema.optionalKey(Schema.Unknown), +}); const TurnCompleted = Schema.Struct({ sessionId: Schema.String, turnId: Schema.String, terminal: Schema.String, - error: Schema.optionalKey(Schema.Struct({ message: Schema.String })), + reason: Schema.optionalKey(Schema.String), + error: Schema.optionalKey(TurnError), }); const ApprovalRequested = Schema.Struct({ sessionId: Schema.String, @@ -75,10 +82,32 @@ const decodeItem = Schema.decodeUnknownSync(ItemNotification); const decodeCompleted = Schema.decodeUnknownSync(TurnCompleted); const decodeApproval = Schema.decodeUnknownSync(ApprovalRequested); const decodeUserInput = Schema.decodeUnknownSync(UserInputRequested); +const isMuseSdkError = Schema.is(MuseSdkError); const encodeJson = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown)); const decodeJson = Schema.decodeEffect(Schema.fromJsonString(Schema.Unknown)); type Operation = keyof ProviderTextGeneration; +class MuseTurnFailure extends Schema.TaggedError()("MuseTurnFailure", { + turnError: TurnError, +}) { + override get message() { + return this.turnError.message; + } +} +const isMuseTurnFailure = Schema.is(MuseTurnFailure); + +function museFailureDetail(cause: unknown): string { + const error = + isMuseSdkError(cause) && isMuseTurnFailure(cause.cause) ? cause.cause.turnError : undefined; + // Muse sends `quota` only for quota exhaustion, which it still labels `modelError`. + if (error?.quota !== undefined || isMuseUsageLimitFailure(error?.message)) + return "Muse Code usage limit reached. Try again after it resets."; + if (error?.kind === "authRequired") + return "Muse Code is not signed in. Run `muse login` on this T3 server host."; + if (error?.kind === "modelError") + return "Muse Code's model request failed. Try again or choose another Muse model."; + return "Muse Code text generation failed. Check Muse login and availability on this T3 server host."; +} async function generateMuseText( host: MuseSdkHost, @@ -144,8 +173,13 @@ async function generateMuseText( resolveCompletion(answer?.text ?? ""); } } else { + const error = + completed.error ?? + (completed.reason !== undefined ? { message: completed.reason } : undefined); rejectCompletion( - new Error(completed.error?.message ?? `Muse turn ${completed.terminal}.`), + error + ? new MuseTurnFailure({ turnError: error }) + : new Error(`Muse turn ${completed.terminal}.`), ); } } else if ( @@ -276,8 +310,7 @@ export const makeMuseTextGeneration = Effect.fn("makeMuseTextGeneration")(functi (cause) => new TextGenerationError({ operation, - detail: - "Muse Code text generation failed. Check Muse login and availability on this T3 server host.", + detail: museFailureDetail(cause), cause, }), ), From 486ba483804aa967f9cb0089e8128afd519dfcdd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dominik=20=C5=BDab=C4=8D=C3=ADk?= <35886301+dominikzabcik@users.noreply.github.com> Date: Wed, 18 Nov 2026 10:07:58 +0100 Subject: [PATCH 14/25] fix(server): imported Claude threads show prompts, not Claude Code markup (#33403) Co-authored-by: Claude Opus 5.5 Co-authored-by: maria-rcks Co-authored-by: Julius Marminge --- .../src/project/AgentSessionScanner.test.ts | 97 +++++++++++++++++-- .../server/src/project/AgentSessionScanner.ts | 89 +++++++++++++---- docs/user/welcome-page.md | 7 +- 3 files changed, 166 insertions(+), 27 deletions(-) diff --git a/apps/server/src/project/AgentSessionScanner.test.ts b/apps/server/src/project/AgentSessionScanner.test.ts index 9c62ddb1a2b84..6d9d3438ef380 100644 --- a/apps/server/src/project/AgentSessionScanner.test.ts +++ b/apps/server/src/project/AgentSessionScanner.test.ts @@ -2676,15 +2676,25 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => { content: [{ type: "tool_result", tool_use_id: "toolu_1", content: "ok" }], }, }); + // Claude Code's own command output is not a message and must not take a history slot. + const commandOutput = record({ + type: "user", + message: { + role: "user", + content: "Compacted", + }, + }); yield* writeTranscript({ filePath: path.join(claudeHomePath, "projects", "-slug", "long-session.jsonl"), contents: [ record({ type: "attachment", cwd: workspace, aiTitle: "Old title" }), + commandOutput, record({ type: "user", message: { role: "user", content: "First prompt" } }), record({ type: "assistant", message: { role: "assistant", model: "claude-opus-5-5", content: "First reply" }, }), + ...Array.from({ length: 200 }, () => commandOutput), // Small tool records exceed the real 32 MiB selected-history budget in aggregate. ...Array.from({ length: 20_000 }, () => toolResult), record({ type: "user", message: { role: "user", content: "Latest prompt" } }), @@ -3284,6 +3294,20 @@ describe("parseAgentSessionTranscript", () => { sessionId: "claude-session", message: { role: "user", content: [{ type: "tool_result", text: "hidden" }] }, }), + ...[ + "/review\nreview\nthe login flow", + "Enabled plan mode", + "npm test", + "1 passed", + "\na1\ncompleted\n", + "[Request interrupted by user for tool use]", + ].map((content) => + JSON.stringify({ + type: "user", + sessionId: "claude-session", + message: { role: "user", content }, + }), + ), JSON.stringify({ type: "assistant", sessionId: "claude-session", @@ -3315,6 +3339,8 @@ describe("parseAgentSessionTranscript", () => { model: "claude-sonnet-5", messages: [ { role: "user", text: "Fix authentication" }, + { role: "user", text: "/review the login flow" }, + { role: "user", text: "!npm test" }, { role: "assistant", text: "Updated the login flow" }, { role: "assistant", text: "The provider request failed" }, ], @@ -3325,6 +3351,16 @@ describe("parseAgentSessionTranscript", () => { { customTitles: ["Refactor auth module"], expected: "Refactor auth module" }, // Claude writes an empty customTitle when the user clears a rename. { customTitles: ["Refactor auth module", ""], expected: "Generated title" }, + // Some launchers rename the session to the raw markup of its opening command. + { + customTitles: ["pstack:poteto-mode"], + expected: "Generated title", + }, + { + customTitles: ["Enabled plan mode"], + expected: "Generated title", + }, + { customTitles: ["npm test"], expected: "Generated title" }, ])("uses Claude custom titles $customTitles over the AI title", ({ customTitles, expected }) => { const aiTitle = JSON.stringify({ type: "ai-title", @@ -3337,7 +3373,7 @@ describe("parseAgentSessionTranscript", () => { type: "user", sessionId: "claude-session", timestamp: "2026-08-24T10:00:00.000Z", - message: { role: "user", content: "/effort" }, + message: { role: "user", content: "Tighten the session checks" }, }), // Claude rewrites both records on every metadata flush with ai-title // last, so a later ai-title must not override the user's rename. @@ -3355,6 +3391,33 @@ describe("parseAgentSessionTranscript", () => { expect(thread?.title).toBe(expected); }); + it.each([ + { + first: + "/pstack:arenaCompare designs", + title: "Compare designs", + }, + { + first: "/clearclear", + title: "Plan the release", + }, + { first: "/Users/me/app fails to build", title: "/Users/me/app fails to build" }, + ])("titles a Claude thread after its request, not command markup: $title", ({ first, title }) => { + const thread = AgentSessionScanner.parseAgentSessionTranscript({ + contents: [first, "Plan the release"] + .map((content) => + JSON.stringify({ type: "user", sessionId: "claude-session", message: { content } }), + ) + .join("\n"), + source: "claudeAgent", + providerInstanceId: ProviderInstanceId.make("claudeAgent"), + fallbackSessionId: "fallback", + lastActiveAtMs: Date.parse("2026-08-24T12:00:00.000Z"), + }); + + expect(thread?.title).toBe(title); + }); + it.each([199, 200])("keeps the canonical first prompt with %s later Codex messages", (count) => { const canonicalPrompt = "\n Keep the canonical prompt \n"; const canonicalTimestamp = "2026-08-24T10:01:00.000Z"; @@ -3789,18 +3852,38 @@ describe("parseAgentSessionTranscript", () => { expect(thread?.title).toBe(prompt); }); - it("skips sessions without a visible user message", () => { + it.each([ + { + name: "only an assistant reply", + records: [{ type: "assistant", message: { content: "Done" } }], + expected: null, + }, + { + name: "only a bare command", + records: [{ type: "user", message: { content: "/clear" } }], + expected: null, + }, + { + name: "a bare command the agent answered", + records: [ + { type: "user", message: { content: "/review" } }, + { type: "assistant", message: { content: "Found two issues" } }, + ], + expected: { title: "/review", texts: ["/review", "Found two issues"] }, + }, + ])("imports a Claude session only if it got a request: $name", ({ records, expected }) => { const thread = AgentSessionScanner.parseAgentSessionTranscript({ - contents: JSON.stringify({ - type: "assistant", - message: { role: "assistant", content: "Done" }, - }), + contents: records.map((record) => JSON.stringify(record)).join("\n"), source: "claudeAgent", providerInstanceId: ProviderInstanceId.make("claudeAgent"), fallbackSessionId: "claude-session", lastActiveAtMs: Date.parse("2026-08-24T12:00:00.000Z"), }); - expect(thread).toBeNull(); + expect( + thread === null + ? null + : { title: thread.title, texts: thread.messages.map((message) => message.text) }, + ).toEqual(expected); }); }); diff --git a/apps/server/src/project/AgentSessionScanner.ts b/apps/server/src/project/AgentSessionScanner.ts index 1e300d1fe0410..b6e1780bd039e 100644 --- a/apps/server/src/project/AgentSessionScanner.ts +++ b/apps/server/src/project/AgentSessionScanner.ts @@ -363,10 +363,12 @@ function foldClaudeFields(fields: ClaudeFields, record: DecodedTranscriptRecord) const model = record.message?.model?.trim(); return { sessionId: record.sessionId?.trim() || fields.sessionId, - title: record.aiTitle?.trim() || fields.title, + title: claudeTitle(record.aiTitle) ?? fields.title, // Claude flushes the AI title after the user's rename; an empty rename clears it. customTitle: - record.customTitle === undefined ? fields.customTitle : record.customTitle.trim() || null, + record.customTitle === undefined + ? fields.customTitle + : (claudeTitle(record.customTitle) ?? null), // Claude uses this sentinel for local error responses. It is not a // model ID that can be selected when the imported session resumes. model: model && model !== "" ? model : fields.model, @@ -404,6 +406,44 @@ function codexHistoryBase(records: ReadonlyArray) { : undefined; } +// Claude Code records its own UI as user turns: slash commands, `!` shell runs and +// their output, task notifications. Keep what the user typed, as they typed it. +const CLAUDE_UI_OUTPUT = + /^(?:<(?:task-notification|local-command-stdout|local-command-stderr|local-command-caveat|bash-stdout|bash-stderr)>|\[Request interrupted by user(?: for tool use)?\]$)/; + +/** + * A slash command as typed. Its arguments may name the thread; a bare command + * leaves that to a later prompt. Null for any other text. + */ +function claudeCommand(text: string): { readonly text: string; readonly titleText: string } | null { + if (!/^/.test(text)) return null; + const name = + /([^<]*)<\/command-name>/.exec(text)?.[1]?.trim() || + `/${/([^<]*)<\/command-message>/.exec(text)?.[1]?.trim() ?? ""}`; + const args = /([\s\S]*?)<\/command-args>/.exec(text)?.[1]?.trim() ?? ""; + return { text: args.length === 0 ? name : `${name} ${args}`, titleText: args }; +} + +/** What a Claude user turn shows the user typed, and the part of it that may name the thread. */ +function claudeUserText(text: string): { readonly text: string; readonly titleText: string } { + if (CLAUDE_UI_OUTPUT.test(text)) return { text: "", titleText: "" }; + const shellInput = /^([\s\S]*)<\/bash-input>$/.exec(text)?.[1]; + if (shellInput !== undefined) return { text: `!${shellInput}`, titleText: "" }; + return claudeCommand(text) ?? { text, titleText: text }; +} + +function claudeVisibleText(record: DecodedTranscriptRecord) { + const text = extractText(record.message?.content); + return record.type === "user" ? claudeUserText(text) : { text, titleText: text }; +} + +/** Saved titles can be the raw markup of a user turn, such as the command that opened the session. */ +function claudeTitle(title: string | undefined): string | undefined { + const trimmed = title?.trim(); + if (!trimmed) return undefined; + return claudeUserText(trimmed).text === trimmed ? trimmed : undefined; +} + // Agent-started sessions wrap the prompt in a `` // envelope; title them after the prompt inside it. const WAKE_ENVELOPE = /^\s*]*)?>([\s\S]*?)(?:<\/wake>|$)/; @@ -487,6 +527,9 @@ function parseAgentSessionRecords( : (claudeFields.title ?? null); let model = claudeFields.model ?? null; let derivedTitle: string | undefined; + // Names a session whose only request was a bare command, such as `/review`. + let bareCommandTitle: string | undefined; + let hasAssistantMessage = false; let hasCodexSessionId = false; const messages: Array = []; let firstUserMessage: @@ -548,13 +591,16 @@ function parseAgentSessionRecords( let conversationMessageCount = 0; const retainMessage = ( message: AgentSessionThreadMessage & { readonly codexResponseUser: boolean }, + titleText = message.text, ) => { if (firstUserMessage === undefined && message.role === "user") { firstUserMessage = message; } if (derivedTitle === undefined && message.role === "user") { - derivedTitle = deriveTitle(input.source, message.text); + derivedTitle = deriveTitle(input.source, titleText); + bareCommandTitle ??= deriveTitle(input.source, message.text); } + hasAssistantMessage ||= message.role === "assistant"; conversationMessageCount += 1; messages.push(message); if (messages.length > MAX_IMPORTED_MESSAGES) messages.shift(); @@ -594,14 +640,17 @@ function parseAgentSessionRecords( if (input.source === "claudeAgent") { if (isHiddenClaudeRecord(record)) continue; if (record.type !== "user" && record.type !== "assistant") continue; - const text = extractText(record.message?.content); + const { text, titleText } = claudeVisibleText(record); if (text.length === 0) continue; - retainMessage({ - role: record.type, - text, - createdAt: normalizeTimestamp(record.timestamp, fallbackTimestamp), - codexResponseUser: false, - }); + retainMessage( + { + role: record.type, + text, + createdAt: normalizeTimestamp(record.timestamp, fallbackTimestamp), + codexResponseUser: false, + }, + titleText, + ); continue; } @@ -667,7 +716,14 @@ function parseAgentSessionRecords( const visibleMessages = messages.map( ({ codexResponseUser: _codexResponseUser, ...message }) => message, ); - if (providerSessionId.trim().length === 0 || firstUserMessage === undefined) return null; + if ( + providerSessionId.trim().length === 0 || + firstUserMessage === undefined || + // A Claude session of bare commands such as `/clear` that no reply followed did nothing. + (input.source === "claudeAgent" && derivedTitle === undefined && !hasAssistantMessage) + ) { + return null; + } const firstUserMessageRetained = messages.includes(firstUserMessage); const { codexResponseUser: _codexResponseUser, ...visibleFirstUserMessage } = firstUserMessage; const retainedMessages = firstUserMessageRetained @@ -678,7 +734,8 @@ function parseAgentSessionRecords( source: input.source, providerInstanceId: input.providerInstanceId, providerSessionId, - title: claudeFields.customTitle ?? title ?? derivedTitle ?? "Imported thread", + title: + claudeFields.customTitle ?? title ?? derivedTitle ?? bareCommandTitle ?? "Imported thread", model, createdAt: retainedMessages[0]?.createdAt ?? fallbackTimestamp, updatedAt: fallbackTimestamp, @@ -702,12 +759,8 @@ function shouldRetainDecodedRecord( if (isHiddenClaudeRecord(record) || (record.type !== "user" && record.type !== "assistant")) { return false; } - const content = record.message?.content; - return typeof content === "string" - ? content.trim().length > 0 - : (content?.some( - (block) => isTextContentBlock(block) && (block.text?.trim().length ?? 0) > 0, - ) ?? false); + // Same rule as the parser, so Claude Code's own output never takes a history window slot. + return claudeVisibleText(record).text.length > 0; } if (extractDecodedCwd(record) !== null) return true; return ( diff --git a/docs/user/welcome-page.md b/docs/user/welcome-page.md index a914349694156..ed8e75c28c74c 100644 --- a/docs/user/welcome-page.md +++ b/docs/user/welcome-page.md @@ -95,8 +95,11 @@ newest remaining visible user and assistant messages, with 200 messages total. It omits tool activity and attachments. For Codex, it omits generated setup context only when a canonical user event and a valid shared turn ID identify the same user turn. Ambiguous legacy or response-only context stays in the imported -conversation so T3 Code does not remove user text. It reads one conversation at -a time and skips files larger than 4 GiB. It also skips a conversation when the +conversation so T3 Code does not remove user text. For Claude, slash commands +and `!` shell commands appear as you typed them; their output, background task +notifications and interruption markers are left out, and a conversation that +only ran commands such as `/clear`, with no reply, is skipped. It reads one +conversation at a time and skips files larger than 4 GiB. It also skips a conversation when the message text and metadata it keeps need more than 32 MiB of memory. Tool output does not count toward that limit. It skips a conversation with more than 100,000 records every time, so opening the page again does not import it. It ignores From 316c3256a3a09cef7ed68914ebe74c7183ac08e1 Mon Sep 17 00:00:00 2001 From: ahalekelly <7078138+ahalekelly@users.noreply.github.com> Date: Wed, 18 Nov 2026 01:08:16 -0800 Subject: [PATCH 15/25] fix(server): a resumed Claude subagent keeps its earlier result (#34663) Co-authored-by: Claude Opus 5.5 --- .../Adapters/ClaudeAdapterV2.test.ts | 41 ++++++++++++++----- .../Adapters/ClaudeAdapterV2.ts | 20 +++++++-- 2 files changed, 48 insertions(+), 13 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index ef09d0022ac82..5e855f3431203 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -18427,11 +18427,14 @@ describe("ClaudeAdapterV2 background wake turns", () => { yield* startTurn(1, false); for (const frame of [ roster([agentEntry("run-1")]), - makeSubagentTaskStartedFrame({ - taskId: TASK_ID, - toolUseId: LAUNCH, - uuid: "00000000-0000-4000-8000-000000016101", - }), + { + ...makeSubagentTaskStartedFrame({ + taskId: TASK_ID, + toolUseId: LAUNCH, + uuid: "00000000-0000-4000-8000-000000016101", + }), + run_id: "run-1", + }, makeResultFrame({ uuid: "00000000-0000-4000-8000-000000016102", result: "LAUNCHED" }), ]) { yield* harness.offerAndWait(frame); @@ -18483,11 +18486,14 @@ describe("ClaudeAdapterV2 background wake turns", () => { }), roster([]), roster([agentEntry("run-2")]), - makeSubagentTaskStartedFrame({ - taskId: TASK_ID, - toolUseId: LAUNCH, - uuid: "00000000-0000-4000-8000-000000016107", - }), + { + ...makeSubagentTaskStartedFrame({ + taskId: TASK_ID, + toolUseId: LAUNCH, + uuid: "00000000-0000-4000-8000-000000016107", + }), + run_id: "run-2", + }, ]) { yield* harness.offerAndWait(frame); } @@ -18545,6 +18551,21 @@ describe("ClaudeAdapterV2 background wake turns", () => { ); yield* harness.until(() => subagentUpdates().at(-1)?.result === "DONE"); assert.equal(subagentUpdates().at(-1)?.status, "completed"); + yield* harness.until(() => + harness.events.some( + (event) => event.type === "message.updated" && event.message.text === "DONE", + ), + ); + const childMessageTexts = new Map(); + for (const event of harness.events) { + if (event.type === "message.updated" && event.message.threadId === routing.childThreadId) { + childMessageTexts.set(event.message.id, event.message.text); + } + } + assert.deepEqual( + [...childMessageTexts.values()].filter((text) => text === "WAITING" || text === "DONE"), + ["WAITING", "DONE"], + ); }).pipe( Effect.provide( Layer.mergeAll( diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index abf31497a9ad1..6d6cc1fee8c95 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -5119,6 +5119,8 @@ interface ActiveClaudeSubagent { readonly runToolUseId: string | null; readonly effort: string | undefined; nextChildItemOrdinal: number; + // Keyed on Claude's per-run id so a resumed run's result never replaces an earlier one. + resultNativeItemId: string; resultItemOrdinal: number | null; lastAssistantText: string | null; lastAssistantMessageId: string | null; @@ -7374,6 +7376,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( runToolUseId: launchToolUseId, effort: undefined, nextChildItemOrdinal: 100, + resultNativeItemId: `task:${resume.taskId}:result`, resultItemOrdinal: null, lastAssistantText: null, lastAssistantMessageId: null, @@ -7919,6 +7922,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( "running" | "completed" | "failed" | "cancelled" >; readonly reopen?: boolean; + readonly nativeRunId?: string; readonly nativeOutcome?: Extract< SDKMessage, { readonly type: "system"; readonly subtype: "task_notification" } @@ -8090,7 +8094,13 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( childThread: existingSubagent?.childThread ?? null, effort, nextChildItemOrdinal: existingSubagent?.nextChildItemOrdinal ?? 100, - resultItemOrdinal: existingSubagent?.resultItemOrdinal ?? null, + resultNativeItemId: + existingSubagent === undefined + ? `${nativeItemId}:result` + : isReopen && input.nativeRunId !== undefined + ? `${nativeItemId}:result:${input.nativeRunId}` + : existingSubagent.resultNativeItemId, + resultItemOrdinal: isReopen ? null : (existingSubagent?.resultItemOrdinal ?? null), lastAssistantText: input.reopen === true ? null : (existingSubagent?.lastAssistantText ?? null), lastAssistantMessageId: @@ -8301,11 +8311,10 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( input.status !== "running" && !resultAlreadyShown ) { - const resultNativeItemId = `${nativeItemId}:result`; const resultItemOrdinal = subagent.resultItemOrdinal ?? ++subagent.nextChildItemOrdinal; subagent.resultItemOrdinal = resultItemOrdinal; yield* emitSubagentConversationMessage({ - nativeItemId: resultNativeItemId, + nativeItemId: subagent.resultNativeItemId, threadId: childThreadId, rootNodeId: childRootNodeId, role: "assistant", @@ -9873,6 +9882,10 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( new Map(current).set(message.task_id, { ...registered, confirmedOutcome: undefined, + ...(message.run_id === undefined + ? {} + : { resultNativeItemId: `task:${message.task_id}:result:${message.run_id}` }), + resultItemOrdinal: null, task: { ...priorTask, status: "running", @@ -11354,6 +11367,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( title: message.description, status: "running", reopen: true, + ...(message.run_id === undefined ? {} : { nativeRunId: message.run_id }), }); yield* Ref.update(wakeBuffers, (current) => { const entry = current.get(liveQuery.nativeThreadId); From ce884e3a9d11ec46a31aa6ee7c5838dac76f3d02 Mon Sep 17 00:00:00 2001 From: Isaac-b-ux Date: Wed, 18 Nov 2026 04:39:17 -0500 Subject: [PATCH 16/25] fix(server): a preview navigation request issued before its frame exists no longer crashes the server (#30946) Co-authored-by: Isaac-b-ux <264455269+Isaac-b-ux@users.noreply.github.com> Co-authored-by: Claude Sonnet 5.5 Co-authored-by: maria-rcks --- apps/server/src/preview/ServerBrowser.test.ts | 34 +++++++++++++++++++ apps/server/src/preview/ServerBrowser.ts | 11 ++++-- 2 files changed, 43 insertions(+), 2 deletions(-) diff --git a/apps/server/src/preview/ServerBrowser.test.ts b/apps/server/src/preview/ServerBrowser.test.ts index 46a28b26aa8b9..f345bf6f150e6 100644 --- a/apps/server/src/preview/ServerBrowser.test.ts +++ b/apps/server/src/preview/ServerBrowser.test.ts @@ -2111,6 +2111,40 @@ it.effect( ).pipe(Effect.provide(layer)), ); +it.effect("a request whose frame is not available yet is not a main navigation", () => + Effect.scoped( + Effect.gen(function* () { + const { broker, tabId } = yield* ready; + const page = contexts[0]!.page; + const frameless = { + url: () => "https://example.com/early", + method: () => "GET", + isNavigationRequest: () => true, + frame: () => { + throw new Error("Frame for this navigation request is not available"); + }, + failure: () => ({ errorText: "net::ERR_CONNECTION_REFUSED" }), + }; + expect(() => page.emit("request", frameless)).not.toThrow(); + const statusAfterRequest = yield* broker.invoke({ + scope, + tabId, + operation: "status", + input: {}, + }); + expect(statusAfterRequest.loading).toBe(false); + expect(() => page.emit("requestfailed", frameless)).not.toThrow(); + const status = yield* broker.invoke({ + scope, + tabId, + operation: "status", + input: {}, + }); + expect(status.loading).toBe(false); + }), + ).pipe(Effect.provide(layer)), +); + it.effect.each(["before", "during"] as const)( "a navigation that fails while a load reads its title keeps its failure (request %s read)", (requestTiming) => diff --git a/apps/server/src/preview/ServerBrowser.ts b/apps/server/src/preview/ServerBrowser.ts index 19381a3da74f0..8598b47e68dca 100644 --- a/apps/server/src/preview/ServerBrowser.ts +++ b/apps/server/src/preview/ServerBrowser.ts @@ -1234,8 +1234,15 @@ const make = Effect.gen(function* () { }); await cdp.send("Page.enable"); } - const isMainNavigation = (request: { isNavigationRequest(): boolean; frame(): unknown }) => - request.isNavigationRequest() && request.frame() === page.mainFrame(); + // Playwright's `request.frame()` throws for a request issued before its frame exists, and a + // throw from a page listener is uncaught, so such a request is not a main-frame navigation. + const isMainNavigation = (request: { isNavigationRequest(): boolean; frame(): unknown }) => { + try { + return request.isNavigationRequest() && request.frame() === page.mainFrame(); + } catch { + return false; + } + }; const navigationGenerations = new WeakMap(); page.on("request", (request) => { if (!isMainNavigation(request)) return; From d0a754daeaa972101881befe74a6f99e24e25da7 Mon Sep 17 00:00:00 2001 From: Alex Vallone <39172404+amv146@users.noreply.github.com> Date: Wed, 18 Nov 2026 01:45:01 -0800 Subject: [PATCH 17/25] fix(server): label Copilot rg calls as file searches (#38512) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Co-authored-by: Julius Marminge --- .../Adapters/AcpRegistryAdapterV2.test.ts | 10 +++++----- .../provider-acp-registry/src/server/copilotAcp.ts | 2 +- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts index 495f16646a61d..1931b1a87b0d2 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts @@ -1997,9 +1997,9 @@ describe("AcpRegistryAdapterV2", () => { }).pipe(Effect.provide(layerTest)), ); - // Copilot flattens MCP titles and reports kind "read" for MCP calls and glob; its native - // tool.execution_start event carries the real identity. - it.effect("keeps Copilot's MCP and search tool identity instead of calling them file reads", () => + // Copilot flattens MCP titles and reports kind "read" for MCP calls and glob ("other" for rg); + // its native tool.execution_start event carries the real identity. + it.effect.each(["glob", "rg"])("keeps Copilot's MCP and %s identity", (toolName) => Effect.gen(function* () { const sessionId = "copilot-session"; const executionStart = (data: Record) => ({ @@ -2058,7 +2058,7 @@ describe("AcpRegistryAdapterV2", () => { }), executionStart({ toolCallId: "native-search", - toolName: "glob", + toolName, toolTitle: "Finding files", arguments: { pattern: "*.ts", paths: ["/workspace"] }, }), @@ -2066,7 +2066,7 @@ describe("AcpRegistryAdapterV2", () => { sessionUpdate: "tool_call", toolCallId: "native-search", title: "Finding files matching *.ts", - kind: "read", + kind: toolName === "rg" ? "other" : "read", status: "completed", rawInput: { pattern: "*.ts", paths: ["/workspace"] }, locations: [{ path: "/workspace" }], diff --git a/packages/provider-acp-registry/src/server/copilotAcp.ts b/packages/provider-acp-registry/src/server/copilotAcp.ts index 7b5027147c073..44723c79dc1d5 100644 --- a/packages/provider-acp-registry/src/server/copilotAcp.ts +++ b/packages/provider-acp-registry/src/server/copilotAcp.ts @@ -69,7 +69,7 @@ type CopilotToolIdentity = | { readonly kind: "mcp"; readonly server: string; readonly tool: string } | { readonly kind: "search" }; -const COPILOT_SEARCH_TOOLS = new Set(["glob", "grep"]); +const COPILOT_SEARCH_TOOLS = new Set(["glob", "grep", "rg"]); interface CopilotSessionAttribution { delta: { readonly kind: string; readonly text: string; readonly task?: string } | undefined; From 75514dfa551f155532385cfed1d55408a9bfc5bc Mon Sep 17 00:00:00 2001 From: Yash Singh Date: Wed, 18 Nov 2026 03:51:22 -0600 Subject: [PATCH 18/25] fix(web): keep Ready pending label until its request finishes (#38517) Co-authored-by: Julius Marminge Co-authored-by: Claude Opus 5.5 --- .../chat/ThreadDetailsPrRow.browser.test.tsx | 76 ++++++++++++++++--- .../components/chat/ThreadDetailsPrRow.tsx | 7 +- .../usePullRequestActions.browser.test.tsx | 24 ++++-- .../pullRequest/usePullRequestActions.ts | 18 +++-- 4 files changed, 101 insertions(+), 24 deletions(-) diff --git a/apps/web/src/components/chat/ThreadDetailsPrRow.browser.test.tsx b/apps/web/src/components/chat/ThreadDetailsPrRow.browser.test.tsx index 0c33baf1a2e4c..3abae88a711b5 100644 --- a/apps/web/src/components/chat/ThreadDetailsPrRow.browser.test.tsx +++ b/apps/web/src/components/chat/ThreadDetailsPrRow.browser.test.tsx @@ -1,3 +1,4 @@ +import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell"; import { EnvironmentId, IssueTrackerKind, @@ -12,6 +13,7 @@ import { AsyncResult } from "effect/reactivity"; import { expect, it, vi } from "vite-plus/test"; const state = vi.hoisted(() => ({ + isDraft: false, status: "success" as PullRequestCheck["status"], extraStatus: null as PullRequestCheck["status"] | null, mergeMethods: ["merge"] as Array<"merge" | "squash" | "rebase">, @@ -26,6 +28,10 @@ const state = vi.hoisted(() => ({ projectMergeMethods: {} as Record, })); +vi.mock(import("~/state/use-atom-command"), () => ({ + useAtomCommand: (() => state.perform) as never, +})); + vi.mock(import("~/state/entities"), async (importOriginal) => ({ ...(await importOriginal()), // Rows render a pull request only with a project, so this does not reach tests that pass none. @@ -47,7 +53,7 @@ const queryData = () => ({ number: 1, title: "Test PR", state: "open", - isDraft: false, + isDraft: state.isDraft, mergeability: "mergeable", headBranch: "feature", baseBranch: "main", @@ -60,8 +66,8 @@ const queryData = () => ({ description: null, url: null, })), - capabilities: { actions: ["merge"], mergeMethods: state.mergeMethods }, - viewerPermissions: { actions: ["merge"] }, + capabilities: { actions: ["merge", "ready"], mergeMethods: state.mergeMethods }, + viewerPermissions: { actions: ["merge", "ready"] }, mergeCapabilities: { merge: state.mergeMethods.includes("merge"), squash: state.mergeMethods.includes("squash"), @@ -87,7 +93,6 @@ vi.mock(import("~/state/query"), async (importOriginal) => ({ })); vi.mock(import("../pullRequest/usePullRequestActions"), async (importOriginal) => ({ ...(await importOriginal()), - usePullRequestActionRunner: () => ({ actionPending: false, perform: state.perform }), usePullRequestDefaultMergeMethodResolver: ((_environmentId: unknown, projectId: unknown) => () => state.projectMergeMethods[String(projectId)]) as never, })); @@ -139,6 +144,9 @@ const repositoryProject = { environmentId: EnvironmentId.make("environment"), title: "repo", workspaceRoot: "/work/repo", + defaultModelSelection: null, + createdAt: "2026-11-18T00:00:00.000Z", + updatedAt: "2026-11-18T00:00:00.000Z", scripts: [], repositoryIdentity: { canonicalKey: "github.com/owner/repo", @@ -152,7 +160,7 @@ const repositoryProject = { name: "repo", displayName: "owner/repo", }, -}; +} satisfies EnvironmentProject; const clickButton = async (scope: ParentNode, label: string) => await act(async () => { @@ -173,7 +181,7 @@ it("merges with the last selected merge method", async () => { pr={null} number={1} status={null} - project={null} + project={repositoryProject} label="Test PR" onOpen={vi.fn()} />, @@ -189,7 +197,11 @@ it("merges with the last selected merge method", async () => { const dialog = document.querySelector('[role="alertdialog"]')!; expect(dialog.textContent).toContain("using squash"); await clickMerge(dialog); - expect(state.perform).toHaveBeenCalledWith("merge", "squash"); + expect(state.perform).toHaveBeenCalledWith( + expect.objectContaining({ + input: expect.objectContaining({ action: "merge", mergeMethod: "squash" }), + }), + ); }); it("requires a new merge click after passing checks become pending and pass again", async () => { @@ -201,7 +213,7 @@ it("requires a new merge click after passing checks become pending and pass agai pr={null} number={1} status={null} - project={null} + project={repositoryProject} label="Test PR" onOpen={vi.fn()} /> @@ -233,7 +245,7 @@ it("requires a new merge click after passing checks become pending and pass agai }); async function setup() { - state.perform.mockReset(); + state.perform.mockReset().mockResolvedValue({ _tag: "Success", value: undefined }); state.checkoutError = null; state.newThread.mockReset().mockResolvedValue({ draftId: DraftId.make("new-draft"), @@ -243,6 +255,7 @@ async function setup() { state.addToast.mockReset().mockReturnValue("checkout-toast"); state.updateToast.mockReset(); + state.isDraft = false; state.status = "success"; state.extraStatus = null; state.mergeMethods = ["merge"]; @@ -264,7 +277,7 @@ it("adds the failing checks to a given composer instead of opening a new thread" pr={null} number={1} status={null} - project={null} + project={repositoryProject} label="Test PR" onOpen={vi.fn()} composerTarget={threadRef} @@ -402,3 +415,46 @@ it("names a linked issue row by its kind, number and title, not its URL", async expect(name).toContain("#123"); expect(name).toContain("Sidebar flickers on resize"); }); + +it("keeps Ready pending when refreshed detail becomes mergeable before the action settles", async () => { + await using screen = await setup(); + const row = () => ( + + ); + let finish!: (result: { _tag: "Success"; value: undefined }) => void; + const result = new Promise<{ _tag: "Success"; value: undefined }>((resolve) => { + finish = resolve; + }); + state.perform.mockReturnValueOnce(result); + state.isDraft = true; + await screen.rerender(row()); + await clickButton(screen.container, "Ready"); + expect(state.perform).toHaveBeenCalledWith( + expect.objectContaining({ + input: expect.objectContaining({ + projectId: repositoryProject.id, + repository: "owner/repo", + number: 1, + action: "ready", + }), + }), + ); + await expect.element(screen.getByRole("button", { name: "Marking..." })).toBeDisabled(); + + state.isDraft = false; + await screen.rerender(row()); + await expect.element(screen.getByRole("button", { name: "Marking..." })).toBeDisabled(); + await act(async () => { + finish({ _tag: "Success", value: undefined }); + await result; + }); + await expect.element(screen.getByRole("button", { name: "Merge", exact: true })).toBeEnabled(); +}); diff --git a/apps/web/src/components/chat/ThreadDetailsPrRow.tsx b/apps/web/src/components/chat/ThreadDetailsPrRow.tsx index 843bb3b037ca4..3b7836b32293d 100644 --- a/apps/web/src/components/chat/ThreadDetailsPrRow.tsx +++ b/apps/web/src/components/chat/ThreadDetailsPrRow.tsx @@ -166,7 +166,7 @@ export function ThreadDetailsPrRow({ checks: detail?.checks ?? [], }); - const { actionPending, perform } = usePullRequestActionRunner({ + const { actionPending, pendingAction, perform } = usePullRequestActionRunner({ environmentId, reference, terminology, @@ -183,7 +183,10 @@ export function ThreadDetailsPrRow({ ); const [confirmingMerge, setConfirmingMerge] = useState(false); - const rowAction = resolveThreadPanelPullRequestAction(detail); + const rowAction = + pendingAction === "ready" || pendingAction === "merge" + ? pendingAction + : resolveThreadPanelPullRequestAction(detail); if (confirmingMerge && rowAction !== "merge") { setConfirmingMerge(false); } diff --git a/apps/web/src/components/pullRequest/usePullRequestActions.browser.test.tsx b/apps/web/src/components/pullRequest/usePullRequestActions.browser.test.tsx index 018a5012fbf30..79089c0a858c6 100644 --- a/apps/web/src/components/pullRequest/usePullRequestActions.browser.test.tsx +++ b/apps/web/src/components/pullRequest/usePullRequestActions.browser.test.tsx @@ -32,19 +32,26 @@ function deferred() { } function MergeButton({ reference }: { reference: PullRequestRef }) { - const { actionPending, perform } = usePullRequestActionRunner({ + const { actionPending, pendingAction, perform } = usePullRequestActionRunner({ environmentId: EnvironmentId.make("environment"), reference, terminology: sourceControlClients.get(undefined).changeRequest, }); return ( ); } +function setup() { + state.runAction.mockReset(); + state.newThread.mockReset(); + state.prepareThread.mockReset(); +} + it("keeps pending merges with their pull request when navigating between threads", async () => { + setup(); const first: PullRequestRef = { projectId: ProjectId.make("project"), repository: "owner/repo", @@ -54,7 +61,6 @@ it("keeps pending merges with their pull request when navigating between threads const firstResult = deferred<{ _tag: "Success"; value: void }>(); const secondResult = deferred<{ _tag: "Success"; value: void }>(); state.runAction - .mockReset() .mockReturnValueOnce(firstResult.promise) .mockReturnValueOnce(secondResult.promise); await using screen = await render(); @@ -62,6 +68,14 @@ it("keeps pending merges with their pull request when navigating between threads await userEvent.click(button); await expect.element(button).toHaveTextContent("Merging..."); + await screen.rerender( + , + ); + await expect.element(button).toHaveTextContent("Merge"); + await expect.element(button).toBeEnabled(); + await screen.rerender(); + await expect.element(button).toHaveTextContent("Merging..."); + await expect.element(button).toBeDisabled(); await screen.rerender(); await expect.element(button).toHaveTextContent("Merge"); await expect.element(button).toBeEnabled(); @@ -102,6 +116,7 @@ function FixChecksButton() { } it("stops a pull request handoff when its loading toast is dismissed", async () => { + setup(); const prepared = deferred<{ _tag: "Success"; value: { @@ -112,10 +127,9 @@ it("stops a pull request handoff when its loading toast is dismissed", async () }; }>(); state.newThread - .mockReset() .mockResolvedValueOnce({ draftId: "draft-1", threadId: ThreadId.make("thread-1") }) .mockResolvedValueOnce({ draftId: "draft-2", threadId: ThreadId.make("thread-1") }); - state.prepareThread.mockReset().mockReturnValueOnce(prepared.promise); + state.prepareThread.mockReturnValueOnce(prepared.promise); await using screen = await render( diff --git a/apps/web/src/components/pullRequest/usePullRequestActions.ts b/apps/web/src/components/pullRequest/usePullRequestActions.ts index 5b7210ae32b96..f7885e098d3c3 100644 --- a/apps/web/src/components/pullRequest/usePullRequestActions.ts +++ b/apps/web/src/components/pullRequest/usePullRequestActions.ts @@ -201,23 +201,27 @@ export function usePullRequestActionRunner({ const runAction = useAtomCommand(pullRequestEnvironment.runAction, { reportFailure: false, }); - const pendingRef = useRef(new Set()); - const [pendingKeys, setPendingKeys] = useState>(() => new Set()); + const pendingRef = useRef(new Map()); + const [pendingActions, setPendingActions] = useState>( + () => new Map(), + ); const actionKey = reference === null ? null : JSON.stringify([ environmentId, + reference.projectId, reference.host ?? null, reference.repository, reference.number, ]); - const actionPending = actionKey !== null && pendingKeys.has(actionKey); + const pendingAction = actionKey === null ? null : (pendingActions.get(actionKey) ?? null); + const actionPending = pendingAction !== null; const perform = async (action: PullRequestAction, method?: PullRequestMergeMethod) => { if (actionKey === null || reference === null || pendingRef.current.has(actionKey)) return; - pendingRef.current.add(actionKey); - setPendingKeys(new Set(pendingRef.current)); + pendingRef.current.set(actionKey, action); + setPendingActions(new Map(pendingRef.current)); const result = await runAction({ environmentId, input: { @@ -227,7 +231,7 @@ export function usePullRequestActionRunner({ }, }); pendingRef.current.delete(actionKey); - setPendingKeys(new Set(pendingRef.current)); + setPendingActions(new Map(pendingRef.current)); if (result._tag === "Failure") { toastManager.add({ type: "error", @@ -246,7 +250,7 @@ export function usePullRequestActionRunner({ onSuccess?.(action, result.value); }; - return { actionPending, perform }; + return { actionPending, pendingAction, perform }; } export function usePullRequestCloseBatch( From 1c41c5ed898434f97dae7815f57b0914c9aeb0b5 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 18 Nov 2026 01:53:22 -0800 Subject: [PATCH 19/25] fix(azure-devops): issue lists reuse each project's states and survive a refresh while loading (#38508) --- apps/web/src/components/issue/IssuesPage.tsx | 8 +++++- .../server/AzureDevOpsIssueTracker.test.ts | 13 +++++++--- .../src/server/AzureDevOpsIssueTracker.ts | 26 +++++++++++++++---- 3 files changed, 38 insertions(+), 9 deletions(-) diff --git a/apps/web/src/components/issue/IssuesPage.tsx b/apps/web/src/components/issue/IssuesPage.tsx index 307aca3741398..bd8627a2e6689 100644 --- a/apps/web/src/components/issue/IssuesPage.tsx +++ b/apps/web/src/components/issue/IssuesPage.tsx @@ -216,7 +216,13 @@ export function IssuesPage() { input: listInput, })); const list = useIssueList(targets); - useLiveRefresh(list.refresh, { key: JSON.stringify(targets) }); + // Refreshing a list still loading would cancel it and start over, losing the scopes already read. + useLiveRefresh( + () => { + if (!list.isPending) list.refresh(); + }, + { key: JSON.stringify(targets) }, + ); const [pages, setPages] = useState>(new Map()); const held = holdIssuePages(list.answers, pages); diff --git a/packages/source-control-azure-devops/src/server/AzureDevOpsIssueTracker.test.ts b/packages/source-control-azure-devops/src/server/AzureDevOpsIssueTracker.test.ts index 5bd495bca73ee..cc6a1d18cd28f 100644 --- a/packages/source-control-azure-devops/src/server/AzureDevOpsIssueTracker.test.ts +++ b/packages/source-control-azure-devops/src/server/AzureDevOpsIssueTracker.test.ts @@ -219,6 +219,7 @@ describe("AzureDevOpsIssueTracker", () => { const fs = yield* FileSystem.FileSystem; const bodies: string[] = []; const hydrated: string[] = []; + let typeReads = 0; const api = yield* AzureDevOpsIssueTracker.make.pipe( Effect.provide( Layer.mock(AzureDevOpsCli.AzureDevOpsCli)({ @@ -238,6 +239,7 @@ describe("AzureDevOpsIssueTracker", () => { ); } if (resource !== "wiql" && resource !== "workitemsbatch") { + if (resource === "workitemtypes") typeReads += 1; return Effect.succeed(TestSourceControlHost.processOutput(answer(args))); } return fs.readFileString(args[args.indexOf("--in-file") + 1]!).pipe( @@ -260,7 +262,7 @@ describe("AzureDevOpsIssueTracker", () => { }), ), ); - const page = yield* api.listIssues({ + const list = api.listIssues({ cwd: "/w", host: "dev.azure.com", scope: "acme/Web App", @@ -273,11 +275,16 @@ describe("AzureDevOpsIssueTracker", () => { limit: 2, cursor: "2026-07-01T00:00:00Z|7", }); + const page = yield* list; + yield* list; // The rows come back in WIQL's order, and the cursor is the last one of the page. - expect(hydrated).toEqual(["9,7"]); + expect(hydrated).toEqual(["9,7", "9,7"]); expect(page.items.map((item) => item.key)).toEqual(["9", "7"]); expect(page.nextCursor).toBe("2026-07-01T00:00:00Z|7"); - expect(bodies).toHaveLength(1); + // Each `az` call costs seconds, so a second list reuses the project's states. + expect(typeReads).toBe(1); + expect(bodies).toHaveLength(2); + expect(bodies[1]).toBe(bodies[0]); expect(bodies[0]).toContain("AND [System.State] NOT IN ('shipped')"); const { query } = JSON.parse(bodies[0]!) as { query: string }; // Mentions cannot be asked for over REST, so the filter sends no clause for them. diff --git a/packages/source-control-azure-devops/src/server/AzureDevOpsIssueTracker.ts b/packages/source-control-azure-devops/src/server/AzureDevOpsIssueTracker.ts index 5a6f4c7c38ef9..84212c9ff0ecd 100644 --- a/packages/source-control-azure-devops/src/server/AzureDevOpsIssueTracker.ts +++ b/packages/source-control-azure-devops/src/server/AzureDevOpsIssueTracker.ts @@ -3,7 +3,10 @@ * scope is `organization/project` and every call names the organization. Listing is a WIQL * query paged by a `(changedDate, id)` keyset cursor, because WIQL has no offset. */ +import * as Cache from "effect/Cache"; +import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; import * as FileSystem from "effect/FileSystem"; import * as Result from "effect/Result"; import * as Schema from "effect/Schema"; @@ -67,6 +70,7 @@ const VIEWER_PERMISSIONS: IssueViewerPermissions = { const REST_API_VERSION = "7.1"; const PAGE_SIZE = 100; +const CLOSED_STATES_TTL = Duration.minutes(10); /** Updates are read a page per `az` process, oldest first, so a long history is bounded. */ const UPDATE_PAGE_LIMIT = 5; /** Linked pull requests are read one `az` process each, so a work item's links are bounded. */ @@ -356,8 +360,19 @@ export const make: Effect.Effect< decode: decodeAs(decodeTypes), }).pipe(Effect.map((types) => types.value)); - const closedStates = (input: Parameters[0]) => - workItemTypes(input).pipe(Effect.map(closedStateNames)); + // Each `az` call costs seconds of startup, and a project's states rarely change. + const listClosedStates = yield* Cache.makeWith( + (key: string) => { + const [cwd, organization, project] = JSON.parse(key) as [string, string, string]; + return workItemTypes({ cwd, organization, project, operation: "listIssues" }).pipe( + Effect.map(closedStateNames), + ); + }, + { + capacity: 256, + timeToLive: (exit) => (Exit.isSuccess(exit) ? CLOSED_STATES_TTL : Duration.zero), + }, + ); const workItem = (input: { readonly cwd: string; @@ -599,9 +614,10 @@ export const make: Effect.Effect< const dateField = created ? "[System.CreatedDate]" : "[System.ChangedDate]"; return yield* scoped("listIssues", input).pipe( Effect.flatMap((scope) => - closedStates({ ...scope, cwd: input.cwd, operation: "listIssues" }).pipe( - Effect.map((closed) => ({ scope, closed })), - ), + Cache.get( + listClosedStates, + JSON.stringify([input.cwd, scope.organization, scope.project]), + ).pipe(Effect.map((closed) => ({ scope, closed }))), ), Effect.flatMap(({ scope, closed }) => invokeWithBody({ From fe1f1a5732d8a72f435ee4981bef303d88d7dc7f Mon Sep 17 00:00:00 2001 From: Ian Rowe <87292868+ianrowe12@users.noreply.github.com> Date: Wed, 18 Nov 2026 05:08:25 -0500 Subject: [PATCH 20/25] fix(acp): Devin terminals no longer inherit the launching thread's T3 MCP credentials (#26652) Co-authored-by: Claude Opus 5.5 Co-authored-by: maria-rcks --- .../src/server/clientTerminals.test.ts | 45 ++++++++++++++++--- .../src/server/clientTerminals.ts | 41 ++++++++++++----- 2 files changed, 69 insertions(+), 17 deletions(-) diff --git a/packages/provider-acp/src/server/clientTerminals.test.ts b/packages/provider-acp/src/server/clientTerminals.test.ts index 22f8bb9ce3dde..87a96999cd1bf 100644 --- a/packages/provider-acp/src/server/clientTerminals.test.ts +++ b/packages/provider-acp/src/server/clientTerminals.test.ts @@ -99,28 +99,59 @@ describe("AcpClientTerminals", () => { it.live("resolves terminal environment from the requesting ACP session", () => Effect.gen(function* () { + const inheritedEnvironment = yield* HostProcess.Environment; const terminals = yield* makeAcpClientTerminals({ defaultCwd: process.cwd(), - environmentForSession: (sessionId) => ({ - T3_TEST_ACP_SESSION_TOKEN: sessionId === "session-a" ? "token-a" : "token-b", - }), + environmentForSession: (sessionId) => + sessionId === "unknown" + ? undefined + : { + T3_ACP_MCP_AUTHORIZATION: sessionId === "session-a" ? "token-a" : "token-b", + T3CODE_THREAD_ID: sessionId, + }, }); yield* Effect.addFinalizer(() => terminals.disposeAll); + inheritedEnvironment.T3_TEST_INHERITED = "refreshed"; for (const [sessionId, expected] of [ - ["session-a", "token-a"], - ["session-b", "token-b"], + ["session-a", "token-a||session-a|refreshed|T3_TEST_OVERRIDE=request"], + ["session-b", "token-b||session-b|refreshed|T3_TEST_OVERRIDE=request"], + ["unknown", "|||refreshed|T3_TEST_OVERRIDE=inherited"], ] as const) { const created = yield* terminals.create({ sessionId, command: process.execPath, - args: ["-e", "process.stdout.write(process.env.T3_TEST_ACP_SESSION_TOKEN ?? '')"], + args: [ + "-e", + "const env = process.env; process.stdout.write([env.T3_ACP_MCP_AUTHORIZATION ?? '', env.t3_Acp_Mcp_Endpoint ?? '', env.T3CODE_THREAD_ID ?? '', env.T3_TEST_INHERITED, ...Object.keys(env).filter((name) => name.toUpperCase() === 'T3_TEST_OVERRIDE').map((name) => name + '=' + env[name])].join('|'))", + ], + ...(sessionId === "unknown" + ? {} + : { + env: [ + { name: "T3_TEST_OVERRIDE", value: "first" }, + { name: "t3_Test_Override", value: "second" }, + { name: "T3_TEST_OVERRIDE", value: "request" }, + ], + }), }); yield* terminals.waitForExit({ sessionId, terminalId: created.terminalId }); const output = yield* terminals.output({ sessionId, terminalId: created.terminalId }); expect(output.output).toBe(expected); } - }).pipe(Effect.provide(NodeServices.layer)), + }).pipe( + Effect.provideService(HostProcess.Environment, { + ...process.env, + T3_ACP_MCP_AUTHORIZATION: "launching-thread-token", + t3_Acp_Mcp_Endpoint: "launching-thread-endpoint", + T3CODE_THREAD_ID: "launching-thread", + T3_TEST_INHERITED: "kept", + T3_TEST_OVERRIDE: "inherited", + }), + // Exercise Windows' case-insensitive variable names on every OS. + Effect.provideService(HostProcess.Platform, "win32"), + Effect.provide(NodeServices.layer), + ), ); it.live("runs Devin shell source with arguments, pipes, and session fallback variables", () => diff --git a/packages/provider-acp/src/server/clientTerminals.ts b/packages/provider-acp/src/server/clientTerminals.ts index 77d8767904bb5..2fda24d4e4fa5 100644 --- a/packages/provider-acp/src/server/clientTerminals.ts +++ b/packages/provider-acp/src/server/clientTerminals.ts @@ -12,6 +12,7 @@ import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; import * as EffectAcpErrors from "effect-acp/errors"; import type * as EffectAcpSchema from "effect-acp/compat"; import * as NodeBuffer from "node:buffer"; +import * as HostProcess from "@t3tools/shared/HostProcess"; const MAX_LIVE_TERMINALS = 16; const MAX_UNRELEASED_TERMINALS = 64; @@ -137,22 +138,38 @@ function acpTerminalCommand(input: { readonly request: EffectAcpSchema.CreateTerminalRequest; readonly shellCommands?: boolean | undefined; readonly defaultCwd: string; - readonly environment?: NodeJS.ProcessEnv | undefined; + readonly environment: NodeJS.ProcessEnv; readonly forceKillAfter: Duration.Input; }) { return ChildProcess.make(input.request.command, input.request.args ?? [], { cwd: input.request.cwd ?? input.defaultCwd, - ...(input.environment === undefined ? {} : { env: input.environment }), + env: input.environment, shell: input.shellCommands === true && (input.request.args?.length ?? 0) === 0, forceKillAfter: input.forceKillAfter, }); } +// Windows variable names are case-insensitive and Node passes only one spelling to the child, +// so a later layer's `Path` must replace an earlier `PATH` rather than sit beside it. +function mergeEnvironments( + isWindows: boolean, + layers: ReadonlyArray>, +) { + const variables = new Map(); + for (const layer of layers) { + for (const [name, value] of layer) { + variables.set(isWindows ? name.toUpperCase() : name, [name, value]); + } + } + return Object.fromEntries(variables.values()); +} + export const makeAcpClientTerminals = Effect.fn("makeAcpClientTerminals")(function* ( options: AcpClientTerminalsOptions, ): Effect.fn.Return { const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; const forceKillAfter = options.forceKillAfter ?? "5 seconds"; + const isWindows = yield* HostProcess.isWindows; const creationPermit = yield* Semaphore.make(1); const terminals = new Map(); let nextTerminalNumber = 1; @@ -215,16 +232,20 @@ export const makeAcpClientTerminals = Effect.fn("makeAcpClientTerminals")(functi `ACP terminal/create exceeded the limit of ${MAX_LIVE_TERMINALS} concurrent terminals.`, ); } - const requestEnvironment = Object.fromEntries( - (request.env ?? []).map((variable) => [variable.name, variable.value] as const), + // Thread credentials and identity must come from the requesting session. + const inheritedEnvironment = Object.fromEntries( + Object.entries(options.environment ?? (yield* HostProcess.Environment)).filter( + ([name]) => + !name.toUpperCase().startsWith("T3_ACP_MCP_") && + name.toUpperCase() !== "T3CODE_THREAD_ID", + ), ); const sessionEnvironment = options.environmentForSession?.(request.sessionId); - const environment = - options.environment === undefined && - sessionEnvironment === undefined && - (request.env?.length ?? 0) === 0 - ? undefined - : { ...options.environment, ...sessionEnvironment, ...requestEnvironment }; + const environment = mergeEnvironments(isWindows, [ + Object.entries(inheritedEnvironment), + Object.entries(sessionEnvironment ?? {}), + (request.env ?? []).map((variable) => [variable.name, variable.value] as const), + ]); const terminalScope = yield* Scope.make(); const child = yield* restore( spawner From 0d405f664a2720a73ad2491529597317c6bd5945 Mon Sep 17 00:00:00 2001 From: Fuksss Date: Wed, 18 Nov 2026 11:13:28 +0100 Subject: [PATCH 21/25] fix(web): a ~\ home path opens as a read-only home file, not as a project file (#38510) Co-authored-by: Julius Marminge --- apps/web/src/components/files/filePath.test.ts | 5 +++++ apps/web/src/components/files/filePath.ts | 4 +++- packages/client-runtime/src/operations/projects.ts | 11 ++++++++--- packages/shared/src/path.test.ts | 1 + packages/shared/src/path.ts | 13 +++++++++---- 5 files changed, 26 insertions(+), 8 deletions(-) diff --git a/apps/web/src/components/files/filePath.test.ts b/apps/web/src/components/files/filePath.test.ts index fbe6a67ece922..00a3247dc6508 100644 --- a/apps/web/src/components/files/filePath.test.ts +++ b/apps/web/src/components/files/filePath.test.ts @@ -33,6 +33,11 @@ describe("fileBreadcrumbs", () => { { label: ".claude", path: "~/.claude", kind: "directory" }, { label: "CLAUDE.md", path: "~/.claude/CLAUDE.md", kind: "file" }, ]); + expect(fileBreadcrumbs("t3code", "~\\.claude/CLAUDE.md")).toEqual([ + { label: "~", path: "~/", kind: "directory" }, + { label: ".claude", path: "~/.claude", kind: "directory" }, + { label: "CLAUDE.md", path: "~/.claude/CLAUDE.md", kind: "file" }, + ]); expect(isListableHostFolder("~/")).toBe(true); expect(isListableHostFolder("~/.claude")).toBe(true); }); diff --git a/apps/web/src/components/files/filePath.ts b/apps/web/src/components/files/filePath.ts index facefbb173016..b7a9d2784d973 100644 --- a/apps/web/src/components/files/filePath.ts +++ b/apps/web/src/components/files/filePath.ts @@ -16,7 +16,9 @@ export function fileBreadcrumbs(projectName: string, relativePath: string): File const windowsPath = isWindowsAbsolutePath(relativePath); const separator = windowsPath ? "\\" : "/"; // `\` is a legal filename character outside Windows paths. - const parts = relativePath.split(windowsPath ? /[\\/]/ : "/").filter(Boolean); + // The server reads `~\` as home; the rest keeps the usual relative-path spelling. + const homePath = relativePath.startsWith("~\\") ? `~/${relativePath.slice(2)}` : relativePath; + const parts = homePath.split(windowsPath ? /[\\/]/ : "/").filter(Boolean); const root = relativePath.startsWith("\\\\") ? "\\\\" : relativePath.startsWith("/") ? "/" : ""; return [ ...(hostPath ? [] : [{ label: projectName, path: "", kind: "project" as const }]), diff --git a/packages/client-runtime/src/operations/projects.ts b/packages/client-runtime/src/operations/projects.ts index 92532a6a90579..c56fa973c4501 100644 --- a/packages/client-runtime/src/operations/projects.ts +++ b/packages/client-runtime/src/operations/projects.ts @@ -11,7 +11,7 @@ import type { } from "@t3tools/contracts"; import { SourceControlProviderKind } from "@t3tools/contracts"; import { cloneUrlRepositoryPath } from "@t3tools/shared/cloneUrl"; -import { isExplicitRelativePath, isHostPath, newProjectFolderName } from "@t3tools/shared/path"; +import { isAbsolutePath, isExplicitRelativePath, newProjectFolderName } from "@t3tools/shared/path"; import * as Arr from "effect/Array"; import * as Option from "effect/Option"; import * as Order from "effect/Order"; @@ -222,8 +222,13 @@ export function buildAddProjectRemoteSourceReadiness( export function getAddProjectInitialQuery(baseDirectory: string | null | undefined): string { const trimmed = baseDirectory?.trim() ?? ""; if (trimmed.length === 0) return "~/"; - // A bare relative setting such as `Desktop/dev` means a folder under home. - const isAnchored = trimmed === "~" || isHostPath(trimmed) || isExplicitRelativePath(trimmed); + // A bare relative setting such as `Desktop/dev` means a folder under home. The browser + // navigates `~/` but not `~\` home paths. + const isAnchored = + trimmed === "~" || + isAbsolutePath(trimmed) || + trimmed.startsWith("~/") || + isExplicitRelativePath(trimmed); return ensureBrowseDirectoryPath(isAnchored ? trimmed : `~/${trimmed}`); } diff --git a/packages/shared/src/path.test.ts b/packages/shared/src/path.test.ts index 514f92b8f54e0..9a9647c1bcd4b 100644 --- a/packages/shared/src/path.test.ts +++ b/packages/shared/src/path.test.ts @@ -59,6 +59,7 @@ describe("resolvePastedPath", () => { ["over a selection", "/Users/me/old", "'/Users/me/My Code'", "/Users/me/My Code"], ["after a prefilled folder", "~/", "~/'/Users/me/My Code'", "/Users/me/My Code"], ["plain, after a prefilled folder", "~/", "~//Users/me/code", "/Users/me/code"], + ["backslash home, after a folder", "~/", "~/~\\folder\\ child", "~/~\\folder\\ child"], ["after a Windows folder", "C:\\Users\\", 'C:\\Users\\"D:\\My Code"', "D:\\My Code"], ["a shell's quoted apostrophe", "", "'/Users/me/Bob'\\''s Work'", "/Users/me/Bob's Work"], ["after a clone destination", "~/code/repo", "~/code/repo'/a b'", "/a b"], diff --git a/packages/shared/src/path.ts b/packages/shared/src/path.ts index 45b49b200091c..e4351b97b2626 100644 --- a/packages/shared/src/path.ts +++ b/packages/shared/src/path.ts @@ -134,15 +134,20 @@ export function isAbsolutePath(value: string): boolean { return value.startsWith("/") || isWindowsAbsolutePath(value); } -/** Home-relative host paths are expanded by the destination server. */ +/** Both ~/ and ~\ home prefixes are expanded by the destination server. */ export function isHostPath(value: string): boolean { - return isAbsolutePath(value) || value.startsWith("~/"); + return isAbsolutePath(value) || value.startsWith("~/") || value.startsWith("~\\"); } // Finder and Explorer copy a path ready for a shell: `'/a b'`, `/a\'s\ b`, or `"C:\a b"`. const QUOTED_PATH_AT_END = /(?:'((?:[^']|'\\'')+)'|"([^"]+)")\s*$/; const SHELL_ESCAPE = /\\([\s'"\\()[\]{}<>|&;$`!*?#~^=])/g; +// Folder browsers only navigate `~/` home paths, so a pasted `~\` path is not a replacement. +function isPastedFolderPath(value: string): boolean { + return isAbsolutePath(value) || value.startsWith("~/"); +} + /** * What a folder box holds after a change. A full path pasted into it replaces the box, even after * the text already there, because `~/'/a b'` would create that nested folder. @@ -157,13 +162,13 @@ export function resolvePastedPath(previous: string, next: string): string { // Text before the quote that wasn't in the box is a search, not a folder to paste after. if (match && previous.startsWith(next.slice(0, match.index).trimEnd())) { const quoted = match[1]?.replaceAll("'\\''", "'") ?? match[2] ?? ""; - if (isHostPath(quoted)) return quoted; + if (isPastedFolderPath(quoted)) return quoted; } // Without a trailing separator, `/a` then `/a/b` is a longer path, not one pasted after a folder. const afterFolder = /[/\\]$/.test(previous) && next.startsWith(previous); const path = afterFolder ? next.slice(previous.length) : next; - if (!isHostPath(path)) return next; + if (!isPastedFolderPath(path)) return next; // `\` separates folders in Windows paths, so it only escapes in `/` and `~/` paths. return isWindowsAbsolutePath(path) ? path : path.replace(SHELL_ESCAPE, "$1"); } From e6265a926e0e61109611201605bf68d9f0a9d6fa Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 18 Nov 2026 02:22:46 -0800 Subject: [PATCH 22/25] fix(web): thread jump hints re-check when a modifier changes while the hold is already met (#38545) --- apps/web/src/components/Sidebar.logic.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/apps/web/src/components/Sidebar.logic.ts b/apps/web/src/components/Sidebar.logic.ts index 8c9af1ed0508b..5cb2a044093a0 100644 --- a/apps/web/src/components/Sidebar.logic.ts +++ b/apps/web/src/components/Sidebar.logic.ts @@ -723,12 +723,15 @@ const threadJumpModifierHold = createModifierHoldStore(THREAD_JUMP_HINT_SHOW_DEL function subscribeToThreadJumpHintInputs(listener: () => void): () => void { const unsubscribeHold = threadJumpModifierHold.subscribe(listener); + // The snapshot reads the modifiers; the hold stays silent when it is true across a change. + const unsubscribeModifiers = shortcutModifierStore.subscribe(listener); const unsubscribeFocus = subscribeToTerminalFocusChanges(listener); const unsubscribeTerminals = useTerminalUiStateStore.subscribe(listener); const unsubscribeRightPanels = useRightPanelStore.subscribe(listener); const unsubscribeModelPicker = subscribeToModelPickerVisibility(listener); return () => { unsubscribeHold(); + unsubscribeModifiers(); unsubscribeFocus(); unsubscribeTerminals(); unsubscribeRightPanels(); From 3babab1497ddd82dfd90a0d53ad4d16ebae41063 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 18 Nov 2026 02:31:50 -0800 Subject: [PATCH 23/25] fix(server): Changes base follows the remote a plain recorded base branch tracks (#38543) --- apps/server/src/vcs/GitVcsDriverCore.test.ts | 40 ++++++++++++++++++++ apps/server/src/vcs/GitVcsDriverCore.ts | 4 ++ 2 files changed, 44 insertions(+) diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.ts index f4eb10810503e..bbd61b5010fde 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.test.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts @@ -4420,6 +4420,46 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); + it.effect("compares a plain recorded base with the remote that base branch tracks", () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + const fork = yield* makeTmpDir(); + const upstream = yield* makeTmpDir(); + yield* initRepoWithCommit(cwd); + const driver = yield* GitVcsDriver.GitVcsDriver; + yield* git(cwd, ["branch", "-M", "main"]); + yield* git(fork, ["init", "--bare"]); + yield* git(upstream, ["init", "--bare"]); + yield* git(cwd, ["remote", "add", "origin", fork]); + yield* git(cwd, ["remote", "add", "upstream", upstream]); + yield* git(cwd, ["push", "origin", "main"]); + yield* writeTextFile(cwd, "upstream.txt", "unrelated upstream work\n"); + yield* git(cwd, ["add", "upstream.txt"]); + yield* git(cwd, ["commit", "-m", "upstream work"]); + yield* git(cwd, ["push", "-u", "upstream", "main"]); + yield* git(cwd, ["checkout", "-b", "feature/from-local-main"]); + yield* git(cwd, ["config", "branch.feature/from-local-main.t3-merge-base", "main"]); + yield* writeTextFile(cwd, "feature.txt", "intended branch change\n"); + yield* git(cwd, ["add", "feature.txt"]); + yield* git(cwd, ["commit", "-m", "feature work"]); + + const status = yield* driver.statusDetailsLocal(cwd, { includeBranchChanges: true }); + assert.deepStrictEqual(status.branchChanges, { + baseRef: "upstream/main", + insertions: 1, + deletions: 0, + }); + assert.strictEqual(status.aheadCount, 1); + const preview = yield* driver.getReviewDiffPreview({ cwd }); + const changes = preview.sources.find((source) => source.kind === "branch-range")!; + assert.strictEqual(changes.baseRef, "upstream/main"); + assert.deepStrictEqual( + changes.files?.map((file) => file.path), + ["feature.txt"], + ); + }), + ); + it.effect("does not guess a Changes base for a branch renamed during the status read", () => Effect.gen(function* () { const cwd = yield* makeTmpDir(); diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index 0d6ef4631327d..25c7b4505e25f 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -2158,6 +2158,10 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* return { baseRef: comparisonRef, comparisonRef }; } if (configuredBase !== null) return configuredBase; + if (configuredBaseBranch.length > 0 && configuredBaseBranch !== refName) { + const trackedBase = yield* resolveTrackedRemoteBaseRef(cwd, configuredBaseBranch); + if (trackedBase !== null) return trackedBase; + } const primaryRemoteName = yield* resolvePrimaryRemoteName(cwd).pipe( Effect.orElseSucceed(() => null), From 2d558c4dad93f59cd03b5c3c9b3372555a503c84 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Wed, 18 Nov 2026 11:35:00 +0100 Subject: [PATCH 24/25] fix(web): the issue viewer shows why a refresh failed (#38537) Co-authored-by: Julius Marminge --- .../src/components/issue/IssueDetailPanel.tsx | 10 ++ 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 + .../issues-shows-failed-refresh.e2e.ts | 125 ++++++++++++++++++ 12 files changed, 145 insertions(+) create mode 100644 scripts/scenarios/issues-shows-failed-refresh.e2e.ts diff --git a/apps/web/src/components/issue/IssueDetailPanel.tsx b/apps/web/src/components/issue/IssueDetailPanel.tsx index d7d98e26e04fc..20a9d7aa93cf8 100644 --- a/apps/web/src/components/issue/IssueDetailPanel.tsx +++ b/apps/web/src/components/issue/IssueDetailPanel.tsx @@ -50,6 +50,7 @@ import { threadEnvironment } from "~/state/threads"; import { useAtomCommand } from "~/state/use-atom-command"; import { formatRelativeTimeLabel } from "~/timestampFormat"; +import { Alert, AlertDescription, AlertTitle } from "../ui/alert"; import { Button, InlineButton } from "../ui/button"; import { Input } from "../ui/input"; import { Menu, MenuItem, MenuPopup, MenuTrigger } from "../ui/menu"; @@ -667,6 +668,15 @@ export function IssueDetailPanel({ + {detailQuery.error !== null && !detailQuery.isPending ? ( +
+ + {gt("Could not refresh this issue")} + {detailQuery.error} + +
+ ) : null} + {editing === "title" ? (
+import type { IssueDetail, IssueRef } from "@t3tools/contracts"; +import { expect } from "e2e"; + +import { test, WEB } from "./t3.ts"; + +test( + "A failed issue refresh tells the reader what went wrong", + WEB, + async ({ t3, app, browser, screen }) => { + await t3.project("demo"); + await browser.addInitScript(() => { + let rateLimited = false; + Object.assign(window, { + armIssueRefreshFailure: () => { + rateLimited = true; + }, + }); + const refresh = new Promise((resolve) => { + Object.assign(window, { releaseIssueRefresh: () => resolve() }); + }); + // The first issue read succeeds; the refresh then hits GitHub's rate limit. + const send = WebSocket.prototype.send; + WebSocket.prototype.send = function (data) { + const request: { _tag: string; id: string; tag: string; payload: IssueRef } | null = + typeof data === "string" ? JSON.parse(data) : null; + if (request?._tag !== "Request" || request.tag !== "issues.detail") + return send.call(this, data); + const reply = (exit: unknown) => + this.dispatchEvent( + new MessageEvent("message", { + data: JSON.stringify({ _tag: "Exit", requestId: request.id, exit }), + }), + ); + if (rateLimited) { + void refresh.then(() => + reply({ + _tag: "Failure", + cause: [ + { + _tag: "Fail", + error: { + _tag: "IssueOperationError", + operation: "detail", + detail: "GitHub API rate limit exceeded.", + reason: "rate-limited", + }, + }, + ], + }), + ); + return; + } + const { projectId, tracker, scope, key } = request.payload; + const detail: IssueDetail = { + projectId, + tracker, + scope, + key, + host: "github.com", + displayKey: "#42", + projectTitle: "demo", + title: "Issue before the rate limit", + body: "The details from the last successful read.", + url: "https://github.com/example/demo/issues/42", + author: null, + state: { category: "open", name: "Open" }, + createdAt: "2026-10-01T00:00:00.000Z", + updatedAt: "2026-10-01T00:00:00.000Z", + closedAt: null, + assignees: [], + labels: [], + commentCount: 0, + writable: false, + capabilities: { + create: false, + edit: false, + comment: false, + labels: false, + assignees: false, + reactions: false, + templates: false, + linkedPullRequests: false, + events: false, + search: true, + }, + viewerPermissions: { + setState: false, + comment: false, + edit: false, + labels: false, + assignees: false, + }, + states: [], + viewer: null, + comments: [], + commentsCursor: null, + events: [], + linkedPullRequests: [], + }; + queueMicrotask(() => reply({ _tag: "Success", value: detail })); + }; + }); + + await t3.open("/issues?selectedProjectId=demo&tracker=github&scope=example/demo&key=42"); + await screen.getByText("Issue before the rate limit", { exact: true }).waitFor(); + await browser.evaluate(() => { + (window as unknown as { armIssueRefreshFailure: () => void }).armIssueRefreshFailure(); + return null; + }); + await screen.getByRole("button", "Refresh issue", { exact: true }).tap(); + const refreshing = browser.locator('button[aria-label="Refresh issue"]:disabled'); + await refreshing.waitFor(); + await browser.evaluate(() => { + (window as unknown as { releaseIssueRefresh: () => void }).releaseIssueRefresh(); + return null; + }); + await refreshing.waitFor({ state: "hidden" }); + await app.screenshot("after-failed-refresh"); + await expect( + screen.getByText("GitHub API rate limit exceeded.", { exact: false }), + ).toBeVisible(); + await expect(screen.getByText("Issue before the rate limit", { exact: true })).toBeVisible(); + }, +); From 1609536d206823b707ae194997aa5d9a9c1108d1 Mon Sep 17 00:00:00 2001 From: D3SOX Date: Wed, 18 Nov 2026 11:53:22 +0100 Subject: [PATCH 25/25] test(server): read the repaired service unit as its encoding --- apps/server/src/cloud/bootService.test.ts | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/apps/server/src/cloud/bootService.test.ts b/apps/server/src/cloud/bootService.test.ts index 756b81c7b1b7d..078c7bfedb7b8 100644 --- a/apps/server/src/cloud/bootService.test.ts +++ b/apps/server/src/cloud/bootService.test.ts @@ -548,9 +548,8 @@ it.layer(NodeServices.layer)("boot service install", (it) => { ? [runtime.entryPath, "__service-launcher"] : [desktopLauncherPath, "serve"], ); - expect((yield* fs.readFileString(repaired.unitPath)).includes(runtime.entryPath)).toBe( - platform === "win32", - ); + const unit = decodeServiceUnit(yield* fs.readFile(repaired.unitPath)); + expect(unit.includes(runtime.entryPath)).toBe(platform === "win32"); expect((yield* desktop.status).current).toBe(platform !== "win32"); yield* desktop.restart; expect((yield* desktop.status).current).toBe(platform !== "win32");