@devries-cameron20 / t3code-1 / commits / d067a04175
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

fix(web): a slow chat file link no longer replaces a file opened from the picker (#39130)

Co-authored-by: Julius Marminge <julius0216@outlook.com>

Wout Stiens committed Nov 19, 2026 at 15:30 UTC d067a0417546e073049ef5ae928604f06063dd96
5 files changed +241 -29
apps/web/src/components/ChatMarkdown.browser.test.tsx
+86 -4
@@ -10,7 +10,11 @@ import { act, render } from "../../test/render";
10 import "../index.css";
11
12 import { filesystemEnvironment } from "../state/filesystem";
13 -import { useRightPanelStore } from "../rightPanelStore";
13 +import {
14 + hostRightPanel,
15 + selectActiveRightPanelSurface,
16 + useRightPanelStore,
17 +} from "../rightPanelStore";
18 import {
19 CHAT_USER_MARKDOWN_REMARK_PLUGINS,
20 remarkEnableOrderedListNumbers,
@@ -508,9 +512,7 @@ describe("ChatMarkdown workspace file opens", () => {
512 resolvePending = resolve;
513 });
514 workspaceSearch.mockReturnValueOnce(pending);
511 - using openFile = vi
512 - .spyOn(useRightPanelStore.getState(), "openFile")
513 - .mockImplementation(() => {});
515 + using openFile = vi.spyOn(useRightPanelStore.getState(), "openFile");
516 await using screen = await renderText(
517 "[Notes](physics/notes/a.md) and [Other](/elsewhere/b.md:9)",
518 {
@@ -530,6 +532,86 @@ describe("ChatMarkdown workspace file opens", () => {
532 expect(openFile).toHaveBeenCalledExactlyOnceWith(threadRef, "/elsewhere/b.md", 9);
533 expect(workspaceSearch).toHaveBeenCalledOnce();
534 });
535 +
536 + it.each([
537 + ["its own panel", "thread-own-panel", false],
538 + ["its parent's panel from a side chat", "thread-side-chat", true],
539 + ])(
540 + "keeps a file opened elsewhere in %s when an earlier link lookup finishes",
541 + async (_, threadId, sideChat) => {
542 + setup();
543 + const host = { environmentId: threadRef.environmentId, threadId: ThreadId.make(threadId) };
544 + const linkRef = sideChat ? { ...host, threadId: ThreadId.make(`${threadId}-guest`) } : host;
545 + using _hosted = { [Symbol.dispose]: sideChat ? hostRightPanel(linkRef, host) : () => {} };
546 + const result = AsyncResult.success({
547 + entries: [{ path: "notes/cited-note.txt", kind: "file" }],
548 + truncated: false,
549 + });
550 + const { promise: pending, resolve: resolvePending } = Promise.withResolvers<typeof result>();
551 + workspaceSearch.mockReturnValueOnce(pending);
552 + await using screen = await renderText("[Cited](cited-note.txt)", {
553 + cwd: "/repo",
554 + threadRef: linkRef,
555 + });
556 + await act(async () => screen.container.querySelector("a")!.click());
557 + expect(workspaceSearch).toHaveBeenCalledOnce();
558 +
559 + useRightPanelStore.getState().openFile(host, "picker-note.txt");
560 + await act(async () => resolvePending(result));
561 +
562 + expect(
563 + selectActiveRightPanelSurface(useRightPanelStore.getState().byThreadKey, host),
564 + ).toMatchObject({ kind: "file", relativePath: "picker-note.txt" });
565 + },
566 + );
567 +
568 + it.each([
569 + ["open a link in another panel", "separate-panels"],
570 + ["unhost the side chat", "unhosted-side-chat"],
571 + ] as const)("keeps a citation in its original panel scope if you %s", async (action, scope) => {
572 + setup();
573 + const host = { ...threadRef, threadId: ThreadId.make(`${scope}-host`) };
574 + const guest = { ...threadRef, threadId: ThreadId.make(`${scope}-guest`) };
575 + const other = { ...threadRef, threadId: ThreadId.make(`${scope}-other`) };
576 + const unhost = hostRightPanel(guest, host);
577 + using _hosted = { [Symbol.dispose]: unhost };
578 + const result = AsyncResult.success({
579 + entries: [{ path: "notes/cited-note.txt", kind: "file" }],
580 + truncated: false,
581 + });
582 + const { promise: pending, resolve: resolvePending } = Promise.withResolvers<typeof result>();
583 + workspaceSearch.mockReturnValueOnce(pending);
584 + await using screen = await render(
585 + <>
586 + <ChatMarkdown cwd="/repo" threadRef={guest} text="[Cited](cited-note.txt)" />
587 + <ChatMarkdown cwd="/repo" threadRef={other} text="[Other](/elsewhere/other.md)" />
588 + </>,
589 + );
590 + const [cited, otherLink] = screen.container.querySelectorAll("a");
591 + await act(async () => cited!.click());
592 + expect(workspaceSearch).toHaveBeenCalledOnce();
593 + if (action === "open a link in another panel") {
594 + await act(async () => otherLink!.click());
595 + } else {
596 + unhost();
597 + }
598 + await act(async () => resolvePending(result));
599 +
600 + const { byThreadKey } = useRightPanelStore.getState();
601 + expect(selectActiveRightPanelSurface(byThreadKey, guest)).toBeNull();
602 + if (action === "unhost the side chat") {
603 + expect(selectActiveRightPanelSurface(byThreadKey, host)).toBeNull();
604 + } else {
605 + expect(selectActiveRightPanelSurface(byThreadKey, host)).toMatchObject({
606 + kind: "file",
607 + relativePath: "notes/cited-note.txt",
608 + });
609 + expect(selectActiveRightPanelSurface(byThreadKey, other)).toMatchObject({
610 + kind: "file",
611 + relativePath: "/elsewhere/other.md",
612 + });
613 + }
614 + });
615 });
616
617 describe("ChatMarkdown skill chips", () => {
apps/web/src/components/ChatMarkdown.tsx
+11 -5
@@ -61,6 +61,7 @@ import {
61 isAtomCommandInterrupted,
62 squashAtomCommandFailure,
63 } from "@t3tools/client-runtime/state/runtime";
64 +import { scopedThreadKey } from "@t3tools/client-runtime/environment";
65 import type {
66 CodexArtifactTemplate,
67 CodexArtifactTemplateKind,
@@ -162,7 +163,7 @@ import { appAtomRegistry } from "../rpc/atomRegistry";
163 import { hostEnvironmentIdAtom } from "../state/primaryEnvironment";
164 import { cn } from "../lib/utils";
165 import { resolveRemoteOpenState, useRemoteOpenResolution } from "../remoteOpen";
165 -import { useRightPanelStore } from "../rightPanelStore";
166 +import { rightPanelHostRef, useRightPanelStore } from "../rightPanelStore";
167 import { useOpenIssueLink } from "../lib/openIssueLink";
168 import { issueTrackerEnvironment } from "../state/issueTrackers";
169 import { useEnvironmentQuery } from "../state/query";
@@ -181,7 +182,6 @@ import { useAtomQueryRunner } from "../state/use-atom-query-runner";
182 import { projectEnvironment } from "../state/projects";
183 import { filesystemEnvironment } from "../state/filesystem";
184 import {
184 - claimWorkspaceBasenameLookup,
185 findAgentDirectoryMatch,
186 needsWorkspaceBasenameLookup,
187 pickProjectLinkMatch,
@@ -893,8 +893,6 @@ function useChatMarkdownState({
893 };
894 const openFileInPanel = (fileLinkMeta: MarkdownFileLinkMeta, panelPath: string) => {
895 if (!threadRef) return;
896 - // Every open supersedes pending lookups, including synchronous opens.
897 - const isLatestLookup = claimWorkspaceBasenameLookup();
896 const openAt = (path: string) =>
897 useRightPanelStore.getState().openFile(threadRef, path, fileLinkMeta.line);
898 if (
@@ -905,9 +903,17 @@ function useChatMarkdownState({
903 openAt(panelPath);
904 return;
905 }
906 + // Anything the user opens in this panel meanwhile, such as a file from the picker, wins.
907 + const panelRef = rightPanelHostRef(threadRef);
908 + const panelKey = scopedThreadKey(panelRef);
909 + const userActionRevision = useRightPanelStore.getState().markUserAction(panelRef);
910 void (async () => {
911 const match = await findWorkspaceFileMatch(fileLinkMeta);
910 - if (!isLatestLookup()) return;
912 + if (
913 + scopedThreadKey(rightPanelHostRef(threadRef)) !== panelKey ||
914 + useRightPanelStore.getState().getUserActionRevision(panelRef) !== userActionRevision
915 + )
916 + return;
917 openAt(match ?? panelPath);
918 })();
919 };
apps/web/src/workspaceBasenameLookup.test.ts
-11
@@ -2,7 +2,6 @@ import { describe, expect, it } from "vite-plus/test";
2
3 import {
4 agentWorkingDirectories,
5 - claimWorkspaceBasenameLookup,
5 findAgentDirectoryMatch,
6 pickProjectLinkMatch,
7 pickWorkspaceBasenameMatch,
@@ -183,13 +182,3 @@ describe("findAgentDirectoryMatch", () => {
182 expect(await findAgentDirectoryMatch("config.test.yaml", ["/work/repo-b"], found)).toBeNull();
183 });
184 });
186 -
187 -describe("claimWorkspaceBasenameLookup", () => {
188 - it("keeps only the newest claim, whatever order the lookups settle in", () => {
189 - const first = claimWorkspaceBasenameLookup();
190 - const second = claimWorkspaceBasenameLookup();
191 -
192 - expect(second()).toBe(true);
193 - expect(first()).toBe(false);
194 - });
195 -});
packages/client-runtime/src/workspaceBasenameLookup.ts
-9
@@ -7,15 +7,6 @@ import {
7
8 export const WORKSPACE_BASENAME_LOOKUP_LIMIT = 25;
9
10 -// All callers open one panel; the newest click must win across callers.
11 -let latestLookupSequence = 0;
12 -
13 -export function claimWorkspaceBasenameLookup(): () => boolean {
14 - latestLookupSequence += 1;
15 - const claimed = latestLookupSequence;
16 - return () => claimed === latestLookupSequence;
17 -}
18 -
10 export interface WorkspaceEntryCandidate {
11 readonly path: string;
12 readonly kind: "file" | "directory";
scripts/scenarios/file-picker-keeps-newer-file.e2e.ts new
+144
@@ -0,0 +1,144 @@
1 +/// <reference lib="dom" />
2 +import type { EnvironmentId, ProjectSearchEntriesInput } from "@t3tools/contracts";
3 +import { expect } from "e2e";
4 +import type { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
5 +
6 +import { test, WEB } from "./t3.ts";
7 +
8 +const CITED = "cited-note.txt";
9 +const PICKED = "picker-note.txt";
10 +
11 +test(
12 + "A slow citation leaves the newer file picker choice active",
13 + WEB,
14 + async ({ t3, app, browser, screen }) => {
15 + const project = await t3.project("demo", {
16 + [`notes/${CITED}`]: "Text from the earlier citation",
17 + [PICKED]: "Text from the newer choice",
18 + });
19 + const thread = await t3.thread({
20 + project,
21 + title: "File preview order",
22 + messages: [`See :codex-file-citation{path="${CITED}" line_range_start="1"}`],
23 + });
24 +
25 + await browser.addInitScript((citation) => {
26 + const { promise: requested, resolve: markRequested } = Promise.withResolvers<void>();
27 + const { promise: released, resolve: release } = Promise.withResolvers<void>();
28 + const { promise: replied, resolve: markReplied } = Promise.withResolvers<void>();
29 + Object.assign(window, {
30 + citationRequested: requested,
31 + releaseCitation: release,
32 + citationReplied: replied,
33 + });
34 +
35 + // Delay only the citation's real search, so the file picker can search in the meantime.
36 + const send = WebSocket.prototype.send;
37 + WebSocket.prototype.send = function (data) {
38 + const request =
39 + typeof data === "string"
40 + ? (JSON.parse(data) as {
41 + _tag?: string;
42 + id?: string;
43 + tag?: string;
44 + payload?: { query?: string };
45 + })
46 + : null;
47 + if (
48 + request?._tag !== "Request" ||
49 + request.tag !== "projects.searchEntries" ||
50 + request.payload?.query !== citation
51 + ) {
52 + return send.call(this, data);
53 + }
54 +
55 + const onReply = (event: MessageEvent) => {
56 + if (typeof event.data !== "string") return;
57 + const messages = [JSON.parse(event.data)].flat();
58 + if (
59 + !messages.some((message) => message._tag === "Exit" && message.requestId === request.id)
60 + )
61 + return;
62 + this.removeEventListener("message", onReply);
63 + markReplied();
64 + };
65 + this.addEventListener("message", onReply);
66 + Object.assign(window, { citationInput: request.payload });
67 + markRequested();
68 + void released.then(() => send.call(this, data));
69 + };
70 + }, CITED);
71 +
72 + const activeTab = browser.locator('[data-active-tab="true"]');
73 + await t3.open(thread);
74 + await screen.getByRole("button", /^Agent See/).tap();
75 + await screen.getByRole("link", /^cited-note\.txt/).tap();
76 + await browser.evaluate(async () => {
77 + await (window as unknown as { citationRequested: Promise<void> }).citationRequested;
78 + return null;
79 + });
80 +
81 + await browser.keyboard.press("Control+p");
82 + await screen.getByPlaceholder("Search files…").fill(PICKED);
83 + await screen.getByRole("option", PICKED, { exact: false }).tap();
84 + await activeTab.getByText(PICKED, { exact: true }).waitFor();
85 +
86 + await browser.evaluate(async () => {
87 + const test = window as unknown as {
88 + releaseCitation: () => void;
89 + citationReplied: Promise<void>;
90 + citationInput: ProjectSearchEntriesInput;
91 + };
92 + const registryModule = "/src/rpc/atomRegistry.ts";
93 + const projectsModule = "/src/state/projects.ts";
94 + const reactModule = performance
95 + .getEntriesByType("resource")
96 + .find(({ name }) => /\/\.vite\/deps\/react\.js(?:\?|$)/.test(name))?.name;
97 + if (!reactModule) throw new Error("The app's React module has not loaded");
98 + const [{ appAtomRegistry }, { projectEnvironment }, { default: react }] = await Promise.all([
99 + import(registryModule) as Promise<{
100 + appAtomRegistry: Pick<AtomRegistry.AtomRegistry, "subscribe">;
101 + }>,
102 + import(projectsModule) as Promise<{
103 + projectEnvironment: {
104 + searchEntries: (target: {
105 + environmentId: EnvironmentId;
106 + input: ProjectSearchEntriesInput;
107 + }) => Atom.Atom<AsyncResult.AsyncResult<unknown, unknown>>;
108 + };
109 + }>,
110 + import(reactModule) as Promise<{
111 + default: { act: (run: () => Promise<void>) => PromiseLike<void> };
112 + }>,
113 + ]);
114 + const atom = projectEnvironment.searchEntries({
115 + environmentId: location.pathname.split("/")[1] as EnvironmentId,
116 + input: test.citationInput,
117 + });
118 + // Wait for the query used by the citation and flush React before reading the selected tab.
119 + const settled = Promise.resolve(
120 + react.act(async () => {
121 + const { promise, resolve } = Promise.withResolvers<void>();
122 + const unsubscribe = appAtomRegistry.subscribe(atom, (result) => {
123 + if (result._tag !== "Initial" && !result.waiting) resolve();
124 + });
125 + try {
126 + await promise;
127 + } finally {
128 + unsubscribe();
129 + }
130 + }),
131 + );
132 + test.releaseCitation();
133 + await test.citationReplied;
134 + await settled;
135 + return null;
136 + });
137 + await app.screenshot("active-file-after-citation-search");
138 + const activeFile = await browser.evaluate(
139 + () =>
140 + document.querySelector('[data-active-tab="true"] button:last-of-type')?.textContent ?? null,
141 + );
142 + expect(activeFile).toBe(PICKED);
143 + },
144 +);