Skip to content

Commit 1656bc1

Browse files
committed
Merge remote-tracking branch 'origin/main' into t3/windows-service-trim
2 parents bddafe6 + 6c7d23d commit 1656bc1

72 files changed

Lines changed: 2479 additions & 293 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎apps/desktop/src/app/DesktopCliShim.test.ts‎

Lines changed: 80 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -41,10 +41,10 @@ const run = (shim: string, args: ReadonlyArray<string>, env: NodeJS.ProcessEnv =
4141
const REPORTER =
4242
'#!/bin/sh\necho "node=$ELECTRON_RUN_AS_NODE cli=$T3CODE_CLI_PATH home=$T3CODE_HOME"\nprintf "%s\\n" "$@"\nexit 3\n';
4343

44-
const fakeAppImage = (canMount = true) => {
44+
const fakeAppImage = (canMount = true, app = REPORTER) => {
4545
const root = tempRoot();
4646
const image = NodePath.join(root, "image");
47-
writeExecutable(NodePath.join(image, "t3code"), REPORTER);
47+
writeExecutable(NodePath.join(image, "t3code"), app);
4848
const appImage = NodePath.join(root, "T3 Code.AppImage");
4949
writeExecutable(
5050
appImage,
@@ -53,8 +53,11 @@ const fakeAppImage = (canMount = true) => {
5353
`if [ "$1" = --appimage-extract ]; then cp -R '${image}' squashfs-root; exit 0; fi`,
5454
'[ "$1" = --appimage-mount ] || exit 9',
5555
'[ -n "$APPIMAGE_EXTRACT_AND_RUN" ] && exit 8',
56+
`echo $$ >'${root}/mounter.pid'`,
5657
canMount ? `echo '${image}'` : 'echo "Cannot mount AppImage"; exit 1',
57-
`trap 'touch "${root}/unmounted"; exit 0' TERM`,
58+
// Like the FUSE runtime, any of these unmounts. fd 3 reports to the test when it is open.
59+
`trap 'echo unmounted >&3 2>/dev/null; touch "${root}/unmounted"; exit 0' TERM HUP INT`,
60+
"trap 'echo mounted >&3 2>/dev/null' WINCH",
5861
"while :; do sleep 0.05; done",
5962
"",
6063
].join("\n"),
@@ -63,7 +66,81 @@ const fakeAppImage = (canMount = true) => {
6366
return { root, image, appImage, shim };
6467
};
6568

69+
// Stays up after a signal until the test lets it finish, like a server shutting down.
70+
const SLOW_SERVER = [
71+
"#!/bin/sh",
72+
"trap 'echo stopping >&3; read go; echo stopped >&3; exit 0' TERM HUP",
73+
"echo ready",
74+
"while :; do sleep 0.05; done",
75+
"",
76+
].join("\n");
77+
78+
// The launcher mounts only under setsid, which stock macOS and Windows lack; there it extracts instead.
79+
const hasSetsid = NodeChildProcess.spawnSync("setsid", ["true"]).status === 0;
80+
81+
const lines = (stream: NodeJS.ReadableStream) => {
82+
const seen: Array<string> = [];
83+
const waiters: Array<() => void> = [];
84+
let buffer = "";
85+
stream.setEncoding("utf8");
86+
stream.on("data", (chunk: string) => {
87+
buffer += chunk;
88+
const parts = buffer.split("\n");
89+
buffer = parts.pop()!;
90+
seen.push(...parts);
91+
for (const wake of waiters.splice(0)) wake();
92+
});
93+
const until = async (match: (line: string) => boolean) => {
94+
for (;;) {
95+
const line = seen.find(match);
96+
if (line !== undefined) return line;
97+
await new Promise<void>((resolve) => waiters.push(resolve));
98+
}
99+
};
100+
return { seen, until };
101+
};
102+
66103
describe("renderCliShim", () => {
104+
it.skipIf(!hasSetsid).each(["SIGTERM", "SIGHUP"] as const)(
105+
"keeps the AppImage mounted until the server exits after %s to the process group",
106+
async (signal) => {
107+
const { root, shim } = fakeAppImage(true, SLOW_SERVER);
108+
const child = NodeChildProcess.spawn(shim, [], {
109+
detached: true,
110+
env: { PATH: process.env.PATH },
111+
stdio: ["pipe", "pipe", "ignore", "pipe"],
112+
});
113+
let mounter: number | undefined;
114+
try {
115+
const stdout = lines(child.stdout!);
116+
const events = lines(child.stdio[3] as NodeJS.ReadableStream);
117+
const exited = new Promise((resolve) => child.on("close", resolve));
118+
await stdout.until((line) => line === "ready");
119+
mounter = Number(NodeFS.readFileSync(NodePath.join(root, "mounter.pid"), "utf8"));
120+
121+
// Ctrl-C in a terminal, a closed SSH session, or a service manager signals the whole group.
122+
process.kill(-child.pid!, signal);
123+
// The shell runs pending traps in ascending signal number, and WINCH outnumbers TERM and
124+
// HUP, so a mounter that also got the group signal unmounts before it answers this probe.
125+
process.kill(mounter, "SIGWINCH");
126+
const mount = await events.until((line) => line === "mounted" || line === "unmounted");
127+
expect(mount).toBe("mounted");
128+
129+
await events.until((line) => line === "stopping");
130+
child.stdin!.end("go\n");
131+
await exited;
132+
expect(events.seen.slice(-2)).toEqual(["stopped", "unmounted"]);
133+
} finally {
134+
for (const pid of [-child.pid!, mounter]) {
135+
if (pid === undefined) continue;
136+
try {
137+
process.kill(pid, "SIGKILL");
138+
} catch {}
139+
}
140+
}
141+
},
142+
);
143+
67144
it("extracts the AppImage where it cannot be mounted", () => {
68145
const { shim } = fakeAppImage(false);
69146
const result = run(shim, ["--version"], { APPIMAGE_EXTRACT_AND_RUN: "1" });

‎apps/desktop/src/app/DesktopCliShim.ts‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -90,12 +90,13 @@ export const renderCliShim = (input: {
9090
...header,
9191
// Extract-and-run would make the runtime start the app instead of mounting it.
9292
"unset APPIMAGE_EXTRACT_AND_RUN",
93-
// The runtime stays mounted until killed; traps unmount it because background jobs ignore Ctrl-C.
93+
// Its own session keeps a group signal (Ctrl-C, SSH hangup) from unmounting it under the
94+
// running server; the traps unmount it after. Without setsid the extract fallback runs.
9495
"work=$(mktemp -d) || exit 1",
95-
'"$app" --appimage-mount >"$work/mount" 2>/dev/null &',
96+
'setsid "$app" --appimage-mount >"$work/mount" 2>/dev/null &',
9697
"mounter=$!",
9798
`trap 'kill "$mounter" 2>/dev/null; rm -rf "$work"' EXIT`,
98-
"trap 'exit 130' INT TERM",
99+
"trap 'exit 130' INT TERM HUP",
99100
"mount=",
100101
'while kill -0 "$mounter" 2>/dev/null; do',
101102
' mount=$(head -n 1 "$work/mount")',

‎apps/server/src/device/DeviceHubProxy.test.ts‎

Lines changed: 63 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,10 @@ const fixture = (
2727
) => {
2828
let finalized = 0;
2929
const requests: string[] = [];
30+
const screenshots: Array<Parameters<DeviceService.DeviceService["Service"]["screenshot"]>[0]> =
31+
[];
3032
const headers: Array<Readonly<Record<string, string>>> = [];
33+
const unexpectedOperation = Effect.die("Unexpected device operation");
3134
const client = HttpClient.make((request, _url, signal) =>
3235
Effect.gen(function* () {
3336
requests.push(request.url);
@@ -45,7 +48,7 @@ const fixture = (
4548
const { handler, dispose } = HttpRouter.toWebHandler(
4649
DeviceHubProxy.layer.pipe(
4750
Layer.provideMerge(
48-
Layer.succeed(EnvironmentAuth.EnvironmentAuth, {
51+
Layer.mock(EnvironmentAuth.EnvironmentAuth)({
4952
authenticateWebSocketUpgrade: () =>
5053
authError
5154
? Effect.fail(authError)
@@ -55,24 +58,50 @@ const fixture = (
5558
method: "bearer-access-token",
5659
scopes,
5760
}),
58-
} as unknown as EnvironmentAuth.EnvironmentAuth["Service"]),
61+
}),
5962
),
6063
Layer.provideMerge(
61-
Layer.succeed(DeviceService.DeviceService, {
62-
currentReadiness: () =>
64+
Layer.mock(DeviceService.DeviceService)({
65+
currentReadiness: (hostId) =>
6366
Effect.succeed({
64-
hostId: LOCAL_DEVICE_HOST_ID,
67+
hostId: hostId ?? LOCAL_DEVICE_HOST_ID,
68+
nodePath: "node",
6569
hub: { origin: "http://hub.test" },
70+
devices: {
71+
list: unexpectedOperation,
72+
boot: () => unexpectedOperation,
73+
attach: () => unexpectedOperation,
74+
shutdown: () => unexpectedOperation,
75+
screenshot: () => unexpectedOperation,
76+
},
77+
run: () => unexpectedOperation,
78+
helpers: { serveSimAxSettings: null, serveSimCli: null },
6679
...(upstream ? { upstream } : {}),
6780
}),
68-
} as DeviceService.DeviceService["Service"]),
81+
screenshot: (input) =>
82+
Effect.sync(() => {
83+
screenshots.push(input);
84+
return {
85+
device: {
86+
hostId: input.hostId ?? LOCAL_DEVICE_HOST_ID,
87+
id: input.deviceId,
88+
platform: "ios",
89+
name: "Phone",
90+
version: "27.0",
91+
booted: true,
92+
physical: false,
93+
},
94+
png: new Uint8Array([137, 80, 78, 71]),
95+
};
96+
}),
97+
}),
6998
),
7099
Layer.provideMerge(Layer.succeed(HttpClient.HttpClient, client)),
71100
),
72101
{ disableLogger: true },
73102
);
74103
disposers.push(dispose);
75-
return { handler, requests, headers, finalized: () => finalized };
104+
return { handler, requests, screenshots, headers, finalized: () => finalized };
76105
};
77106

78107
describe("device hub proxy", () => {
@@ -239,6 +268,33 @@ describe("device hub proxy", () => {
239268
).toBe(404);
240269
expect(requests).toEqual([]);
241270
});
271+
272+
it.each(["serve-sim", "serve-emu"])(
273+
"captures %s screenshots through hosts with their own stream routing",
274+
async (vendor) => {
275+
const { handler, requests, screenshots } = fixture(
276+
[AuthOrchestrationReadScope],
277+
false,
278+
undefined,
279+
() => Effect.succeed(null),
280+
);
281+
const response = await handler(
282+
new Request(
283+
`http://t3.test/api/device-hub/vendor/${vendor}/api/screenshot?device=udid-1&hostId=pool`,
284+
{
285+
method: "POST",
286+
},
287+
),
288+
);
289+
expect(response.status).toBe(200);
290+
expect(response.headers.get("content-type")).toBe("image/png");
291+
expect(new Uint8Array(await response.arrayBuffer())).toEqual(
292+
new Uint8Array([137, 80, 78, 71]),
293+
);
294+
expect(requests).toEqual([]);
295+
expect(screenshots).toEqual([{ hostId: "pool", deviceId: "udid-1" }]);
296+
},
297+
);
242298
});
243299

244300
it.each([

‎apps/server/src/device/DeviceHubProxy.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -214,7 +214,10 @@ const handler = Effect.gen(function* () {
214214
upstreamSearch.delete("hostId");
215215
const search = upstreamSearch.size > 0 ? `?${upstreamSearch.toString()}` : "";
216216
const screenshotDevice = upstreamSearch.get("device");
217-
if (!ready.upstream && hubPath === "/vendor/serve-sim/api/screenshot" && screenshotDevice) {
217+
if (
218+
screenshotDevice &&
219+
["/vendor/serve-sim/api/screenshot", "/vendor/serve-emu/api/screenshot"].includes(hubPath)
220+
) {
218221
const { png } = yield* devices.screenshot({ hostId: ready.hostId, deviceId: screenshotDevice });
219222
return HttpServerResponse.uint8Array(png, {
220223
contentType: "image/png",

‎apps/server/src/guest/GuestShareService.test.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,7 @@ const layerProviders = Layer.mock(ProviderRegistry.ProviderRegistry)({
9090
getProviders: Effect.succeed([]),
9191
});
9292
const layerConfig = ServerConfig.layerTest(process.cwd(), { prefix: "t3-guest-share-" });
93-
// The real cleanup also closes terminals and previews; these tests only need the files gone.
93+
// The real cleanup also closes terminals, previews and devices; these tests only need the files gone.
9494
const layerCleanup = Layer.effect(
9595
ResourceCleanupService.ResourceCleanupService,
9696
Effect.gen(function* () {
@@ -100,6 +100,7 @@ const layerCleanup = Layer.effect(
100100
cleanupScheduledTasks: () => Effect.void,
101101
cleanupTerminals: () => Effect.void,
102102
cleanupPreviews: () => Effect.void,
103+
cleanupDevices: () => Effect.void,
103104
cleanupAttachments: (attachmentIds) =>
104105
Effect.forEach(
105106
attachmentIds,

‎apps/server/src/htmlRender/HtmlRender.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -453,6 +453,7 @@ process.on("SIGTERM", () => {});
453453
const quit = () => { fs.writeFileSync(${JSON.stringify(exitRecord)}, "asked to close"); process.exit(0); };
454454
const reply = (message) => fs.writeSync(4, JSON.stringify(message) + "\\0");
455455
const results = {
456+
"Target.createBrowserContext": { browserContextId: "context" },
456457
"Target.createTarget": { targetId: "page" },
457458
"Target.attachToTarget": { sessionId: "session" },
458459
"Runtime.evaluate": { result: { value: 100 } },

‎apps/server/src/htmlRender/headlessChrome.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -418,10 +418,17 @@ const launchBrowser = Effect.fnUntraced(function* (input: {
418418
);
419419
});
420420

421+
// Chrome's default context can stall Fetch interception during navigation.
422+
const { browserContextId } = yield* send(
423+
"Target.createBrowserContext",
424+
{},
425+
Schema.Struct({ browserContextId: Schema.String }),
426+
);
427+
421428
const openPage = Effect.fnUntraced(function* (width: number, appearance: ThemeAppearance) {
422429
const { targetId } = yield* send(
423430
"Target.createTarget",
424-
{ url: "about:blank" },
431+
{ url: "about:blank", browserContextId },
425432
Schema.Struct({ targetId: Schema.String }),
426433
);
427434
const { sessionId } = yield* send(

‎apps/server/src/mcp/toolkits/orchestrator/tools.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -154,7 +154,11 @@ const BackgroundWaitTool = Tool.make("t3_background_wait", {
154154
failure: OrchestratorMcpFailure,
155155
failureMode: "return",
156156
dependencies,
157-
}).annotate(Tool.Title, "Wait on background work");
157+
})
158+
.annotate(Tool.Title, "Wait on background work")
159+
// Only marks which tasks keep the thread Working; Claude Plan mode blocks tools without this.
160+
.annotate(Tool.Readonly, true)
161+
.annotate(Tool.Destructive, false);
158162

159163
const ScheduleTaskTool = Tool.make("schedule_task", {
160164
description:

0 commit comments

Comments
 (0)