Skip to content

Commit 073902d

Browse files
fix(desktop): native file links stay on the machine that owns them
The shared scratch selector now falls back to the sole eligible machine when the current one has no scratch root. That is right for web links and the New thread menu, but a native file opened through the desktop link bridge lives on the primary: starting its thread on a remote machine would create a draft there and request an asset that server cannot serve. Native files now only get a scratch thread on the primary, and fail before any remote draft or asset request when the primary has no scratch root and no reusable preview. Web links keep the fallback. Co-Authored-By: Claude Fable 5.1 <[email protected]>
1 parent f467fa4 commit 073902d

2 files changed

Lines changed: 164 additions & 4 deletions

File tree

Lines changed: 152 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,152 @@
1+
import { scopeThreadRef } from "@t3tools/client-runtime/environment";
2+
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
3+
import { act } from "react";
4+
import { createRoot, type Root } from "react-dom/client";
5+
import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
6+
7+
const PRIMARY = EnvironmentId.make("primary");
8+
const REMOTE = EnvironmentId.make("remote");
9+
10+
const state = vi.hoisted(() => ({
11+
routeParams: {} as Record<string, string>,
12+
environments: [] as Array<{
13+
environmentId: string;
14+
connection: { phase: string };
15+
serverConfig: { scratchWorkspaceRoot: string | null };
16+
}>,
17+
openScratch: vi.fn(),
18+
openFileInPreview: vi.fn(),
19+
openUrlInPreview: vi.fn(),
20+
}));
21+
vi.mock(import("@tanstack/react-router"), async (original) => ({
22+
...(await original()),
23+
useRouter: (() => ({
24+
navigate: vi.fn(),
25+
state: {
26+
get matches() {
27+
return [{ params: state.routeParams }];
28+
},
29+
},
30+
})) as never,
31+
}));
32+
vi.mock(import("../../state/environments"), async (original) => ({
33+
...(await original()),
34+
useEnvironments: (() => ({ environments: state.environments })) as never,
35+
usePrimaryEnvironment: (() => state.environments[0]) as never,
36+
useEnvironmentHttpBaseUrl: (() => "http://primary.test") as never,
37+
}));
38+
vi.mock(import("../../state/use-atom-command"), async (original) => ({
39+
...(await original()),
40+
useAtomCommand: (() => state.openScratch) as never,
41+
}));
42+
vi.mock(import("../../state/use-atom-query-runner"), async (original) => ({
43+
...(await original()),
44+
useAtomQueryRunner: (() => vi.fn()) as never,
45+
}));
46+
vi.mock(import("../../hooks/useHandleNewThread"), async (original) => ({
47+
...(await original()),
48+
useNewThreadHandler: (() => async () => ({ threadId: "draft-thread" })) as never,
49+
}));
50+
vi.mock(import("../../browser/previewRuntime"), async (original) => ({
51+
...(await original()),
52+
isPreviewAvailableFor: () => true,
53+
}));
54+
vi.mock(import("../../browser/openFileInPreview"), async (original) => ({
55+
...(await original()),
56+
openFileInPreview: state.openFileInPreview,
57+
openUrlInPreview: state.openUrlInPreview,
58+
}));
59+
import { useRightPanelStore } from "../../rightPanelStore";
60+
import { toastManager } from "../ui/toast";
61+
import { DesktopWebLinkCoordinator } from "./DesktopWebLinkCoordinator";
62+
63+
let root: Root;
64+
let deliver: (url: string) => void;
65+
let toast: ReturnType<typeof vi.spyOn>;
66+
67+
beforeEach(async () => {
68+
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
69+
toast = vi.spyOn(toastManager, "add");
70+
state.routeParams = {};
71+
// The primary is connected but has no scratch root; the remote is the sole
72+
// machine that could start a project-free thread.
73+
state.environments = [
74+
{
75+
environmentId: PRIMARY,
76+
connection: { phase: "connected" },
77+
serverConfig: { scratchWorkspaceRoot: null },
78+
},
79+
{
80+
environmentId: REMOTE,
81+
connection: { phase: "connected" },
82+
serverConfig: { scratchWorkspaceRoot: "/scratch" },
83+
},
84+
];
85+
state.openScratch.mockReset().mockImplementation(async ({ environmentId }) => ({
86+
_tag: "Success",
87+
value: { environmentId, id: "scratch-project" },
88+
}));
89+
state.openFileInPreview.mockReset().mockResolvedValue({ _tag: "Success", value: undefined });
90+
state.openUrlInPreview.mockReset().mockResolvedValue({ _tag: "Success", value: undefined });
91+
window.desktopBridge = {
92+
webLinks: {
93+
setReady: async () => undefined,
94+
onOpen: (listener: (url: string) => void) => {
95+
deliver = listener;
96+
return () => undefined;
97+
},
98+
},
99+
} as never;
100+
root = createRoot(document.createElement("div"));
101+
await act(async () => root.render(<DesktopWebLinkCoordinator />));
102+
});
103+
afterEach(async () => {
104+
await act(async () => root.unmount());
105+
delete window.desktopBridge;
106+
vi.unstubAllGlobals();
107+
vi.restoreAllMocks();
108+
});
109+
110+
async function open(url: string) {
111+
await act(async () => {
112+
deliver(url);
113+
await vi.waitFor(() =>
114+
expect(
115+
state.openScratch.mock.calls.length +
116+
state.openFileInPreview.mock.calls.length +
117+
state.openUrlInPreview.mock.calls.length +
118+
toast.mock.calls.length,
119+
).toBeGreaterThan(0),
120+
);
121+
});
122+
}
123+
124+
it("keeps native files on the machine that owns them instead of a remote scratch thread", async () => {
125+
await open("file:///tmp/page.html");
126+
127+
expect(toast).toHaveBeenCalledWith(expect.objectContaining({ title: "Could not open the link" }));
128+
expect(state.openScratch).not.toHaveBeenCalled();
129+
expect(state.openFileInPreview).not.toHaveBeenCalled();
130+
});
131+
132+
it("still sends web links to the sole remote that can start a project-free thread", async () => {
133+
await open("https://example.com/");
134+
135+
expect(state.openScratch).toHaveBeenCalledWith({ environmentId: REMOTE, input: {} });
136+
expect(state.openUrlInPreview).toHaveBeenCalledWith(
137+
expect.objectContaining({ threadRef: scopeThreadRef(REMOTE, ThreadId.make("draft-thread")) }),
138+
);
139+
});
140+
141+
it("reuses the primary's open browser for native files", async () => {
142+
const threadRef = scopeThreadRef(PRIMARY, ThreadId.make("chat"));
143+
state.routeParams = { environmentId: PRIMARY, threadId: "chat" };
144+
useRightPanelStore.getState().openBrowser(threadRef, null);
145+
146+
await open("file:///tmp/page.html");
147+
148+
expect(state.openScratch).not.toHaveBeenCalled();
149+
expect(state.openFileInPreview).toHaveBeenCalledWith(
150+
expect.objectContaining({ threadRef, filePath: "/tmp/page.html" }),
151+
);
152+
});

