Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ dist-electron/
.electron-runtime/
.showcase/
apps/mobile/.showcase/
apps/mobile/.generated/
/.generated/
artifacts/app-store/screenshots/
.github/pr-assets/
native/**/target/
Expand All @@ -38,3 +40,6 @@ node_modules/
*.log
.env*
!.env.example

# pnpm content-addressable store; never belongs in the repo.
.pnpm-store/
Binary file added .pnpm-store/v11/index.db
Binary file not shown.
1 change: 1 addition & 0 deletions apps/desktop/src/electron/ElectronProtocol.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -226,6 +226,7 @@ describe("ElectronProtocol", () => {
"https:",
]);
assert.deepEqual(directives["media-src"], ["'self'", "t3code:", "blob:", "http:", "https:"]);
assert.deepEqual(directives["frame-src"], ["'self'", "blob:", "http:", "https:"]);
assert.deepEqual(directives["font-src"], ["'self'", "t3code:", "data:"]);
});
});
4 changes: 3 additions & 1 deletion apps/desktop/src/electron/ElectronProtocol.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,9 @@ export function makeDesktopContentSecurityPolicy(input: DesktopProtocolRegistrat
"style-src 'self' 'unsafe-inline'",
`font-src 'self' ${input.scheme}: data:`,
"worker-src 'self' blob:",
"frame-src 'self' https://challenges.cloudflare.com",
// Document viewers use local Blob URLs and signed assets from runtime environments.
// HTML viewers retain their own sandbox; the renderer's script policy stays unchanged.
"frame-src 'self' blob: http: https:",
"form-action 'self'",
].join("; ");
}
Expand Down
248 changes: 174 additions & 74 deletions apps/desktop/src/preview/Manager.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import * as NodeVM from "node:vm";
import { it as effectIt } from "@effect/vitest";
import { DESKTOP_PREVIEW_RECORDING_CAPTURE_TRIGGER } from "@t3tools/contracts";
import type { DesktopPreviewRecordingFrame } from "@t3tools/contracts";
Expand Down Expand Up @@ -3925,29 +3926,92 @@ describe("PreviewManager", () => {
withManager((manager) =>
Effect.gen(function* () {
let failKeyDown = false;
let routeToIframe = false;
let interruptFrameKeyDown = false;
let holdKeyUp = false;
let releaseKeyUp: (() => void) | undefined;
let notifyKeyUpQueued: (() => void) | undefined;
const keyUpQueued = new Promise<void>((resolve) => {
notifyKeyUpQueued = resolve;
});
const listeners = new Map<string, (event: unknown) => void>();
const eventCounts = new Map<string, number>();
const animationFrames = new Map<number, () => void>();
let animationFrameId = 0;
const renderFrame = () => {
const callbacks = [...animationFrames.values()];
animationFrames.clear();
callbacks.forEach((callback) => callback());
};
const frameContext = NodeVM.createContext({
performance: { eventCounts },
requestAnimationFrame: (callback: () => void) => {
const id = ++animationFrameId;
animationFrames.set(id, callback);
return id;
},
cancelAnimationFrame: (id: number) => animationFrames.delete(id),
window: {
addEventListener: (type: string, listener: (event: unknown) => void) =>
listeners.set(type, listener),
removeEventListener: (type: string) => listeners.delete(type),
},
});
const frame = {
executeJavaScript: vi.fn(async (expression: string) =>
NodeVM.runInContext(expression, frameContext),
),
};
let humanInput: ((_event: unknown, signal: unknown) => void) | undefined;
const sendCommand = vi.fn(async (method: string, params?: Record<string, unknown>) => {
if (
failKeyDown &&
method === "Input.dispatchKeyEvent" &&
(params?.["type"] === "keyDown" || params?.["type"] === "rawKeyDown")
) {
throw new Error("key dispatch failed");
}
if (
method === "Input.dispatchKeyEvent" &&
(params?.["type"] === "keyDown" || params?.["type"] === "rawKeyDown")
) {
humanInput?.(
{},
{
kind: "key",
key: params["key"],
code: params["code"] ?? "Digit1",
},
);
const sendCommand = vi.fn(
async (method: string, params?: Record<string, unknown>, sessionId?: string) => {
if (method === "Runtime.evaluate") {
if (params?.["returnByValue"] === true) return { result: { value: { ok: true } } };
return {
result:
routeToIframe && !sessionId
? { objectId: "focused-iframe-object" }
: { subtype: "null" },
};
}
if (method === "DOM.describeNode") return { node: { frameId: "focused-frame" } };
if (method === "Target.getTargets")
return {
targetInfos: [
{ targetId: "unrelated-frame", type: "iframe" },
{ targetId: "focused-frame", type: "iframe" },
],
};
if (method === "Target.attachToTarget") return { sessionId: "child-session" };
if (method === "Input.dispatchKeyEvent" && params?.["type"] !== "keyUp") {
if (failKeyDown) throw new Error("key dispatch failed");
if (interruptFrameKeyDown)
humanInput?.({}, { kind: "pointer", x: 80, y: 40, button: 0 });
}
return undefined;
},
);
const sendInputEvent = vi.fn((input: Electron.KeyboardInputEvent) => {
const signal = {
kind: "key",
key: input.keyCode,
code: input.keyCode === "!" ? "Digit1" : `Key${input.keyCode.toUpperCase()}`,
};
if (input.type === "keyUp") {
const deliver = () => {
eventCounts.set("keyup", (eventCounts.get("keyup") ?? 0) + 1);
renderFrame();
};
if (holdKeyUp) {
releaseKeyUp = deliver;
notifyKeyUpQueued?.();
} else {
queueMicrotask(deliver);
}
}
return method === "Runtime.evaluate" ? { result: { value: { ok: true } } } : undefined;
if (input.type !== "keyDown") return;
if (failKeyDown) throw new Error("key dispatch failed");
humanInput?.({}, signal);
});
const restoreFocus = vi.fn();
const focus = vi.fn();
Expand All @@ -3958,13 +4022,15 @@ describe("PreviewManager", () => {
} as never);
fromId.mockReturnValue({
id: 42,
mainFrame: { framesInSubtree: [frame] },
isDestroyed: () => false,
getType: () => "webview",
getURL: () => "https://example.com",
getTitle: () => "Example",
isLoading: () => false,
isDevToolsOpened: () => false,
focus,
sendInputEvent,
getZoomFactor: () => 1,
setZoomFactor: vi.fn(),
setAudioMuted: vi.fn(),
Expand Down Expand Up @@ -4003,13 +4069,6 @@ describe("PreviewManager", () => {
([method, params]) =>
method === "Emulation.setFocusEmulationEnabled" && params?.["enabled"] === true,
);
const keyDownIndex = calls.findIndex(
([method, params]) =>
method === "Input.dispatchKeyEvent" && params?.["type"] === "keyDown",
);
const keyUpIndex = calls.findIndex(
([method, params]) => method === "Input.dispatchKeyEvent" && params?.["type"] === "keyUp",
);
const focusOffIndex = calls.findIndex(
([method, params]) =>
method === "Emulation.setFocusEmulationEnabled" && params?.["enabled"] === false,
Expand Down Expand Up @@ -4037,61 +4096,102 @@ describe("PreviewManager", () => {
expect(clearOnlyEvaluation).toBeDefined();
expect(methods).not.toContain("Input.insertText");
expect(enableIndex).toBeGreaterThanOrEqual(0);
expect(focus).toHaveBeenCalledOnce();
expect(restoreFocus).toHaveBeenCalledOnce();
expect(methods).toContain("Page.bringToFront");
expect(methods).not.toContain("Page.bringToFront");
expect(methods).not.toContain("Input.dispatchKeyEvent");
expect(enableIndex).toBeLessThan(focusOnIndex);
expect(focusOnIndex).toBeLessThan(keyDownIndex);
expect(keyDownIndex).toBeLessThan(keyUpIndex);
expect(keyUpIndex).toBeLessThan(focusOffIndex);
expect(
calls.filter(
([method, params]) =>
method === "Input.dispatchKeyEvent" && params?.["type"] === "keyUp",
),
).toHaveLength(1);
expect(sendCommand.mock.invocationCallOrder[focusOnIndex]).toBeLessThan(
sendInputEvent.mock.invocationCallOrder[0]!,
);
expect(sendInputEvent.mock.invocationCallOrder[2]).toBeLessThan(
sendCommand.mock.invocationCallOrder[focusOffIndex]!,
);
expect(sendInputEvent.mock.calls.map(([input]) => input.type)).toEqual([
"keyDown",
"char",
"keyUp",
]);
expect(sendCommand).toHaveBeenCalledWith("Input.setIgnoreInputEvents", { ignore: false });
expect(listeners.size).toBe(0);
expect(animationFrames.size).toBe(0);

sendCommand.mockClear();
failKeyDown = true;
const failedPress = yield* Effect.exit(manager.automationPress("tab_input", { key: "y" }));

expect(Exit.isFailure(failedPress)).toBe(true);
expect(sendCommand).toHaveBeenCalledWith("Input.dispatchKeyEvent", {
type: "keyUp",
key: "y",
code: "KeyY",
modifiers: 0,
windowsVirtualKeyCode: 89,
location: 0,
isKeypad: false,
sendInputEvent.mockClear();
getFocusedWebContents.mockReturnValue(null);
holdKeyUp = true;
const backgroundPress = yield* manager
.automationPress("tab_input", { key: "x" })
.pipe(Effect.forkChild({ startImmediately: true }));
yield* Effect.promise(() => keyUpQueued);
expect(sendCommand).not.toHaveBeenCalledWith("Emulation.setFocusEmulationEnabled", {
enabled: false,
});
renderFrame();
expect(animationFrames.size).toBe(1);
releaseKeyUp?.();
yield* Fiber.join(backgroundPress);
expect(listeners.size).toBe(0);
expect(animationFrames.size).toBe(0);
expect(sendCommand).toHaveBeenCalledWith("Emulation.setFocusEmulationEnabled", {
enabled: false,
});
expect(restoreFocus).toHaveBeenCalledTimes(2);
expect(
sendCommand.mock.calls.filter(
([method, params]) =>
method === "Input.dispatchKeyEvent" && params?.["type"] === "keyUp",
),
).toHaveLength(1);
holdKeyUp = false;

// Both native failures and expected-input matching must leave focus emulation off.
for (const key of ["y", "!"]) {
sendCommand.mockClear();
sendInputEvent.mockClear();
failKeyDown = key === "y";
const exit = yield* Effect.exit(manager.automationPress("tab_input", { key }));
expect(Exit.isFailure(exit)).toBe(failKeyDown);
expect(sendInputEvent.mock.calls.map(([input]) => input.type)).toEqual(
failKeyDown ? ["keyDown", "keyUp"] : ["keyDown", "char", "keyUp"],
);
expect(sendCommand).toHaveBeenCalledWith("Emulation.setFocusEmulationEnabled", {
enabled: false,
});
}

sendCommand.mockClear();
failKeyDown = false;
yield* manager.automationPress("tab_input", { key: "!" });
expect(sendCommand).toHaveBeenCalledWith("Input.dispatchKeyEvent", {
type: "keyDown",
key: "!",
code: "Digit1",
modifiers: 0,
windowsVirtualKeyCode: 49,
location: 0,
isKeypad: false,
text: "!",
unmodifiedText: "!",
});
expect(restoreFocus).toHaveBeenCalledTimes(3);
routeToIframe = true;
sendInputEvent.mockClear();
for (const outcome of ["success", "failure", "interrupted"]) {
sendCommand.mockClear();
failKeyDown = outcome === "failure";
interruptFrameKeyDown = outcome === "interrupted";
const exit = yield* Effect.exit(
manager.automationPress("tab_input", {
key: outcome === "success" ? "Enter" : "x",
}),
);
expect(Exit.isSuccess(exit)).toBe(outcome === "success");
if (outcome === "interrupted" && Exit.isFailure(exit)) {
expect(Option.getOrThrow(Cause.findErrorOption(exit.cause))).toMatchObject({
_tag: "PreviewAutomationControlInterruptedError",
});
}
expect(sendInputEvent).not.toHaveBeenCalled();
expect(sendCommand).toHaveBeenCalledWith("Target.attachToTarget", {
targetId: "focused-frame",
flatten: true,
});
expect(
sendCommand.mock.calls
.filter(([method]) => method === "Input.dispatchKeyEvent")
.map(([, params, sessionId]) => ({ type: params?.["type"], sessionId })),
).toEqual([
{ type: "keyDown", sessionId: "child-session" },
{ type: "keyUp", sessionId: "child-session" },
]);
expect(sendCommand).toHaveBeenCalledWith(
"Emulation.setFocusEmulationEnabled",
{ enabled: false },
"child-session",
);
expect(sendCommand).toHaveBeenCalledWith("Target.detachFromTarget", {
sessionId: "child-session",
});
}
expect(focus).not.toHaveBeenCalled();
expect(restoreFocus).not.toHaveBeenCalled();
}),
),
);
Expand Down
Loading
Loading