Skip to content

Commit fc6d15d

Browse files
MarcoDotIOclaude
andcommitted
Merge main into fix/terminal-server
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2 parents b21f9bb + b35819c commit fc6d15d

173 files changed

Lines changed: 7306 additions & 1223 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/DesktopLinuxUrlHandler.test.ts‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -204,6 +204,35 @@ describe("DesktopLinuxUrlHandler", () => {
204204
assert.include(entry, "Icon=/home/al ice/icons/T3\\\\x.png");
205205
});
206206

207+
it.each([
208+
{ from: "T3-Code-0.1.8-x86_64.AppImage", to: "T3-Code-x86_64.AppImage", restored: true },
209+
{
210+
from: "T3-Code-0.1.9-nightly.20261110.4449-arm64.AppImage",
211+
to: "T3-Code-Nightly-arm64.AppImage",
212+
restored: true,
213+
},
214+
{ from: "T3-Code-0.1.8-x86_64.AppImage", to: "T3-Code-0.1.9-x86_64.AppImage", restored: false },
215+
{ from: "t3code.AppImage", to: "T3-Code-x86_64.AppImage", restored: false },
216+
{ from: "T3-Code-x86_64.AppImage", to: "T3-Code-x86_64.AppImage", restored: false },
217+
{ from: "../T3-Code-0.1.8-x86_64.AppImage", to: "T3-Code-x86_64.AppImage", restored: false },
218+
])("finds the launch path an update from $from to $to removed", ({ from, to, restored }) => {
219+
for (const dir of ["/home/alice/Applications", '/home/al ice/My "100%" $Apps\\x']) {
220+
const previous = dir + "/" + from;
221+
const previousEntry = DesktopLinuxUrlHandler.renderUrlHandlerDesktopEntry({
222+
displayName: "T3 Code (Beta)",
223+
execTarget: previous,
224+
scheme: "t3code",
225+
});
226+
assert.equal(
227+
DesktopLinuxUrlHandler.replacedVersionedAppImagePath({
228+
previousEntry,
229+
appImagePath: dir + "/" + to,
230+
}),
231+
restored ? previous : null,
232+
);
233+
}
234+
});
235+
207236
it.effect(
208237
"writes the handler entry, refreshes the MIME cache, and claims the scheme default",
209238
() => {

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

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,38 @@ export function renderUrlHandlerDesktopEntry(input: {
9696
].join("\n");
9797
}
9898

99+
function parseUrlHandlerExecTarget(entry: string): string | null {
100+
const exec = /^Exec=(.*) %U$/mu.exec(entry)?.[1];
101+
if (exec === undefined) return null;
102+
const unescaped = exec.replace(/\\([\\nrt])/gu, (_, char: string) =>
103+
char === "n" ? "\n" : char === "r" ? "\r" : char === "t" ? "\t" : char,
104+
);
105+
const quoted = /^"(.*)"$/su.exec(unescaped)?.[1];
106+
return (
107+
quoted === undefined ? unescaped : quoted.replace(/\\([\\`$"])/gu, (_, char: string) => char)
108+
).replaceAll("%%", "%");
109+
}
110+
111+
const APPIMAGE_NAME_VERSION = /\d+\.\d+\.\d+/u;
112+
113+
// An updater from before version-free AppImage names deletes its own file and installs the update
114+
// beside it under the new name. The previous launch's entry still names the path launchers use.
115+
export function replacedVersionedAppImagePath(input: {
116+
readonly previousEntry: string;
117+
readonly appImagePath: string;
118+
}): string | null {
119+
const previous = parseUrlHandlerExecTarget(input.previousEntry);
120+
if (previous === null) return null;
121+
const previousName = previous.slice(previous.lastIndexOf("/") + 1);
122+
const currentName = input.appImagePath.slice(input.appImagePath.lastIndexOf("/") + 1);
123+
return previous.startsWith("/") &&
124+
previous.slice(0, -previousName.length) === input.appImagePath.slice(0, -currentName.length) &&
125+
APPIMAGE_NAME_VERSION.test(previousName) &&
126+
!APPIMAGE_NAME_VERSION.test(currentName)
127+
? previous
128+
: null;
129+
}
130+
99131
// Docks may look up the Wayland app id without a desktop entry; icon theme lookups are case-sensitive.
100132
const LINUX_THEME_ICON_SIZE = "256x256";
101133

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

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ const {
1616
copyFileSyncMock,
1717
execFileSyncMock,
1818
readFileSyncMock,
19+
symlinkSyncMock,
1920
} = vi.hoisted(() => ({
2021
appendSwitchMock: vi.fn(),
2122
getSwitchValueMock: vi.fn(),
@@ -27,6 +28,7 @@ const {
2728
copyFileSyncMock: vi.fn(),
2829
execFileSyncMock: vi.fn(),
2930
readFileSyncMock: vi.fn(),
31+
symlinkSyncMock: vi.fn(),
3032
}));
3133

3234
vi.mock("electron", () => ({
@@ -51,6 +53,7 @@ vi.mock("node:fs", () => ({
5153
mkdirSync: mkdirSyncMock,
5254
writeFileSync: writeFileSyncMock,
5355
copyFileSync: copyFileSyncMock,
56+
symlinkSync: symlinkSyncMock,
5457
}));
5558

5659
vi.mock("node:child_process", () => ({
@@ -72,6 +75,7 @@ describe("DesktopPreReadyPlatform", () => {
7275
copyFileSyncMock.mockReset();
7376
execFileSyncMock.mockReset();
7477
readFileSyncMock.mockReset().mockReturnValue("{}");
78+
symlinkSyncMock.mockReset();
7579
});
7680

7781
it.effect("persists Linux scaling synchronously across relaunches and settings rewrites", () => {
@@ -181,6 +185,47 @@ describe("DesktopPreReadyPlatform", () => {
181185
).pipe(Effect.ensuring(Effect.sync(() => vi.unstubAllEnvs())));
182186
});
183187

188+
it.effect.each([
189+
{ relaunchedByUpdater: "true", restored: true },
190+
{ relaunchedByUpdater: "", restored: false },
191+
])(
192+
"restores the versioned AppImage path an update removed (updater relaunch: $relaunchedByUpdater)",
193+
({ relaunchedByUpdater, restored }) => {
194+
vi.stubEnv("VITE_DEV_SERVER_URL", "");
195+
getSwitchValueMock.mockReturnValue("");
196+
const entryPath = "/xdg/applications/com.t3tools.T3Code.desktop";
197+
const files = new Map([[entryPath, "Exec=/Applications/T3-Code-0.1.8-x86_64.AppImage %U\n"]]);
198+
readFileSyncMock.mockImplementation((path: string) => files.get(path) ?? "{}");
199+
writeFileSyncMock.mockImplementation((path: string, contents: string | Buffer) => {
200+
files.set(path, String(contents));
201+
});
202+
203+
return Effect.scoped(
204+
Effect.gen(function* () {
205+
yield* Layer.build(
206+
DesktopPreReadyPlatform.layer.pipe(
207+
Layer.provide(Layer.succeed(HostProcess.Platform, "linux")),
208+
Layer.provide(
209+
DesktopConfig.layerTest({
210+
XDG_DATA_HOME: "/xdg",
211+
APPIMAGE: "/Applications/T3-Code-x86_64.AppImage",
212+
APPIMAGE_SILENT_INSTALL: relaunchedByUpdater,
213+
}),
214+
),
215+
),
216+
);
217+
assert.deepEqual(
218+
symlinkSyncMock.mock.calls,
219+
restored
220+
? [["T3-Code-x86_64.AppImage", "/Applications/T3-Code-0.1.8-x86_64.AppImage"]]
221+
: [],
222+
);
223+
assert.include(files.get(entryPath), "Exec=/Applications/T3-Code-x86_64.AppImage %U");
224+
}),
225+
).pipe(Effect.ensuring(Effect.sync(() => vi.unstubAllEnvs())));
226+
},
227+
);
228+
184229
it.effect("points the early portal entry at a configured distribution launcher", () => {
185230
vi.stubEnv("VITE_DEV_SERVER_URL", "");
186231
getSwitchValueMock.mockReturnValue("");

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

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,10 @@ import * as HostProcess from "@t3tools/shared/HostProcess";
1414
import * as DesktopEarlyElectronStartup from "./DesktopEarlyElectronStartup.ts";
1515
import { trimmedString } from "./DesktopConfig.ts";
1616
import { resolveDesktopAppBranding } from "./DesktopEnvironment.ts";
17-
import { renderUrlHandlerDesktopEntry } from "./DesktopLinuxUrlHandler.ts";
17+
import {
18+
renderUrlHandlerDesktopEntry,
19+
replacedVersionedAppImagePath,
20+
} from "./DesktopLinuxUrlHandler.ts";
1821
import * as ElectronProtocol from "../electron/ElectronProtocol.ts";
1922

2023
export interface DesktopPreReadyCommandLineReader {
@@ -56,6 +59,8 @@ const LinuxDesktopEntryConfig = Config.all({
5659
xdgDataHome: trimmedString("XDG_DATA_HOME"),
5760
launcherPath: trimmedString("T3CODE_DESKTOP_LAUNCHER_PATH"),
5861
appImagePath: trimmedString("APPIMAGE"),
62+
// electron-updater sets this on the AppImage it relaunches after installing an update.
63+
relaunchedByUpdater: trimmedString("APPIMAGE_SILENT_INSTALL"),
5964
});
6065

6166
/** @public */
@@ -116,8 +121,26 @@ export const make = Effect.gen(function* () {
116121
);
117122
} catch {}
118123
}
124+
const desktopEntryPath = NodePath.posix.join(applicationsDir, linux.linuxDesktopEntryName);
125+
const { appImagePath } = linuxDesktopEntryConfig;
126+
if (
127+
Option.isSome(appImagePath) &&
128+
Option.isNone(linuxDesktopEntryConfig.launcherPath) &&
129+
Option.contains(linuxDesktopEntryConfig.relaunchedByUpdater, "true")
130+
) {
131+
try {
132+
const replacedPath = replacedVersionedAppImagePath({
133+
previousEntry: NodeFS.readFileSync(desktopEntryPath, "utf8"),
134+
appImagePath: appImagePath.value,
135+
});
136+
// Relative, so the pair survives a moved folder; symlink never overwrites a file.
137+
if (replacedPath !== null) {
138+
NodeFS.symlinkSync(NodePath.posix.basename(appImagePath.value), replacedPath);
139+
}
140+
} catch {}
141+
}
119142
NodeFS.writeFileSync(
120-
NodePath.posix.join(applicationsDir, linux.linuxDesktopEntryName),
143+
desktopEntryPath,
121144
renderUrlHandlerDesktopEntry({
122145
displayName: resolveDesktopAppBranding({
123146
isDevelopment: linux.isDevelopment,

‎apps/desktop/src/main.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,9 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
1212
// @effect-diagnostics-next-line nodeBuiltinImport:off - Version output must flush before Electron exits, without acquiring the runtime.
1313
import * as NodeFS from "node:fs";
1414
import * as NodeOS from "node:os";
15+
import * as SecureRandom from "effect/crypto/SecureRandom";
1516
import * as Effect from "effect/Effect";
17+
import * as FileSystem from "effect/FileSystem";
1618
import * as Layer from "effect/Layer";
1719
import * as Option from "effect/Option";
1820

@@ -125,6 +127,15 @@ const layerDesktopSshEnvironment = Layer.unwrap(
125127
const environment = yield* DesktopEnvironment.DesktopEnvironment;
126128
return DesktopSshEnvironment.layer({
127129
resolveCliRunner: Effect.succeed(resolveDesktopSshCliRunner(environment)),
130+
resolveLauncherId: yield* Effect.cached(
131+
DesktopSshEnvironment.readOrCreateLauncherId(
132+
environment.path.join(environment.stateDir, "ssh-launcher-id"),
133+
).pipe(
134+
Effect.provide(
135+
yield* Effect.context<FileSystem.FileSystem | SecureRandom.SecureRandom>(),
136+
),
137+
),
138+
),
128139
});
129140
}),
130141
);

‎apps/desktop/src/preview/DesktopBrowserHost.test.ts‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1298,6 +1298,41 @@ describe("DesktopBrowserHost", () => {
12981298
}),
12991299
);
13001300

1301+
it.effect("stops crediting the agent once a person acts through a viewer", () =>
1302+
Effect.gen(function* () {
1303+
const host = yield* DesktopBrowserHost.make;
1304+
const debuggee = makeDebuggee();
1305+
host.attach(key, debuggee.tab);
1306+
const replies = yield* watchReplies(host);
1307+
const raw = (message: Record<string, unknown>) =>
1308+
host.handleCommandLine(encodeJson({ type: "cdp", ...key, message: encodeJson(message) }));
1309+
const viewer = (id: number, method: string, type: string) =>
1310+
raw({ id, method, params: { type }, sessionId: "t3-preview-page-1" });
1311+
const led = () => host.agentLedPage(debuggee.tab.webContents);
1312+
1313+
yield* command(host, 1, "DOM.getDocument");
1314+
expect(led()).toBe(false);
1315+
yield* raw({ id: 2, method: "Target.attachToTarget", params: { targetId: "GUEST" } });
1316+
expect(yield* Queue.take(replies)).toBe(2);
1317+
yield* raw({ id: 3, method: "Page.startScreencast", sessionId: "t3-preview-page-1" });
1318+
1319+
for (const [method, type] of [
1320+
["Input.dispatchKeyEvent", "rawKeyDown"],
1321+
["Input.dispatchMouseEvent", "mousePressed"],
1322+
["Input.dispatchTouchEvent", "touchStart"],
1323+
] as const) {
1324+
yield* command(host, 4, "Runtime.evaluate");
1325+
expect(led()).toBe(true);
1326+
// The viewer's pointer only passes over the page the agent drives.
1327+
yield* viewer(5, "Input.dispatchMouseEvent", "mouseMoved");
1328+
yield* viewer(6, "Input.dispatchMouseEvent", "mouseWheel");
1329+
expect(led()).toBe(true);
1330+
yield* viewer(7, method, type);
1331+
expect(led()).toBe(false);
1332+
}
1333+
}).pipe(Effect.scoped),
1334+
);
1335+
13011336
it.effect("detaches only the tab whose CDP event is too large to relay", () =>
13021337
Effect.gen(function* () {
13031338
const host = yield* DesktopBrowserHost.make;

‎apps/desktop/src/preview/DesktopBrowserHost.ts‎

Lines changed: 22 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,9 @@ const AGENT_INPUT_COMMAND =
2626
/"method":"(?:Input\.|Page\.navigate"|Runtime\.(?:evaluate|callFunctionOn)")/;
2727
/** The same commands as above, by method, for the relay's sends. */
2828
const AGENT_INPUT_METHOD = /^(?:Input\.|Page\.navigate$|Runtime\.(?:evaluate|callFunctionOn)$)/;
29-
const AGENT_DOWNLOAD_WINDOW_MS = 5_000;
29+
const AGENT_INPUT_WINDOW_MS = 5_000;
30+
/** A viewer's pointer travelling over the stream activates nothing on the page. */
31+
const POINTER_TRAVEL = new Set<unknown>(["mouseMoved", "mouseWheel"]);
3032
const FOCUS_IDLE = "5 seconds";
3133
/** Well inside the server's 10 s DESKTOP_ATTACH_TIMEOUT, for a first page that never reports it is up. */
3234
const FIRST_PAGE_TIMEOUT = "5 seconds";
@@ -60,6 +62,8 @@ interface AttachedTab {
6062
downloadDirectory: string | null;
6163
pendingDownloadGuid: string | null;
6264
agentInputAt: number;
65+
/** When the agent last drove the page with no person's input through a viewer since. */
66+
agentLedAt: number;
6367
focusEmulated: boolean;
6468
focusChange: Promise<void> | null;
6569
focusUses: number;
@@ -98,6 +102,8 @@ export class DesktopBrowserHost extends Context.Service<
98102
readonly loadFailed: (key: DesktopBrowserTabKey, failure: PreviewAutomationLoadError) => void;
99103
readonly setShown: (key: DesktopBrowserTabKey, shown: boolean | undefined) => void;
100104
readonly humanStartedDownload: (source: Electron.WebContents) => boolean;
105+
/** Whether what the page does now follows the agent's input, not a viewer's. */
106+
readonly agentLedPage: (source: Electron.WebContents) => boolean;
101107
readonly placeDownload: (source: Electron.WebContents, item: Electron.DownloadItem) => boolean;
102108
readonly pointers: Stream.Stream<{
103109
readonly key: DesktopBrowserTabKey;
@@ -351,11 +357,13 @@ export const make = Effect.gen(function* () {
351357
if (tab.screencasts.size > 0) return Promise.resolve({});
352358
}
353359
// A person's input through a viewer, or Playwright's own housekeeping, is not the agent's.
354-
if (
355-
AGENT_INPUT_METHOD.test(method) &&
356-
(owner === undefined || !streamingOwners.has(owner))
357-
) {
358-
tab.agentUsed = true;
360+
if (AGENT_INPUT_METHOD.test(method)) {
361+
if (owner === undefined || !streamingOwners.has(owner)) {
362+
tab.agentUsed = true;
363+
tab.agentLedAt = performance.now();
364+
} else if (method.startsWith("Input.") && !POINTER_TRAVEL.has(params["type"])) {
365+
tab.agentLedAt = Number.NEGATIVE_INFINITY;
366+
}
359367
}
360368
// Waits for focus emulation; insertText and other non-CDP input would not queue behind it.
361369
const forward = (current?: () => boolean) => {
@@ -490,6 +498,7 @@ export const make = Effect.gen(function* () {
490498
downloadDirectory: null,
491499
pendingDownloadGuid: null,
492500
agentInputAt: Number.NEGATIVE_INFINITY,
501+
agentLedAt: Number.NEGATIVE_INFINITY,
493502
focusEmulated: false,
494503
focusChange: null,
495504
focusUses: 0,
@@ -604,7 +613,12 @@ export const make = Effect.gen(function* () {
604613

605614
const humanStartedDownload = (source: Electron.WebContents) => {
606615
const tab = [...tabs.values()].find((candidate) => candidate.debuggee.webContents === source);
607-
return tab !== undefined && performance.now() - tab.agentInputAt > AGENT_DOWNLOAD_WINDOW_MS;
616+
return tab !== undefined && performance.now() - tab.agentInputAt > AGENT_INPUT_WINDOW_MS;
617+
};
618+
619+
const agentLedPage = (source: Electron.WebContents) => {
620+
const tab = [...tabs.values()].find((candidate) => candidate.debuggee.webContents === source);
621+
return tab !== undefined && performance.now() - tab.agentLedAt <= AGENT_INPUT_WINDOW_MS;
608622
};
609623

610624
const announceAll = Effect.suspend(() => {
@@ -647,6 +661,7 @@ export const make = Effect.gen(function* () {
647661
setShown,
648662
placeDownload,
649663
humanStartedDownload,
664+
agentLedPage,
650665
});
651666
});
652667

0 commit comments

Comments
 (0)