‎apps/web/src/components/desktop/DesktopWebLinkCoordinator.tsx‎

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ function threadShowingBrowser(
4747
export function DesktopWebLinkCoordinator() {
4848
const router = useRouter();
4949
const primaryEnvironment = usePrimaryEnvironment();
50-
const { scratchEnvironmentId, openScratchProject } = useScratchProject();
50+
const { scratchEnvironmentId, scratchWorkspaceRootFor, openScratchProject } = useScratchProject();
5151
const openThread = useNewThreadHandler();
5252
const openPreview = useAtomCommand(previewEnvironment.open, { reportFailure: false });
5353
const createAssetUrl = useAtomQueryRunner(assetEnvironment.createUrl, {
@@ -67,8 +67,16 @@ export function DesktopWebLinkCoordinator() {
6767
stackedThreadToast({ type: "error", title: "Could not open the link", description }),
6868
);
6969

70-
const startThread = async (url: string): Promise<ScopedThreadRef | null> => {
71-
const environmentId = scratchEnvironmentId(primaryEnvironment?.environmentId ?? null);
70+
const startThread = async (url: string, isFile: boolean): Promise<ScopedThreadRef | null> => {
71+
const primaryId = primaryEnvironment?.environmentId ?? null;
72+
// A native file lives on the primary, so its thread must too: another
73+
// machine's scratch thread would request the asset from a server that
74+
// cannot serve it.
75+
const environmentId = isFile
76+
? scratchWorkspaceRootFor(primaryId) === null
77+
? null
78+
: primaryId
79+
: scratchEnvironmentId(primaryId);
7280
if (environmentId === null) {
7381
reportFailure(url);
7482
return null;
@@ -97,7 +105,7 @@ export function DesktopWebLinkCoordinator() {
97105
threadShowingBrowser(
98106
routeParams,
99107
isFile ? (primaryEnvironment?.environmentId ?? null) : null,
100-
) ?? (await startThread(url));
108+
) ?? (await startThread(url, isFile));
101109
if (threadRef === null) return;
102110
const result = isFile
103111
? httpBaseUrl === null

0 commit comments

Comments
 (0)