diff --git a/.github/scripts/pr-limits.cjs b/.github/scripts/pr-limits.cjs index 77c09785e4104..f3eb528a08042 100644 --- a/.github/scripts/pr-limits.cjs +++ b/.github/scripts/pr-limits.cjs @@ -100,14 +100,22 @@ function parseExemptions(text) { } // VOUCHED.td: one `github:login` per line, `#` comments, and `-github:login reason` to denounce. -function vouchedLogins(text) { - const logins = new Set(); +// A login listed both ways is an error: pr-vouch.yml's action reads its first line and +// issue-vouch.yml its last, so no answer here would agree with both labels. +function parseVouchList(text) { + const vouched = new Set(); + const denounced = new Set(); for (const raw of text.split("\n")) { - const entry = raw.trim().split(/\s+/)[0]; - if (entry.startsWith("github:")) logins.add(entry.slice("github:".length).toLowerCase()); + const match = /^(-?)github:(\S+)/.exec(raw.trim()); + if (!match) continue; + const login = match[2].toLowerCase(); + const [listed, other] = match[1] ? [denounced, vouched] : [vouched, denounced]; + if (other.has(login)) + throw new Error(`${VOUCHED_PATH}: ${login} is both vouched and denounced`); + listed.add(login); } - if (logins.size === 0) throw new Error(`${VOUCHED_PATH}: no entries`); - return logins; + if (vouched.size === 0) throw new Error(`${VOUCHED_PATH}: no entries`); + return { vouched, denounced }; } function labeledAt(pr, name) { @@ -278,7 +286,8 @@ async function enforceOpenLimit({ github, context, core, dryRun }) { // lookups as "not vouched". Every read below throws on failure, and a throw closes nothing. if (pr.user.type === "Bot") return; if (parseExemptions(fs.readFileSync(EXEMPTIONS_PATH, "utf8")).has(author.toLowerCase())) return; - if (vouchedLogins(fs.readFileSync(VOUCHED_PATH, "utf8")).has(author.toLowerCase())) return; + const { vouched, denounced } = parseVouchList(fs.readFileSync(VOUCHED_PATH, "utf8")); + if (vouched.has(author.toLowerCase())) return; const { data: access } = await github.rest.repos.getCollaboratorPermissionLevel({ ...context.repo, username: author, @@ -289,6 +298,21 @@ async function enforceOpenLimit({ github, context, core, dryRun }) { const reopened = context.payload.action === "reopened"; if (reopened && context.payload.sender.login.toLowerCase() !== author.toLowerCase()) return; + if (denounced.has(author.toLowerCase())) { + if (dryRun) { + core.notice(`Dry run. PR #${pr.number} would close: ${author} is denounced.`); + return; + } + await closeWithComment( + github, + context, + pr.number, + `Closing: ${author} is banned from contributing here, so this PR will not be reviewed. See [bans](${guideLink(context, "bans")}).`, + ); + core.info(`PR #${pr.number}: closed, ${author} is denounced.`); + return; + } + const q = `repo:${context.repo.owner}/${context.repo.repo} is:pr is:open author:${author} sort:created-asc`; const { search } = await read(github, AUTHOR_OPEN_PRS_QUERY, { q }); // A new PR counts only the older ones, so two opened together cannot close each other. diff --git a/.github/workflows/issue-vouch.yml b/.github/workflows/issue-vouch.yml index bbb6e95c9ec60..d65882593c649 100644 --- a/.github/workflows/issue-vouch.yml +++ b/.github/workflows/issue-vouch.yml @@ -40,9 +40,14 @@ jobs: ref: context.payload.repository.default_branch, }); const statusByUser = new Map(); + const listedBothWays = new Set(); for (const raw of Buffer.from(file.content, "base64").toString("utf8").split("\n")) { const match = /^(-?)github:(\S+)/.exec(raw.trim()); - if (match) statusByUser.set(match[2].toLowerCase(), match[1] ? "denounced" : "vouched"); + if (!match) continue; + const login = match[2].toLowerCase(); + const status = match[1] ? "denounced" : "vouched"; + if (statusByUser.has(login) && statusByUser.get(login) !== status) listedBothWays.add(login); + statusByUser.set(login, status); } const issues = @@ -74,4 +79,32 @@ jobs: await github.rest.issues.addLabels({ owner, repo, issue_number: issue.number, labels: [next] }); core.info(`Issue #${issue.number} (${issue.user.login}): ${status} -> ${next}`); } + + // Only a newly opened issue is closed. One filed before its author was denounced + // may already have a fix on the way, so the sweep leaves those to maintainers. + // Someone else reopening it is a maintainer keeping it open. + const reopenedByOther = + context.payload.action === "reopened" && + context.payload.sender.login.toLowerCase() !== issue.user.login.toLowerCase(); + // The PR rules refuse a list that names a login both ways, so nothing closes for one here. + const trusted = + issue.user.type === "Bot" || + ["OWNER", "MEMBER", "COLLABORATOR"].includes(issue.author_association) || + listedBothWays.has(issue.user.login.toLowerCase()); + if (status === "denounced" && context.eventName === "issues" && !reopenedByOther && !trusted) { + await github.rest.issues.createComment({ + owner, + repo, + issue_number: issue.number, + body: `Closing: ${issue.user.login} is banned from contributing here, so this issue will not be triaged. See [bans](https://github.com/${owner}/${repo}/blob/main/CONTRIBUTING.md#bans).`, + }); + await github.rest.issues.update({ + owner, + repo, + issue_number: issue.number, + state: "closed", + state_reason: "not_planned", + }); + core.info(`Issue #${issue.number}: closed, ${issue.user.login} is denounced.`); + } } diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 63e71dc1e250c..0c886bd493389 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -115,6 +115,9 @@ the open PR limit. - If you make our lives harder as reviewers and maintainers, you will be banned. Examples are repeated pings, a fight over a closure, and a second account to get around a limit. +A banned account is denounced in [.github/VOUCHED.td](.github/VOUCHED.td). Any issue or PR it opens +is closed when it is opened. + ## When your PR is closed diff --git a/apps/desktop/src/app/DesktopStartupRecovery.ts b/apps/desktop/src/app/DesktopStartupRecovery.ts index c8228183aad91..e6c210043cf26 100644 --- a/apps/desktop/src/app/DesktopStartupRecovery.ts +++ b/apps/desktop/src/app/DesktopStartupRecovery.ts @@ -217,7 +217,6 @@ export const listen: Effect.Effect< const download = yield* updates.download; if (!download.completed) return; } - // Waits for a running background check; plain install would refuse. yield* updates.installPrepared(current.version); return; } diff --git a/apps/desktop/src/ipc/channels.ts b/apps/desktop/src/ipc/channels.ts index b7bb5e579572f..dd4ace3d3161d 100644 --- a/apps/desktop/src/ipc/channels.ts +++ b/apps/desktop/src/ipc/channels.ts @@ -98,9 +98,11 @@ export const PREVIEW_SET_ZOOM_FACTOR_CHANNEL = "desktop:preview-set-zoom-factor" export const PREVIEW_HARD_RELOAD_CHANNEL = "desktop:preview-hard-reload"; export const PREVIEW_SET_COLOR_SCHEME_CHANNEL = "desktop:preview-set-color-scheme"; export const PREVIEW_SET_AUDIO_MUTED_CHANNEL = "desktop:preview-set-audio-muted"; +export const PREVIEW_ANSWER_DIALOG_CHANNEL = "desktop:preview-answer-dialog"; export const PREVIEW_FIND_IN_PAGE_CHANNEL = "desktop:preview-find-in-page"; export const PREVIEW_STOP_FIND_IN_PAGE_CHANNEL = "desktop:preview-stop-find-in-page"; export const PREVIEW_SET_SHOWN_CHANNEL = "desktop:preview-set-shown"; +export const PREVIEW_SET_CAPTURE_DRAWN_CHANNEL = "desktop:preview-set-capture-drawn"; export const PREVIEW_OPEN_DEVTOOLS_CHANNEL = "desktop:preview-open-devtools"; export const PREVIEW_CLEAR_COOKIES_CHANNEL = "desktop:preview-clear-cookies"; export const PREVIEW_CLEAR_CACHE_CHANNEL = "desktop:preview-clear-cache"; diff --git a/apps/desktop/src/ipc/methods/preview.ts b/apps/desktop/src/ipc/methods/preview.ts index cc810fee072ad..bbba5a454ff7a 100644 --- a/apps/desktop/src/ipc/methods/preview.ts +++ b/apps/desktop/src/ipc/methods/preview.ts @@ -11,8 +11,10 @@ import { DesktopPreviewRecordingSaveInputSchema, DesktopPreviewRegisterWebviewInputSchema, DesktopPreviewScreenshotArtifactSchema, + DesktopPreviewAnswerDialogInputSchema, DesktopPreviewSetAudioMutedInputSchema, DesktopPreviewSetShownInputSchema, + DesktopPreviewSetCaptureDrawnInputSchema, DesktopPreviewSetColorSchemeInputSchema, DesktopPreviewSetZoomFactorInputSchema, BrowserImportResult, @@ -225,6 +227,15 @@ const setAudioMuted = DesktopIpc.makeIpcMethod({ yield* manager.setAudioMuted(tabId, audioMuted); }), }); +const answerDialog = DesktopIpc.makeIpcMethod({ + channel: IpcChannels.PREVIEW_ANSWER_DIALOG_CHANNEL, + payload: DesktopPreviewAnswerDialogInputSchema, + result: Schema.Void, + handler: Effect.fn("desktop.ipc.preview.answerDialog")(function* ({ tabId, accept, promptText }) { + const manager = yield* PreviewManager.PreviewManager; + yield* manager.answerDialog(tabId, accept, promptText); + }), +}); const setShown = DesktopIpc.makeIpcMethod({ channel: IpcChannels.PREVIEW_SET_SHOWN_CHANNEL, payload: DesktopPreviewSetShownInputSchema, @@ -234,6 +245,15 @@ const setShown = DesktopIpc.makeIpcMethod({ yield* manager.setShown(tabId, shown); }), }); +const setCaptureDrawn = DesktopIpc.makeIpcMethod({ + channel: IpcChannels.PREVIEW_SET_CAPTURE_DRAWN_CHANNEL, + payload: DesktopPreviewSetCaptureDrawnInputSchema, + result: Schema.Void, + handler: Effect.fn("desktop.ipc.preview.setCaptureDrawn")(function* ({ tabId, drawn }) { + const manager = yield* PreviewManager.PreviewManager; + yield* manager.setCaptureDrawn(tabId, drawn); + }), +}); const openDevTools = tabMethod( IpcChannels.PREVIEW_OPEN_DEVTOOLS_CHANNEL, "desktop.ipc.preview.openDevTools", @@ -487,7 +507,9 @@ export const methods = [ setColorScheme, setZoomFactor, setAudioMuted, + answerDialog, setShown, + setCaptureDrawn, openDevTools, clearCookies, clearCache, diff --git a/apps/desktop/src/ipc/methods/window.test.ts b/apps/desktop/src/ipc/methods/window.test.ts index fbeda6d2f2dcd..de202529c4113 100644 --- a/apps/desktop/src/ipc/methods/window.test.ts +++ b/apps/desktop/src/ipc/methods/window.test.ts @@ -1,6 +1,8 @@ import { assert, describe, it } from "@effect/vitest"; import * as NodeServices from "@effect/platform-node/NodeServices"; import type { ManagedPolicyLimits } from "@t3tools/contracts"; +import { EDITORS, REMOTE_CAPABLE_EDITOR_IDS } from "@t3tools/contracts"; +import { resolveEditorCommand } from "@t3tools/shared/editor"; import * as HostProcess from "@t3tools/shared/HostProcess"; import { ManagedPolicyFileError } from "@t3tools/shared/managedPolicyFile"; import * as FileSystem from "effect/FileSystem"; @@ -517,3 +519,108 @@ it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")( assert.include(editors, "webstorm"); }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); + +describe("probeRemoteEditors PATH scan", () => { + const platform = HostProcess.Platform.defaultValue(); + const launcherName = (command: string) => (platform === "win32" ? `${command}.cmd` : command); + + const makeFakePath = Effect.fnUntraced(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-probe-path-" }); + const dirs = ["a", "b", "c", "d"].map((name) => path.join(root, name)); + for (const dir of dirs) yield* fs.makeDirectory(dir, { recursive: true }); + // Launchers in different PATH directories, deliberately not in REMOTE_CAPABLE_EDITOR_IDS order. + for (const [dir, command] of [ + [dirs[2]!, "webstorm"], + [dirs[0]!, "cursor"], + [dirs[3]!, "code"], + [dirs[1]!, "zeditor"], + ] as const) { + const file = path.join(dir, launcherName(command)); + yield* fs.writeFileString(file, "#!/bin/sh\n"); + if (platform !== "win32") yield* fs.chmod(file, 0o755); + } + return { + root, + env: { + HOME: root, + USERPROFILE: root, + PATH: dirs.join(platform === "win32" ? ";" : ":"), + PATHEXT: ".COM;.EXE;.BAT;.CMD", + }, + }; + }); + + const countingFileSystem = (counter: { stat: number; reads: Map }) => + Layer.effect( + FileSystem.FileSystem, + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + return FileSystem.FileSystem.of({ + ...fs, + stat: (target) => { + counter.stat += 1; + return fs.stat(target); + }, + readDirectory: (target, options) => { + counter.reads.set(target, (counter.reads.get(target) ?? 0) + 1); + return fs.readDirectory(target, options); + }, + }); + }), + ).pipe(Layer.provideMerge(NodeServices.layer)); + + const serialReference = (env: Record) => + Effect.gen(function* () { + const available: Array = []; + for (const editorId of REMOTE_CAPABLE_EDITOR_IDS) { + const editor = EDITORS.find((candidate) => candidate.id === editorId); + if (editor && Option.isSome(yield* resolveEditorCommand(editor, env))) { + available.push(editorId); + } + } + return available; + }); + + it.effect("reads each PATH directory once instead of stat-ing every candidate per editor", () => + Effect.gen(function* () { + const { env: baseEnv } = yield* makeFakePath(); + const delimiter = platform === "win32" ? ";" : ":"; + const uncachedCounter = { stat: 0, reads: new Map() }; + const cachedCounter = { stat: 0, reads: new Map() }; + const uncachedEnv = { ...baseEnv, PATH: `${baseEnv.PATH}${delimiter}${baseEnv.HOME}x1` }; + const cachedEnv = { ...baseEnv, PATH: `${baseEnv.PATH}${delimiter}${baseEnv.HOME}x2` }; + const uncached = yield* serialReference(uncachedEnv).pipe( + Effect.provide(countingFileSystem(uncachedCounter)), + ); + const cached = yield* probeRemoteEditors + .handler(undefined) + .pipe( + Effect.provideService(HostProcess.Environment, cachedEnv), + Effect.provideService(HostProcess.Platform, platform), + Effect.provide(countingFileSystem(cachedCounter)), + ); + // The host can add editors from app folders the fixture can't redirect (e.g. /Applications). + const fixtureEditors = ["cursor", "vscode", "zed", "webstorm"]; + assert.deepStrictEqual( + uncached.filter((id) => fixtureEditors.includes(id)), + fixtureEditors, + ); + assert.deepStrictEqual(cached, uncached); + assert.isAbove(uncachedCounter.stat, 0); + // On every platform the probe lists each PATH directory at most once. Only PATH entries count: + // resolveEditorCommand also reads app folders such as /Applications on macOS. + const pathReads = cachedEnv.PATH.split(delimiter) + .filter((entry) => entry.length > 0) + .map((entry) => cachedCounter.reads.get(entry) ?? 0); + assert.isAbove(Math.max(...pathReads), 0); + assert.isAtMost(Math.max(...pathReads), 1); + // Without the listings, Windows stats every PATH entry x PATHEXT candidate for each editor; + // elsewhere there is no PATHEXT, so the stat count is about the same either way. + if (platform === "win32") { + assert.isBelow(cachedCounter.stat, uncachedCounter.stat / 2); + } + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); +}); diff --git a/apps/desktop/src/ipc/methods/window.ts b/apps/desktop/src/ipc/methods/window.ts index cee92e1ead38c..5bd23e68c2705 100644 --- a/apps/desktop/src/ipc/methods/window.ts +++ b/apps/desktop/src/ipc/methods/window.ts @@ -17,6 +17,7 @@ import { } from "@t3tools/contracts"; import { PROJECT_FAVICON_EXTENSIONS } from "@t3tools/shared/projectFavicon"; import { resolveEditorCommand } from "@t3tools/shared/editor"; +import { withPathDirectoryListings } from "@t3tools/shared/shell"; import * as HostProcess from "@t3tools/shared/HostProcess"; import { isRelayTracingEnabled } from "@t3tools/shared/otelEnvironment"; import * as FileSystem from "effect/FileSystem"; @@ -427,20 +428,26 @@ export const openSystemSettings = DesktopIpc.makeIpcMethod({ }), }); +const REMOTE_EDITOR_PROBE_CONCURRENCY = 8; + export const probeRemoteEditors = DesktopIpc.makeIpcMethod({ channel: IpcChannels.PROBE_REMOTE_EDITORS_CHANNEL, payload: Schema.Undefined, result: Schema.Array(EditorId), handler: Effect.fn("desktop.ipc.window.probeRemoteEditors")(function* () { - const available: Array = []; const env = yield* HostProcess.Environment; - for (const editorId of REMOTE_CAPABLE_EDITOR_IDS) { - const editor = EDITORS.find((editor) => editor.id === editorId); - if (editor && Option.isSome(yield* resolveEditorCommand(editor, env))) { - available.push(editorId); - } - } - return available; + // Shared listings stop each editor re-stating every PATH entry x PATHEXT candidate on Windows. + const resolved = yield* Effect.forEach( + REMOTE_CAPABLE_EDITOR_IDS, + (editorId) => { + const editor = EDITORS.find((editor) => editor.id === editorId); + return editor + ? resolveEditorCommand(editor, env).pipe(Effect.map(Option.isSome)) + : Effect.succeed(false); + }, + { concurrency: REMOTE_EDITOR_PROBE_CONCURRENCY }, + ).pipe(withPathDirectoryListings); + return REMOTE_CAPABLE_EDITOR_IDS.filter((_, index) => resolved[index]); }), }); diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.ts index e0ac5f2161051..69bd842188558 100644 --- a/apps/desktop/src/preload.ts +++ b/apps/desktop/src/preload.ts @@ -403,6 +403,12 @@ contextBridge.exposeInMainWorld("desktopBridge", { ipcRenderer.invoke(IpcChannels.PREVIEW_SET_COLOR_SCHEME_CHANNEL, { tabId, colorScheme }), setAudioMuted: (tabId, audioMuted) => ipcRenderer.invoke(IpcChannels.PREVIEW_SET_AUDIO_MUTED_CHANNEL, { tabId, audioMuted }), + answerDialog: (tabId, accept, promptText) => + ipcRenderer.invoke(IpcChannels.PREVIEW_ANSWER_DIALOG_CHANNEL, { + tabId, + accept, + ...(promptText === undefined ? {} : { promptText }), + }), findInPage: (tabId, text, { forward, newSession }) => ipcRenderer.invoke(IpcChannels.PREVIEW_FIND_IN_PAGE_CHANNEL, { tabId, @@ -414,6 +420,8 @@ contextBridge.exposeInMainWorld("desktopBridge", { ipcRenderer.invoke(IpcChannels.PREVIEW_STOP_FIND_IN_PAGE_CHANNEL, { tabId }), setShown: (tabId, shown) => ipcRenderer.invoke(IpcChannels.PREVIEW_SET_SHOWN_CHANNEL, { tabId, shown }), + setCaptureDrawn: (tabId, drawn) => + ipcRenderer.invoke(IpcChannels.PREVIEW_SET_CAPTURE_DRAWN_CHANNEL, { tabId, drawn }), openDevTools: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_OPEN_DEVTOOLS_CHANNEL, { tabId }), listBrowserImportSources: () => ipcRenderer.invoke(IpcChannels.PREVIEW_IMPORT_SOURCES_CHANNEL), diff --git a/apps/desktop/src/preview/DesktopBrowserHost.test.ts b/apps/desktop/src/preview/DesktopBrowserHost.test.ts index cf6c7736f81d3..8e96129293fc8 100644 --- a/apps/desktop/src/preview/DesktopBrowserHost.test.ts +++ b/apps/desktop/src/preview/DesktopBrowserHost.test.ts @@ -26,6 +26,11 @@ const decodeCdpMessage = Schema.decodeUnknownSync( ), ); const key = { threadId: "thread-1", tabId: "tab-1" }; + +/** A host whose client already draws `key` at full detail, so its screenshots go out at once. */ +const makeDrawnHost = Effect.tap(DesktopBrowserHost.make, (host) => + Effect.sync(() => host.setCaptureDrawn(key, true)), +); /** Sends a page command whose id the fake debugger records as it receives it. */ const command = ( host: DesktopBrowserHost.DesktopBrowserHost["Service"], @@ -172,7 +177,7 @@ const watchPainting = (host: DesktopBrowserHost.DesktopBrowserHost["Service"]) = describe("DesktopBrowserHost", () => { it.effect("announces tabs already attached to a backend that starts later", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; host.attach(key, makeDebuggee().tab); expect(yield* takeEvents(host, 1)).toEqual([{ type: "attached", ...key }]); @@ -182,7 +187,7 @@ describe("DesktopBrowserHost", () => { it.effect("announces a guest still loading its first page only once that page is up", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const loading = makeDebuggee({ loading: true }); const other = { ...key, tabId: "tab-2" }; const reader = yield* takeEvents(host, 3).pipe(Effect.forkScoped); @@ -205,7 +210,7 @@ describe("DesktopBrowserHost", () => { "keeps a loading guest unannounced across a replaced navigation and a new backend", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const loading = makeDebuggee({ loading: true }); const other = { ...key, tabId: "tab-2" }; host.attach(key, loading.tab); @@ -227,7 +232,7 @@ describe("DesktopBrowserHost", () => { "announces a first page that never comes up, but never a tab closed or destroyed first", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const closed = { ...key, tabId: "tab-2" }; const destroyed = { ...key, tabId: "tab-3" }; const destroyedGuest = makeDebuggee({ loading: true }); @@ -247,7 +252,7 @@ describe("DesktopBrowserHost", () => { it.effect("re-sends shown to a backend that starts later and when a tab attaches again", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; host.attach(key, makeDebuggee().tab); host.setShown(key, true); const reader = yield* takeEvents(host, 5).pipe(Effect.forkScoped); @@ -268,7 +273,7 @@ describe("DesktopBrowserHost", () => { it.effect("replays an explicit hidden report before announcing another tab", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const other = { ...key, tabId: "tab-2" }; host.setShown(key, false); host.attach(key, makeDebuggee().tab); @@ -285,7 +290,7 @@ describe("DesktopBrowserHost", () => { it.effect("drops replies from a relay the server released", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee(); host.attach(key, debuggee.tab); const reader = yield* takeEvents(host, 2).pipe(Effect.forkScoped); @@ -313,7 +318,7 @@ describe("DesktopBrowserHost", () => { it.effect("sends a page one screenshot at a time", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee(); host.attach(key, debuggee.tab); const replies = yield* watchReplies(host); @@ -330,9 +335,38 @@ describe("DesktopBrowserHost", () => { }), ); + it.effect( + "sends a screenshot once the client draws the guest at full detail, or soon after", + () => + Effect.gen(function* () { + const host = yield* DesktopBrowserHost.make; + const debuggee = makeDebuggee(); + host.attach(key, debuggee.tab); + const replies = yield* watchReplies(host); + + yield* command(host, 1, "Page.captureScreenshot"); + yield* settle; + expect(debuggee.sent).toEqual([]); + host.setCaptureDrawn(key, true); + yield* settle; + expect(debuggee.sent).toEqual([1]); + debuggee.releaseFirst(); + expect(yield* Queue.take(replies)).toBe(1); + + // A client that never draws, such as a hidden window, only delays the capture. + host.setCaptureDrawn(key, false); + yield* command(host, 2, "Page.captureScreenshot"); + yield* settle; + expect(debuggee.sent).toEqual([1]); + yield* TestClock.adjust("1 second"); + yield* settle; + expect(debuggee.sent).toEqual([1, 2]); + }).pipe(Effect.scoped), + ); + it.effect("stops waiting on a screenshot the page navigated away from", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee(); host.attach(key, debuggee.tab); const replies = yield* watchReplies(host); @@ -357,7 +391,7 @@ describe("DesktopBrowserHost", () => { it.effect("drops screenshots a released relay left waiting", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee(); host.attach(key, debuggee.tab); @@ -377,7 +411,7 @@ describe("DesktopBrowserHost", () => { it.effect("emulates focus while the server drives a guest, then lets a hidden one throttle", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee(); host.attach(key, debuggee.tab); @@ -408,7 +442,7 @@ describe("DesktopBrowserHost", () => { it.effect("keeps a guest focused while a command it is running is still pending", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee(); host.attach(key, debuggee.tab); const replies = yield* watchReplies(host); @@ -429,7 +463,7 @@ describe("DesktopBrowserHost", () => { it.effect("lets a guest throttle once Chromium can no longer answer its pending command", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee(); host.attach(key, debuggee.tab); @@ -451,7 +485,7 @@ describe("DesktopBrowserHost", () => { it.effect("keeps a guest focused for the screenshot a navigation lets start", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee(); host.attach(key, debuggee.tab); @@ -467,7 +501,7 @@ describe("DesktopBrowserHost", () => { it.effect("never sends a screenshot a navigation superseded while focus was changing", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee({ deferFocus: true }); host.attach(key, debuggee.tab); @@ -484,7 +518,7 @@ describe("DesktopBrowserHost", () => { it.effect("keeps a guest focused when its turn starts after the agent's first command", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee(); host.attach(key, debuggee.tab); const turn = (active: boolean) => @@ -506,7 +540,7 @@ describe("DesktopBrowserHost", () => { it.effect("lets a guest throttle through a turn that only sent it housekeeping", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee(); host.attach(key, debuggee.tab); yield* host.handleCommandLine( @@ -535,7 +569,7 @@ describe("DesktopBrowserHost", () => { it.effect("keeps a guest the agent used focused through its turn's pauses", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee(); host.attach(key, debuggee.tab); const turn = (active: boolean) => @@ -563,7 +597,7 @@ describe("DesktopBrowserHost", () => { "ends a command's hold with the turn that sent it, even if Chromium never answers", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee(); host.attach(key, debuggee.tab); yield* host.handleCommandLine( @@ -584,7 +618,7 @@ describe("DesktopBrowserHost", () => { it.effect("ends the agent's own session's holds with its turn, but not a viewer's stream", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee(); host.attach(key, debuggee.tab); const replies = yield* watchReplies(host); @@ -617,7 +651,7 @@ describe("DesktopBrowserHost", () => { it.effect("paints for a screenshot queued behind one its viewer abandoned mid-capture", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee(); host.attach(key, debuggee.tab); const replies = yield* watchReplies(host); @@ -655,7 +689,7 @@ describe("DesktopBrowserHost", () => { it.effect("stops painting for a queued screenshot once its session detaches", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee(); host.attach(key, debuggee.tab); const replies = yield* watchReplies(host); @@ -694,7 +728,7 @@ describe("DesktopBrowserHost", () => { it.effect("never sends a screenshot whose session detached while focus was changing", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee({ deferFocus: true }); host.attach(key, debuggee.tab); const replies = yield* watchReplies(host); @@ -718,7 +752,7 @@ describe("DesktopBrowserHost", () => { it.effect("holds no focus for a screenshot still queued when the agent's turn ends", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee(); host.attach(key, debuggee.tab); const painting = yield* watchPainting(host); @@ -748,7 +782,7 @@ describe("DesktopBrowserHost", () => { it.effect("lets a guest throttle when Chromium refuses a viewer's screencast", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee({ refuse: (method) => method === "Page.startScreencast" }); host.attach(key, debuggee.tab); const replies = yield* watchReplies(host); @@ -769,7 +803,7 @@ describe("DesktopBrowserHost", () => { it.effect("lets a guest throttle after a person's input through a viewer that then closed", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee(); host.attach(key, debuggee.tab); const replies = yield* watchReplies(host); @@ -798,7 +832,7 @@ describe("DesktopBrowserHost", () => { it.effect("keeps a page's screencast when a child session's screencast is refused", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee({ refuse: (method, sessionId) => method === "Page.startScreencast" && sessionId !== undefined, }); @@ -820,7 +854,7 @@ describe("DesktopBrowserHost", () => { it.effect("ignores a screencast that arrives on a session after it detached", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee(); host.attach(key, debuggee.tab); const replies = yield* watchReplies(host); @@ -846,7 +880,7 @@ describe("DesktopBrowserHost", () => { it.effect("lets a guest throttle once the session waiting on its command detaches", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee(); host.attach(key, debuggee.tab); const replies = yield* watchReplies(host); @@ -873,7 +907,7 @@ describe("DesktopBrowserHost", () => { it.effect("never sends a screenshot queued by a session that has since detached", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee(); host.attach(key, debuggee.tab); const replies = yield* watchReplies(host); @@ -904,7 +938,7 @@ describe("DesktopBrowserHost", () => { it.effect("keeps a streamed guest focused until its screencast ends", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee(); host.attach(key, debuggee.tab); @@ -933,7 +967,7 @@ describe("DesktopBrowserHost", () => { it.effect("keeps a guest focused while any of its screencasts runs", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee(); host.attach(key, debuggee.tab); const replies = yield* watchReplies(host); @@ -965,7 +999,7 @@ describe("DesktopBrowserHost", () => { it.effect("paints a hidden guest only while the screenshot it is taking is pending", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee(); host.attach(key, debuggee.tab); const painting = yield* watchPainting(host); @@ -991,7 +1025,7 @@ describe("DesktopBrowserHost", () => { it.effect("stops painting for a screenshot Chromium never answers once its document goes", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee(); host.attach(key, debuggee.tab); const painting = yield* watchPainting(host); @@ -1036,7 +1070,7 @@ describe("DesktopBrowserHost", () => { it.effect("paints a streamed guest until its last screencast ends", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee(); host.attach(key, debuggee.tab); const replies = yield* watchReplies(host); @@ -1243,7 +1277,7 @@ describe("DesktopBrowserHost", () => { it.effect("saves a server tab's download under its CDP guid where the server asked", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee(); host.attach(key, debuggee.tab); const replies = yield* watchReplies(host); @@ -1278,7 +1312,7 @@ describe("DesktopBrowserHost", () => { it.effect("tells a download the person clicked from one the agent's input started", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee(); host.attach(key, debuggee.tab); @@ -1342,7 +1376,7 @@ describe("DesktopBrowserHost", () => { it.effect("detaches only the tab whose CDP event is too large to relay", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const tabs = [makeDebuggee({ deferFocus: true }), makeDebuggee()]; const send = vi.spyOn(tabs[0]!.tab.debugger, "sendCommand"); const keys = [key, { threadId: "thread-2", tabId: "tab-2" }]; diff --git a/apps/desktop/src/preview/DesktopBrowserHost.ts b/apps/desktop/src/preview/DesktopBrowserHost.ts index e0326b7b76ec1..ce5d7074a786c 100644 --- a/apps/desktop/src/preview/DesktopBrowserHost.ts +++ b/apps/desktop/src/preview/DesktopBrowserHost.ts @@ -30,6 +30,8 @@ const AGENT_INPUT_WINDOW_MS = 5_000; /** A viewer's pointer travelling over the stream activates nothing on the page. */ const POINTER_TRAVEL = new Set(["mouseMoved", "mouseWheel"]); const FOCUS_IDLE = "5 seconds"; +/** How long a screenshot waits for the client to draw its guest at full detail. */ +const CAPTURE_DRAW_WAIT = "1 second"; /** Well inside the server's 10 s DESKTOP_ATTACH_TIMEOUT, for a first page that never reports it is up. */ const FIRST_PAGE_TIMEOUT = "5 seconds"; const ERR_ABORTED = -3; @@ -101,6 +103,8 @@ export class DesktopBrowserHost extends Context.Service< readonly detach: (key: DesktopBrowserTabKey) => void; readonly loadFailed: (key: DesktopBrowserTabKey, failure: PreviewAutomationLoadError) => void; readonly setShown: (key: DesktopBrowserTabKey, shown: boolean | undefined) => void; + /** Whether the client draws the guest at full detail while it is captured. */ + readonly setCaptureDrawn: (key: DesktopBrowserTabKey, drawn: boolean | undefined) => void; readonly humanStartedDownload: (source: Electron.WebContents) => boolean; /** Whether what the page does now follows the agent's input, not a viewer's. */ readonly agentLedPage: (source: Electron.WebContents) => boolean; @@ -138,6 +142,8 @@ export const make = Effect.gen(function* () { // Kept apart from attachment: the renderer can show a webview before its debugger attaches, // and the server forgets `shown` on detach, for example while DevTools holds the debugger. const shownTabs = new Map(); + const drawnTabs = new Set(); + const drawWaiters = new Map void>>(); const emit = (event: DesktopBrowserEventType) => runFork(PubSub.publish(outbox, event)); const nextScreenshot = (tab: AttachedTab) => { @@ -266,12 +272,32 @@ export const make = Effect.gen(function* () { }); }; + /** + * A scaled guest rasters at its on-screen size until the client draws it at full detail, + * and a screenshot taken before that copies the blurred frame. A client that cannot draw + * (a hidden window, say) only delays the capture. + */ + const whenDrawn = (tab: AttachedTab) => + new Promise((resolve) => { + const id = keyOf(tab.key); + const waiters = drawWaiters.get(id) ?? new Set(); + drawWaiters.set(id, waiters); + const done = () => { + waiters.delete(done); + if (waiters.size === 0 && drawWaiters.get(id) === waiters) drawWaiters.delete(id); + resolve(); + }; + waiters.add(done); + runFork(Effect.sleep(CAPTURE_DRAW_WAIT).pipe(Effect.andThen(Effect.sync(done)))); + }); + /** Chromium answers a capture, and frees its wake lock, only once the guest paints a frame. */ const paintUntilAnswered = (tab: AttachedTab, send: () => Promise) => { const sent = {}; tab.capturing.add(sent); syncPainting(tab); - return send().finally(() => { + // Sent at once when already drawn, so it keeps its place among the commands after it. + return (drawnTabs.has(keyOf(tab.key)) ? send() : whenDrawn(tab).then(send)).finally(() => { tab.capturing.delete(sent); syncPainting(tab); }); @@ -368,12 +394,15 @@ export const make = Effect.gen(function* () { // Waits for focus emulation; insertText and other non-CDP input would not queue behind it. const forward = (current?: () => boolean) => { const change = tab.focusChange; - const run = () => - tab.relay !== relay || (current !== undefined && !current()) + const stale = () => tab.relay !== relay || (current !== undefined && !current()); + const sendUnlessStale = () => + stale() ? Promise.reject(new Error("The page this screenshot was for has moved on.")) - : current === undefined - ? send(method, params, sessionId) - : paintUntilAnswered(tab, () => send(method, params, sessionId)); + : send(method, params, sessionId); + const run = () => + current === undefined || stale() + ? sendUnlessStale() + : paintUntilAnswered(tab, sendUnlessStale); return change === null ? run() : change.then(run); }; return method === "Page.captureScreenshot" @@ -587,6 +616,17 @@ export const make = Effect.gen(function* () { if (tabs.get(id)?.stopWaiting === null) emit({ type: "shown", ...key, shown }); }; + const setCaptureDrawn = (key: DesktopBrowserTabKey, drawn: boolean | undefined) => { + const id = keyOf(key); + if (!drawn) { + drawnTabs.delete(id); + return; + } + drawnTabs.add(id); + for (const done of drawWaiters.get(id) ?? []) done(); + drawWaiters.delete(id); + }; + const loadFailed: DesktopBrowserHost["Service"]["loadFailed"] = (key, failure) => { if (tabs.has(keyOf(key))) emit({ type: "loadFailed", ...key, ...failure }); }; @@ -663,6 +703,7 @@ export const make = Effect.gen(function* () { detach, loadFailed, setShown, + setCaptureDrawn, placeDownload, humanStartedDownload, agentLedPage, diff --git a/apps/desktop/src/preview/Manager.test.ts b/apps/desktop/src/preview/Manager.test.ts index 1fdb7b286ba1a..93bc996c2dc19 100644 --- a/apps/desktop/src/preview/Manager.test.ts +++ b/apps/desktop/src/preview/Manager.test.ts @@ -338,6 +338,7 @@ const makeTestPreviewWebContents = ( navigationHistory: { canGoBack: () => false, canGoForward: () => false }, setIgnoreMenuShortcuts: vi.fn(), setWindowOpenHandler: vi.fn(), + listeners: () => [], debugger: { isAttached: () => false, attach: vi.fn(), @@ -501,6 +502,7 @@ const makeFaviconWebContents = (options?: { focusedFrame: {} as object | null, setIgnoreMenuShortcuts: vi.fn(), setWindowOpenHandler: vi.fn(), + listeners: () => [], executeJavaScriptInIsolatedWorld, debugger: { isAttached: () => false, @@ -684,6 +686,7 @@ describe("PreviewManager", () => { attach: () => {}, detach: () => {}, setShown: () => {}, + setCaptureDrawn: () => {}, loadFailed: () => {}, humanStartedDownload: () => true, agentLedPage: () => false, @@ -1250,6 +1253,7 @@ describe("PreviewManager", () => { navigationHistory: { canGoBack: () => false, canGoForward: () => false }, setIgnoreMenuShortcuts: vi.fn(), setWindowOpenHandler: vi.fn(), + listeners: () => [], debugger: { isAttached: () => false, attach: vi.fn(), @@ -1357,6 +1361,7 @@ describe("PreviewManager", () => { navigationHistory: { canGoBack: () => false, canGoForward: () => false }, setIgnoreMenuShortcuts: vi.fn(), setWindowOpenHandler: vi.fn(), + listeners: () => [], get debugger() { if (destroyed) throw new Error("Object has been destroyed"); return wcDebugger; @@ -1629,6 +1634,7 @@ describe("PreviewManager", () => { navigationHistory: { canGoBack: () => false, canGoForward: () => false }, setIgnoreMenuShortcuts: vi.fn(), setWindowOpenHandler: vi.fn(), + listeners: () => [], debugger: { isAttached: () => attach.mock.calls.length > detach.mock.calls.length + chromiumDetaches, attach, @@ -1707,14 +1713,22 @@ describe("PreviewManager", () => { ), ); - const makeAudioWebContents = (id: number) => { + const makeAudioWebContents = (id: number, nativeDialog?: (...args: never[]) => void) => { const listeners = new Map void>(); + if (nativeDialog) listeners.set("-run-dialog", nativeDialog); + let debuggerMessage: ((...args: ReadonlyArray) => void) | undefined; const setAudioMuted = vi.fn(); let audible = false; let audibleAfterFirstRead = false; let audibleReads = 0; return { setAudioMuted, + emit: (event: string, ...args: ReadonlyArray) => { + (listeners.get(event) as ((...args: ReadonlyArray) => void) | undefined)?.( + ...args, + ); + }, + emitDebuggerMessage: (method: string) => debuggerMessage?.({}, method, {}, ""), emitAudioState: (next: boolean) => { audible = next; listeners.get("audio-state-changed")?.({ audible: next } as never); @@ -1746,16 +1760,23 @@ describe("PreviewManager", () => { off: vi.fn((event: string) => { listeners.delete(event); }), + once: vi.fn((event: string, listener: (...args: never[]) => void) => { + listeners.set(event, listener); + }), ipc: { on: vi.fn(), off: vi.fn() }, send: webviewSend, navigationHistory: { canGoBack: () => false, canGoForward: () => false }, setIgnoreMenuShortcuts: vi.fn(), setWindowOpenHandler: vi.fn(), + listeners: (event: string) => + event === "-run-dialog" && nativeDialog ? [nativeDialog] : [], debugger: { isAttached: () => false, attach: vi.fn(), sendCommand: vi.fn(async () => undefined), - on: vi.fn(), + on: vi.fn((event: string, listener: (...args: ReadonlyArray) => void) => { + if (event === "message") debuggerMessage = listener; + }), off: vi.fn(), }, } as never, @@ -1784,6 +1805,128 @@ describe("PreviewManager", () => { ), ); + effectIt.effect( + "holds a page dialog on its tab until it is answered or the guest goes away", + () => + withManager((manager) => + Effect.gen(function* () { + const guest = makeAudioWebContents(42); + fromId.mockReturnValue(guest.wc); + const states: PreviewManager.PreviewTabState[] = []; + const answer = vi.fn(); + const dialogInfo = { + dialogType: "confirm", + messageText: "Delete it?", + defaultPromptText: "", + }; + + yield* manager.subscribeStateChanges((_tabId, state) => + Effect.sync(() => { + states.push(state); + }), + ); + yield* manager.createTab("tab_dialog"); + yield* manager.prepareWebview(guest.wc); + yield* manager.registerWebview("tab_dialog", 42); + yield* Effect.yieldNow; + + guest.emit("-run-dialog", dialogInfo, answer); + yield* Effect.yieldNow; + expect(states.at(-1)?.dialog).toEqual({ + type: "confirm", + message: "Delete it?", + defaultValue: "", + }); + expect(answer).not.toHaveBeenCalled(); + + yield* manager.answerDialog("tab_dialog", true, undefined); + yield* Effect.yieldNow; + expect(answer).toHaveBeenCalledExactlyOnceWith(true, ""); + expect(states.at(-1)?.dialog).toBeUndefined(); + + const answeredByAgent = vi.fn(); + guest.emit("-run-dialog", dialogInfo, answeredByAgent); + yield* Effect.yieldNow; + guest.emitDebuggerMessage("Page.javascriptDialogClosed"); + yield* Effect.yieldNow; + expect(states.at(-1)?.dialog).toBeUndefined(); + yield* manager.answerDialog("tab_dialog", true, undefined); + expect(answeredByAgent).not.toHaveBeenCalled(); + + const replacedAnswer = vi.fn(); + guest.emit("-run-dialog", dialogInfo, replacedAnswer); + yield* Effect.yieldNow; + const replacement = makeAudioWebContents(43); + fromId.mockReturnValue(replacement.wc); + yield* manager.prepareWebview(replacement.wc); + yield* manager.registerWebview("tab_dialog", 43); + yield* Effect.yieldNow; + expect(states.at(-1)?.dialog).toBeUndefined(); + expect(replacedAnswer).toHaveBeenCalledExactlyOnceWith(false, ""); + + const closing = makeAudioWebContents(46); + fromId.mockReturnValue(closing.wc); + const closingAnswer = vi.fn(); + yield* manager.createTab("tab_dialog_closed"); + yield* manager.prepareWebview(closing.wc); + yield* manager.registerWebview("tab_dialog_closed", 46); + yield* Effect.yieldNow; + closing.emit("-run-dialog", dialogInfo, closingAnswer); + yield* Effect.yieldNow; + yield* manager.closeTab("tab_dialog_closed"); + yield* Effect.yieldNow; + expect(closingAnswer).toHaveBeenCalledExactlyOnceWith(false, ""); + expect(states.at(-1)?.dialog).toBeUndefined(); + + const doomed = makeAudioWebContents(44); + fromId.mockReturnValue(doomed.wc); + yield* manager.createTab("tab_dialog_destroyed"); + yield* manager.prepareWebview(doomed.wc); + yield* manager.registerWebview("tab_dialog_destroyed", 44); + yield* Effect.yieldNow; + doomed.emit("-run-dialog", dialogInfo, vi.fn()); + yield* Effect.yieldNow; + expect(states.at(-1)?.dialog).toBeDefined(); + doomed.emit("destroyed"); + yield* Effect.yieldNow; + expect(states.at(-1)?.dialog).toBeUndefined(); + }), + ), + ); + + effectIt.effect("holds a page dialog raised before the guest is registered", () => + withManager((manager) => + Effect.gen(function* () { + const native = vi.fn(); + const guest = makeAudioWebContents(45, native); + fromId.mockReturnValue(guest.wc); + const states: PreviewManager.PreviewTabState[] = []; + const answer = vi.fn(); + + yield* manager.subscribeStateChanges((_tabId, state) => + Effect.sync(() => { + states.push(state); + }), + ); + yield* manager.createTab("tab_dialog_early"); + yield* manager.prepareWebview(guest.wc); + guest.emit( + "-run-dialog", + { dialogType: "alert", messageText: "Hi", defaultPromptText: "" }, + answer, + ); + yield* manager.registerWebview("tab_dialog_early", 45); + yield* Effect.yieldNow; + + expect(native).not.toHaveBeenCalled(); + expect(states.at(-1)?.dialog).toEqual({ type: "alert", message: "Hi", defaultValue: "" }); + + yield* manager.answerDialog("tab_dialog_early", true, undefined); + expect(answer).toHaveBeenCalledExactlyOnceWith(true, ""); + }), + ), + ); + effectIt.effect("ignores audio state from a replaced guest", () => withManager((manager) => Effect.gen(function* () { @@ -2462,6 +2605,7 @@ describe("PreviewManager", () => { }), ); expect(yield* Queue.take(capturing)).toBe(true); + yield* manager.setCaptureDrawn("tab_1", true); screenshot.resolve({ data: "" }); expect(yield* Queue.take(capturing)).toBe(false); }).pipe(Effect.provide(managerLayer())), @@ -2699,6 +2843,7 @@ describe("PreviewManager", () => { navigationHistory: { canGoBack: () => false, canGoForward: () => false }, setIgnoreMenuShortcuts: vi.fn(), setWindowOpenHandler: vi.fn(), + listeners: () => [], debugger: { isAttached: () => false, attach: vi.fn(), @@ -3301,6 +3446,7 @@ describe("PreviewManager", () => { navigationHistory: { canGoBack: () => false, canGoForward: () => false }, setIgnoreMenuShortcuts: vi.fn(), setWindowOpenHandler: vi.fn(), + listeners: () => [], debugger: { isAttached: () => false, attach: vi.fn(), diff --git a/apps/desktop/src/preview/Manager.ts b/apps/desktop/src/preview/Manager.ts index 8fe4cf1c992af..557796e4c9085 100644 --- a/apps/desktop/src/preview/Manager.ts +++ b/apps/desktop/src/preview/Manager.ts @@ -11,6 +11,7 @@ import type { DesktopPreviewAnnotationVoiceConfig, DesktopPreviewAnnotationVoiceState, DesktopPreviewColorScheme, + DesktopPreviewDialog, DesktopPreviewFavicon, DesktopPreviewFindResultEvent, DesktopPreviewOpenLinkEvent, @@ -89,6 +90,7 @@ import { START_PICK_CHANNEL, THUMB_PRESS_CHANNEL, } from "./GuestProtocol.ts"; +import { holdPageDialogs, type PageDialogHold } from "./PageDialogs.ts"; import { isPreviewAnnotationPayload } from "./PickedElementPayload.ts"; import { captureFavicon, safeHttpOrigin, selectFaviconCandidates } from "./FaviconCapture.ts"; import { DEFAULT_RECORDING_INPUT_OPTIONS, type RecordingInputOptions } from "./RecordingInput.ts"; @@ -118,6 +120,7 @@ export interface PreviewTabState { audible: boolean; controller: "human" | "agent" | "none"; capturing: boolean; + dialog?: DesktopPreviewDialog; favicon?: DesktopPreviewFavicon; serverTab?: { readonly threadId: string; readonly tabId: string }; updatedAt: string; @@ -614,6 +617,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function const tabLifecycleGenerations = new Map(); // A guest can fail its first load before registerWebview installs its tab listeners. const guestLoadFailures = new Map(); + const dialogHolds = new Map(); const attempt = (errorContext: PreviewOperationContext, evaluate: () => A) => Effect.try({ @@ -960,6 +964,39 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function if (Option.isSome(next)) yield* emitIfCurrent(tabId, next.value); }); + const syncTabDialog = Effect.fn("PreviewManager.syncTabDialog")(function* ( + wc: Electron.WebContents, + ) { + const updatedAt = yield* currentIso; + const next = yield* SynchronizedRef.modify(tabsRef, (tabs) => { + const entry = [...tabs].find(([, tab]) => tab.webContentsId === wc.id); + if (!entry) return [Option.none(), tabs] as const; + const [tabId, current] = entry; + const dialog = dialogHolds.get(wc.id)?.current(); + const { dialog: _dialog, ...withoutDialog } = current; + const state: PreviewTabState = { + ...withoutDialog, + ...(dialog ? { dialog } : {}), + updatedAt, + }; + return [ + Option.some([tabId, state] as const), + replaceMap(tabs, (copy) => { + copy.set(tabId, state); + }), + ] as const; + }); + if (Option.isSome(next)) yield* emitIfCurrent(next.value[0], next.value[1]); + }); + + const ensureDialogHold = (wc: Electron.WebContents) => { + if (dialogHolds.has(wc.id)) return; + dialogHolds.set( + wc.id, + holdPageDialogs(wc, () => runFork(syncTabDialog(wc))), + ); + }; + const requireWebContents = Effect.fn("PreviewManager.requireWebContents")(function* ( tabId: string, ) { @@ -1102,6 +1139,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function } }); const onMessage: BrowserControlSession["onMessage"] = (_event, method) => { + if (method === "Page.javascriptDialogClosed") dialogHolds.get(wc.id)?.closed(); runFork(handleDebuggerMessage(method)); }; const control: BrowserControlSession = { @@ -1654,6 +1692,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function wc.ipc.off(RECORDING_INPUT_CHANNEL, recordingInput); wc.ipc.off(PAGE_UNHANDLED_SHORTCUT_CHANNEL, pageUnhandledShortcut); detachPasskeys(); + dialogHolds.get(wc.id)?.answer(false); }).pipe(Effect.ignore), ); const install = Effect.fn("PreviewManager.installWebContentsListeners")(function* () { @@ -1827,7 +1866,10 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function }); if (Option.isNone(tab)) return; const closedTab = tab.value; - if (closedTab.serverTab) browserHost.setShown(closedTab.serverTab, undefined); + if (closedTab.serverTab) { + browserHost.setShown(closedTab.serverTab, undefined); + browserHost.setCaptureDrawn(closedTab.serverTab, undefined); + } if (closedTab.webContentsId != null) { yield* Effect.all( [ @@ -1838,8 +1880,9 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function ); } const updatedAt = yield* currentIso; + const { dialog: _dialog, ...closedWithoutDialog } = closedTab; const closed: PreviewTabState = { - ...closedTab, + ...closedWithoutDialog, webContentsId: null, navStatus: { kind: "Idle" }, canGoBack: false, @@ -1964,9 +2007,11 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function } const pendingUrl = current.navStatus.kind === "Loading" ? current.navStatus.url : null; const failure = guestLoadFailures.get(webContentsId); - const { favicon: _favicon, ...currentWithoutFavicon } = current; + const { favicon: _favicon, dialog: _dialog, ...currentWithoutFavicon } = current; + const pendingDialog = dialogHolds.get(webContentsId)?.current(); const next: PreviewTabState = { ...currentWithoutFavicon, + ...(pendingDialog ? { dialog: pendingDialog } : {}), webContentsId, navStatus: failure && (pendingUrl === null || pendingUrl === failure.url) @@ -2041,6 +2086,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function ) { yield* rendererHistory.register(wc, { surface: "preview" }); const webContentsId = wc.id; + ensureDialogHold(wc); wc.on("did-start-navigation", (event) => { if (event.isMainFrame && !event.isSameDocument) guestLoadFailures.delete(webContentsId); }); @@ -2054,6 +2100,8 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function }); wc.once("destroyed", () => { guestLoadFailures.delete(webContentsId); + dialogHolds.get(webContentsId)?.closed(); + dialogHolds.delete(webContentsId); runFork(hideDestroyedGuest(webContentsId)); runFork(detachControlSession(webContentsId)); }); @@ -2114,6 +2162,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function audible: current?.audible ?? false, controller: current?.controller ?? "none", capturing: current?.capturing ?? false, + ...(current?.dialog ? { dialog: current.dialog } : {}), ...(current?.favicon ? { favicon: current.favicon } : {}), ...(current?.serverTab ? { serverTab: current.serverTab } : {}), updatedAt, @@ -2157,7 +2206,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function if (current?.webContentsId !== webContentsId) { return [Option.none(), tabs] as const; } - const { favicon: _favicon, ...currentWithoutFavicon } = current; + const { favicon: _favicon, dialog: _dialog, ...currentWithoutFavicon } = current; const next: PreviewTabState = { ...currentWithoutFavicon, webContentsId: null }; return [ Option.some(next), @@ -2635,12 +2684,21 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function if (serverTab) browserHost.setShown(serverTab, shown); }); + const setCaptureDrawn = Effect.fn("PreviewManager.setCaptureDrawn")(function* ( + tabId: string, + drawn: boolean, + ) { + const serverTab = (yield* SynchronizedRef.get(tabsRef)).get(tabId)?.serverTab; + if (serverTab) browserHost.setCaptureDrawn(serverTab, drawn); + }); + // A window reload or guest crash destroys the guest without the renderer reporting it hidden. // The renderer reports again once a new guest registers. const hideDestroyedGuest = Effect.fnUntraced(function* (webContentsId: number) { for (const tab of (yield* SynchronizedRef.get(tabsRef)).values()) { if (tab.webContentsId === webContentsId && tab.serverTab) { browserHost.setShown(tab.serverTab, false); + browserHost.setCaptureDrawn(tab.serverTab, false); } } }); @@ -2672,6 +2730,22 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function ); }); + const answerDialog = Effect.fn("PreviewManager.answerDialog")(function* ( + tabId: string, + accept: boolean, + promptText: string | undefined, + ) { + const tab = (yield* SynchronizedRef.get(tabsRef)).get(tabId); + if (!tab) { + return yield* new PreviewTabNotFoundError({ tabId }); + } + const webContentsId = tab.webContentsId; + if (webContentsId === null) return; + yield* attempt({ operation: "answerDialog", tabId, webContentsId }, () => + dialogHolds.get(webContentsId)?.answer(accept, promptText), + ); + }); + const captureScreenshot = Effect.fn("PreviewManager.captureScreenshot")(function* ( tabId: string, ) { @@ -3715,7 +3789,9 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function setAnnotationTheme, setAnnotationSendEnabled, setAudioMuted, + answerDialog, setShown, + setCaptureDrawn, setColorScheme, setMainWindow, setForwardedShortcuts: (shortcuts: ReadonlyArray) => @@ -3931,7 +4007,13 @@ export class PreviewManager extends Context.Service< tabId: string, audioMuted: boolean, ) => Effect.Effect; + readonly answerDialog: ( + tabId: string, + accept: boolean, + promptText: string | undefined, + ) => Effect.Effect; readonly setShown: (tabId: string, shown: boolean) => Effect.Effect; + readonly setCaptureDrawn: (tabId: string, drawn: boolean) => Effect.Effect; readonly openDevTools: (tabId: string) => Effect.Effect; readonly clearCookies: ( partitions?: ReadonlyArray, @@ -4093,7 +4175,9 @@ export const make = Effect.gen(function* PreviewManagerMake() { setColorScheme: operations.setColorScheme, setZoomFactor: operations.setZoomFactor, setAudioMuted: operations.setAudioMuted, + answerDialog: operations.answerDialog, setShown: operations.setShown, + setCaptureDrawn: operations.setCaptureDrawn, openDevTools: operations.openDevTools, clearCookies: Effect.fn("PreviewManager.clearCookies")(function* (partitions) { yield* browserSession diff --git a/apps/desktop/src/preview/PageDialogs.test.ts b/apps/desktop/src/preview/PageDialogs.test.ts new file mode 100644 index 0000000000000..c39eb4623f7fa --- /dev/null +++ b/apps/desktop/src/preview/PageDialogs.test.ts @@ -0,0 +1,77 @@ +import * as NodeEvents from "node:events"; +import { describe, expect, it, vi } from "vite-plus/test"; + +import { holdPageDialogs } from "./PageDialogs.ts"; + +const info = { dialogType: "confirm", messageText: "Delete it?", defaultPromptText: "" }; + +function setup() { + const contents = new NodeEvents.EventEmitter(); + const native = vi.fn(); + contents.on("-run-dialog", native); + const changed = vi.fn(); + const hold = holdPageDialogs(contents, changed); + const callback = vi.fn(); + return { contents, native, changed, hold, callback }; +} + +describe("holdPageDialogs", () => { + it("keeps a page dialog pending instead of showing the native box", () => { + const { contents, native, changed, callback } = setup(); + + contents.emit("-run-dialog", info, callback); + + expect(native).not.toHaveBeenCalled(); + expect(callback).not.toHaveBeenCalled(); + expect(changed).toHaveBeenLastCalledWith({ + type: "confirm", + message: "Delete it?", + defaultValue: "", + }); + }); + + it("answers the page once and clears the dialog", () => { + const { contents, changed, hold, callback } = setup(); + contents.emit("-run-dialog", { ...info, dialogType: "prompt" }, callback); + + expect(hold.answer(true, "yes")).toBe(true); + expect(hold.answer(false)).toBe(false); + + expect(callback).toHaveBeenCalledOnce(); + expect(callback).toHaveBeenCalledWith(true, "yes"); + expect(changed).toHaveBeenLastCalledWith(null); + + const first = vi.fn(); + contents.emit("-run-dialog", info, first); + contents.emit("-run-dialog", info, callback); + expect(first).toHaveBeenCalledExactlyOnceWith(false, ""); + }); + + it("drops a dialog that CDP or a navigation already closed without answering twice", () => { + const { contents, changed, hold, callback } = setup(); + + contents.emit("-run-dialog", info, callback); + hold.closed(); + expect(changed).toHaveBeenLastCalledWith(null); + expect(hold.answer(true)).toBe(false); + + contents.emit("-run-dialog", info, callback); + contents.emit("-cancel-dialogs"); + expect(changed).toHaveBeenLastCalledWith(null); + expect(hold.answer(true)).toBe(false); + expect(callback).not.toHaveBeenCalled(); + }); + + it("dismisses a pending dialog when a main-frame navigation starts", () => { + const { contents, changed, callback } = setup(); + contents.emit("-run-dialog", info, callback); + + contents.emit("did-start-navigation", { isMainFrame: false, isSameDocument: false }); + contents.emit("did-start-navigation", { isMainFrame: true, isSameDocument: true }); + expect(callback).not.toHaveBeenCalled(); + + contents.emit("did-start-navigation", { isMainFrame: true, isSameDocument: false }); + expect(callback).toHaveBeenCalledExactlyOnceWith(false, ""); + expect(changed).toHaveBeenLastCalledWith(null); + }); +}); diff --git a/apps/desktop/src/preview/PageDialogs.ts b/apps/desktop/src/preview/PageDialogs.ts new file mode 100644 index 0000000000000..96dcbb7b09380 --- /dev/null +++ b/apps/desktop/src/preview/PageDialogs.ts @@ -0,0 +1,69 @@ +import type { DesktopPreviewDialog } from "@t3tools/contracts"; + +type DialogCallback = (accept: boolean, userInput: string) => void; + +interface RunDialogInfo { + readonly dialogType: string; + readonly messageText: string; + readonly defaultPromptText: string; +} + +export interface PageDialogHold { + readonly answer: (accept: boolean, promptText?: string) => boolean; + readonly closed: () => void; + readonly current: () => DesktopPreviewDialog | null; +} + +// Electron shows page dialogs as a native app-modal box from the `-run-dialog` event and never +// closes it when CDP answers. Replacing that listener keeps the dialog pending for the tab's UI. +export function holdPageDialogs( + contents: NodeJS.EventEmitter, + changed: (dialog: DesktopPreviewDialog | null) => void, +): PageDialogHold { + let pending: DialogCallback | null = null; + let shown: DesktopPreviewDialog | null = null; + const clear = () => { + if (pending === null) return; + pending = null; + shown = null; + changed(null); + }; + const deliver = (callback: DialogCallback, accept: boolean, userInput: string) => { + try { + callback(accept, userInput); + return true; + } catch { + return false; + } + }; + const run = (info: RunDialogInfo, callback: DialogCallback) => { + const previous = pending; + if (previous !== null) deliver(previous, false, ""); + pending = callback; + shown = { + type: info.dialogType, + message: info.messageText, + defaultValue: info.defaultPromptText, + }; + changed(shown); + }; + for (const listener of contents.listeners("-run-dialog")) { + contents.off("-run-dialog", listener as (...args: unknown[]) => void); + } + contents.on("-run-dialog", run); + const answer = (accept: boolean, promptText?: string) => { + const callback = pending; + if (callback === null) return false; + clear(); + return deliver(callback, accept, promptText ?? ""); + }; + contents.on("-cancel-dialogs", clear); + // Chrome dismisses page dialogs when a navigation starts; a held one would block the commit. + contents.on( + "did-start-navigation", + (event: { readonly isMainFrame: boolean; readonly isSameDocument: boolean }) => { + if (event.isMainFrame && !event.isSameDocument) answer(false); + }, + ); + return { answer, closed: clear, current: () => shown }; +} diff --git a/apps/desktop/src/shell/DesktopShellEnvironment.test.ts b/apps/desktop/src/shell/DesktopShellEnvironment.test.ts index 3486c296da516..7808682dfd82b 100644 --- a/apps/desktop/src/shell/DesktopShellEnvironment.test.ts +++ b/apps/desktop/src/shell/DesktopShellEnvironment.test.ts @@ -2,6 +2,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, describe, it } from "@effect/vitest"; import * as HostProcess from "@t3tools/shared/HostProcess"; +import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; import * as Deferred from "effect/Deferred"; @@ -62,6 +63,26 @@ function makeProcess(output: string, exitCode = 0): ChildProcessSpawner.ChildPro }); } +function makeSlowProcess( + output: string, + delay: Duration.Input, +): ChildProcessSpawner.ChildProcessHandle { + const stdout = Stream.fromEffect(Effect.as(Effect.sleep(delay), textEncoder.encode(output))); + return ChildProcessSpawner.makeHandle({ + pid: ChildProcessSpawner.ProcessId(125), + stdout, + stderr: Stream.empty, + all: stdout, + exitCode: Effect.as(Effect.sleep(delay), ChildProcessSpawner.ExitCode(0)), + isRunning: Effect.succeed(true), + kill: () => Effect.void, + stdin: Sink.drain, + getInputFd: () => Sink.drain, + getOutputFd: () => Stream.empty, + unref: Effect.succeed(Effect.void), + }); +} + function makeHungProcess(): ChildProcessSpawner.ChildProcessHandle { return ChildProcessSpawner.makeHandle({ pid: ChildProcessSpawner.ProcessId(124), @@ -670,6 +691,129 @@ describe("DesktopShellEnvironment", () => { }), ); + it.effect("retries the user's shell when only the fallback shell answered", () => + Effect.gen(function* () { + const env: NodeJS.ProcessEnv = { SHELL: "/usr/bin/fish", PATH: "/usr/bin" }; + const commands: string[] = []; + let fishReady = false; + yield* runShellEnvironment({ + env, + platform: "linux", + handler: (command) => { + if (command._tag !== "StandardCommand") return ""; + commands.push(command.command); + if (command.command !== "/usr/bin/fish") return envOutput({ PATH: "/usr/bin" }); + return fishReady + ? envOutput({ PATH: "/fish/bin:/usr/bin" }) + : { output: "", exitCode: 7 }; + }, + use: (service) => + Effect.gen(function* () { + assert.isTrue(yield* service.awaitDiscovery); + assert.equal(env.PATH, "/usr/bin"); + // The Linux probe checks the D-Bus socket on the real filesystem, which the clock does not await. + const published = yield* service.updates.pipe( + Stream.filter((snapshot) => snapshot.environment.PATH === "/fish/bin:/usr/bin"), + Stream.runHead, + Effect.forkChild({ startImmediately: true }), + ); + + fishReady = true; + yield* TestClock.adjust("30 seconds"); + assert.isTrue(Option.isSome(yield* Fiber.join(published))); + assert.equal(env.PATH, "/fish/bin:/usr/bin"); + return true; + }), + }).pipe(Effect.provide(Logger.layer([]))); + assert.deepEqual(commands, ["/usr/bin/fish", "/bin/bash", "/usr/bin/fish"]); + + // With no user shell to wait for, the fallback's answer is final. + commands.length = 0; + yield* runShellEnvironment({ + env: { PATH: "/usr/bin" }, + platform: "linux", + handler: (command) => { + if (command._tag === "StandardCommand") commands.push(command.command); + return envOutput({ PATH: "/usr/bin" }); + }, + use: (service) => + Effect.gen(function* () { + assert.isTrue(yield* service.awaitDiscovery); + yield* TestClock.adjust("5 minutes"); + return true; + }), + }).pipe(Effect.provide(Logger.layer([]))); + assert.deepEqual(commands, ["/bin/bash"]); + }), + ); + + it.effect("gives background retries time for a locked or slow shell, then publishes", () => + Effect.gen(function* () { + const env: NodeJS.ProcessEnv = { SHELL: "/bin/zsh", PATH: "/usr/bin" }; + // Startup fails fast, the first retry meets a shell blocked on a lock, the second a slow one. + const spawned = yield* Effect.forEach([0, 1, 2], () => Deferred.make()); + const stopped = yield* Deferred.make(); + let attempts = 0; + yield* runShellEnvironment({ + env, + platform: "darwin", + handler: () => "", + processSpawner: ChildProcessSpawner.make((command) => { + if (command._tag !== "StandardCommand" || command.command !== "/bin/zsh") { + return Effect.succeed(makeProcess("")); + } + const attempt = attempts++; + const spawn = Deferred.succeed(spawned[attempt]!, undefined); + if (attempt === 0) return spawn.pipe(Effect.as(makeProcess(""))); + if (attempt === 1) { + return spawn.pipe( + Effect.andThen( + Effect.acquireRelease(Effect.succeed(makeHungProcess()), () => + Deferred.succeed(stopped, command.options), + ), + ), + ); + } + return spawn.pipe( + Effect.as(makeSlowProcess(envOutput({ PATH: "/fresh/bin" }), "20 seconds")), + ); + }), + use: (service) => + Effect.gen(function* () { + assert.isFalse(yield* service.awaitDiscovery); + const published = yield* service.updates.pipe( + Stream.drop(1), + Stream.runHead, + Effect.forkChild({ startImmediately: true }), + ); + + yield* TestClock.adjust("30 seconds"); + yield* Deferred.await(spawned[1]!); + // pyenv waits up to 60 s on its rehash lock before the shell continues. + yield* TestClock.adjust("1 minute"); + assert.isFalse(yield* Deferred.isDone(stopped)); + yield* TestClock.adjust("1 minute"); + const stop = yield* Deferred.await(stopped); + // pyenv releases that lock in an EXIT trap, which SIGTERM runs and SIGKILL skips. + assert.equal(stop.killSignal, "SIGTERM"); + assert.isAtLeast(Duration.toMillis(stop.forceKillAfter ?? 0), 5_000); + + yield* TestClock.adjust("30 seconds"); + yield* Deferred.await(spawned[2]!); + yield* TestClock.adjust("20 seconds"); + const snapshot = yield* Fiber.join(published); + assert.equal(env.PATH, "/fresh/bin:/usr/bin"); + assert.isTrue(Option.isSome(snapshot) && snapshot.value.discovered); + assert.equal( + Option.isSome(snapshot) ? snapshot.value.environment.PATH : undefined, + "/fresh/bin:/usr/bin", + ); + return true; + }), + }); + }), + ); + it.effect("recovers the login-shell PATH when the first probe outlasts the timeout", () => Effect.gen(function* () { const env: NodeJS.ProcessEnv = { SHELL: "/bin/zsh", PATH: "/usr/bin:/bin:/usr/sbin:/sbin" }; diff --git a/apps/desktop/src/shell/DesktopShellEnvironment.ts b/apps/desktop/src/shell/DesktopShellEnvironment.ts index 5389d94c1e8e8..351150aa4b987 100644 --- a/apps/desktop/src/shell/DesktopShellEnvironment.ts +++ b/apps/desktop/src/shell/DesktopShellEnvironment.ts @@ -15,6 +15,7 @@ import * as Deferred from "effect/Deferred"; import * as Path from "effect/Path"; import * as PubSub from "effect/PubSub"; import * as Ref from "effect/Ref"; +import * as Schedule from "effect/Schedule"; import * as Scope from "effect/Scope"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; @@ -28,9 +29,17 @@ import * as DesktopEnvironment from "../app/DesktopEnvironment.ts"; type EnvironmentPatch = Record; +interface ProbeBudget { + readonly timeout: Duration.Duration; + // One longer wait for the first login shell that times out. + readonly slowTimeout?: Duration.Duration; + readonly terminateGrace: Duration.Duration; +} + interface ShellEnvironmentConfig { readonly env: NodeJS.ProcessEnv; readonly platform: NodeJS.Platform; + readonly budget: ProbeBudget; } interface WindowsProbeOptions { @@ -125,6 +134,20 @@ const LOGIN_SHELL_TIMEOUT = Duration.seconds(5); const SLOW_LOGIN_SHELL_TIMEOUT = Duration.seconds(20); const LAUNCHCTL_TIMEOUT = Duration.seconds(2); const PROCESS_TERMINATE_GRACE = Duration.seconds(1); +const STARTUP_PROBE: ProbeBudget = { + timeout: LOGIN_SHELL_TIMEOUT, + slowTimeout: SLOW_LOGIN_SHELL_TIMEOUT, + terminateGrace: PROCESS_TERMINATE_GRACE, +}; +// Retries block nothing, so they outlast pyenv's 60 s wait on its rehash lock, and SIGTERM gets +// time to run the exit trap that releases it. A SIGKILL leaves the lock for two minutes. +const RETRY_PROBE: ProbeBudget = { + timeout: Duration.minutes(2), + terminateGrace: Duration.seconds(10), +}; +// A Mac asleep at launch fails the first probe on wake, and nothing else would probe again. +const DISCOVERY_RETRY_DELAY = Duration.seconds(30); +const DISCOVERY_RETRIES = 10; const trimNonEmpty = (value: string | null | undefined): Option.Option => Option.fromNullishOr(value).pipe( @@ -245,6 +268,7 @@ const runCommandOutput = Effect.fn("desktop.shellEnvironment.runCommandOutput")( readonly args: ReadonlyArray; readonly env: NodeJS.ProcessEnv; readonly timeout: Duration.Duration; + readonly terminateGrace?: Duration.Duration; readonly shell?: boolean; }): Effect.fn.Return< string, @@ -263,7 +287,7 @@ const runCommandOutput = Effect.fn("desktop.shellEnvironment.runCommandOutput")( stdout: "pipe", stderr: "ignore", killSignal: "SIGTERM", - forceKillAfter: PROCESS_TERMINATE_GRACE, + forceKillAfter: input.terminateGrace ?? PROCESS_TERMINATE_GRACE, }), ); return yield* Effect.all([Stream.mkString(Stream.decodeText(child.stdout)), child.exitCode], { @@ -329,6 +353,7 @@ const readLoginShellEnvironment = ( names: ReadonlyArray, env: NodeJS.ProcessEnv, timeout: Duration.Duration, + terminateGrace: Duration.Duration, ): Effect.Effect< EnvironmentPatch, DesktopShellEnvironmentCommandTimeoutError, @@ -342,6 +367,7 @@ const readLoginShellEnvironment = ( args: ["-ilc", buildEnvironmentCaptureCommand(shell, names)], env, timeout, + terminateGrace, }).pipe(Effect.map((output) => extractEnvironment(output, names))); const readLaunchctlPath = (env: NodeJS.ProcessEnv) => @@ -358,6 +384,7 @@ const readWindowsEnvironment = Effect.fn("desktop.shellEnvironment.readWindowsEn names: ReadonlyArray, options: WindowsProbeOptions, env: NodeJS.ProcessEnv, + budget: ProbeBudget, ): Effect.fn.Return { if (names.length === 0) return {}; @@ -375,7 +402,8 @@ const readWindowsEnvironment = Effect.fn("desktop.shellEnvironment.readWindowsEn command, args, env, - timeout: LOGIN_SHELL_TIMEOUT, + timeout: budget.timeout, + terminateGrace: budget.terminateGrace, }).pipe(orEmptyOnTimeout); const environment = extractEnvironment(output, names); if (Object.keys(environment).length > 0) { @@ -393,8 +421,13 @@ const installWindowsEnvironment = Effect.fn("desktop.shellEnvironment.installWin ): Effect.fn.Return { const [noProfile, profile] = yield* Effect.all( [ - readWindowsEnvironment(["PATH"], { loadProfile: false }, config.env), - readWindowsEnvironment(WINDOWS_PROFILE_ENV_NAMES, { loadProfile: true }, config.env), + readWindowsEnvironment(["PATH"], { loadProfile: false }, config.env, config.budget), + readWindowsEnvironment( + WINDOWS_PROFILE_ENV_NAMES, + { loadProfile: true }, + config.env, + config.budget, + ), ], { concurrency: 2 }, ); @@ -418,6 +451,9 @@ const installWindowsEnvironment = Effect.fn("desktop.shellEnvironment.installWin }, ); +const listUserShells = (env: NodeJS.ProcessEnv): ReadonlyArray => + [env.SHELL?.trim(), readUserLoginShell()].filter((shell): shell is string => Boolean(shell)); + const installPosixEnvironment = Effect.fn("desktop.shellEnvironment.installPosixEnvironment")( function* ( config: ShellEnvironmentConfig, @@ -428,22 +464,28 @@ const installPosixEnvironment = Effect.fn("desktop.shellEnvironment.installPosix > { const fileSystem = yield* FileSystem.FileSystem; const shellEnvironment: EnvironmentPatch = {}; - const userShells = [config.env.SHELL?.trim(), readUserLoginShell()]; + const userShells = listUserShells(config.env); let answeredBy: string | undefined; let waitedForSlowShell = false; for (const shell of listLoginShellCandidates(config.platform, config.env.SHELL)) { const read = (timeout: Duration.Duration) => - readLoginShellEnvironment(shell, LOGIN_SHELL_ENV_NAMES, config.env, timeout); + readLoginShellEnvironment( + shell, + LOGIN_SHELL_ENV_NAMES, + config.env, + timeout, + config.budget.terminateGrace, + ); Object.assign( shellEnvironment, - yield* read(LOGIN_SHELL_TIMEOUT).pipe( + yield* read(config.budget.timeout).pipe( Effect.catchTags({ DesktopShellEnvironmentCommandTimeoutError: (error) => { - const retry = !waitedForSlowShell; + const slowTimeout = waitedForSlowShell ? undefined : config.budget.slowTimeout; waitedForSlowShell = true; return logShellEnvironmentCommandError(error).pipe( - Effect.andThen(retry ? read(SLOW_LOGIN_SHELL_TIMEOUT) : Effect.succeed({})), + Effect.andThen(slowTimeout ? read(slowTimeout) : Effect.succeed({})), ); }, }), @@ -557,7 +599,10 @@ const installPosixEnvironment = Effect.fn("desktop.shellEnvironment.installPosix } const prepared = Option.isSome(trimNonEmpty(shellEnvironment.PATH)); - return { prepared, fromUserShell: prepared && userShells.includes(answeredBy) }; + return { + prepared, + fromUserShell: prepared && answeredBy !== undefined && userShells.includes(answeredBy), + }; }, ); @@ -641,38 +686,60 @@ export const make = Effect.gen(function* () { yield* Ref.set(latest, Option.some(message)); yield* PubSub.publish(changes, message); }); - const refresh = Effect.gen(function* () { - // Refresh from the inherited baseline so removed cached paths and values do not survive. - const fresh = { ...inherited }; - const discovery = yield* installShellEnvironment({ - env: fresh, - platform: environment.platform, - }); - const { prepared } = discovery; - const patch = Object.fromEntries( - Object.keys(ShellEnvironmentPatch.fields).map((name) => [name, fresh[name] ?? null]), - ); - if (prepared || Option.isNone(yield* Ref.get(latest))) yield* publish(patch, prepared); - if (prepared) { - const cached = Object.fromEntries( - CACHED_ENV_NAMES.flatMap((name) => (fresh[name] ? [[name, fresh[name]]] : [])), - ); - const persist = Effect.gen(function* () { - const encoded = yield* encodeCache({ version: 1, key, environment: cached }); - yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true }); - yield* fileSystem.writeFileString(cachePath + ".tmp", encoded, { mode: 0o600 }); - yield* fileSystem.rename(cachePath + ".tmp", cachePath); + const probe = Effect.fn("desktop.shellEnvironment.refresh")( + function* (budget: ProbeBudget) { + // Refresh from the inherited baseline so removed cached paths and values do not survive. + const fresh = { ...inherited }; + const discovery = yield* installShellEnvironment({ + env: fresh, + platform: environment.platform, + budget, }); - yield* persist.pipe( - Effect.catch(() => Effect.logWarning("Could not cache shell environment")), + const { prepared } = discovery; + const patch = Object.fromEntries( + Object.keys(ShellEnvironmentPatch.fields).map((name) => [name, fresh[name] ?? null]), ); - } - return discovery; - }).pipe( + if (prepared || Option.isNone(yield* Ref.get(latest))) yield* publish(patch, prepared); + if (prepared) { + const cached = Object.fromEntries( + CACHED_ENV_NAMES.flatMap((name) => (fresh[name] ? [[name, fresh[name]]] : [])), + ); + const persist = Effect.gen(function* () { + const encoded = yield* encodeCache({ version: 1, key, environment: cached }); + yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true }); + yield* fileSystem.writeFileString(cachePath + ".tmp", encoded, { mode: 0o600 }); + yield* fileSystem.rename(cachePath + ".tmp", cachePath); + }); + yield* persist.pipe( + Effect.catch(() => Effect.logWarning("Could not cache shell environment")), + ); + } + return discovery; + }, Effect.provideService(FileSystem.FileSystem, fileSystem), Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), - Effect.withSpan("desktop.shellEnvironment.refresh"), + ); + // A fallback shell's PATH can miss folders the user's own shell adds, so keep asking that shell. + const awaitsUserShell = listUserShells(inherited).length > 0; + const settled = ({ prepared, fromUserShell }: ShellDiscovery) => + fromUserShell || (prepared && !awaitsUserShell); + const refresh = probe(STARTUP_PROBE).pipe( Effect.onExit((exit) => Deferred.done(discovered, exit)), + Effect.flatMap((discovery) => + settled(discovery) + ? Effect.void + : Effect.sleep(DISCOVERY_RETRY_DELAY).pipe( + Effect.andThen( + probe(RETRY_PROBE).pipe( + Effect.repeat({ + until: settled, + schedule: Schedule.spaced(DISCOVERY_RETRY_DELAY), + times: DISCOVERY_RETRIES - 1, + }), + ), + ), + ), + ), ); const installIntoProcess = yield* Effect.cached( Effect.gen(function* () { diff --git a/apps/desktop/src/updates/DesktopRemoteUpdates.test.ts b/apps/desktop/src/updates/DesktopRemoteUpdates.test.ts index a489a64b4fcb8..fdac65f86a595 100644 --- a/apps/desktop/src/updates/DesktopRemoteUpdates.test.ts +++ b/apps/desktop/src/updates/DesktopRemoteUpdates.test.ts @@ -757,7 +757,7 @@ describe("DesktopRemoteUpdates", () => { const backgroundCheck = yield* updates.check("poll").pipe(Effect.forkChild); yield* Deferred.await(backgroundCheckStarted); - assert.equal((yield* updates.getState).status, "checking"); + assert.isTrue(yield* updates.isActionActive); yield* Queue.offer(commits, { version: 1, @@ -767,7 +767,6 @@ describe("DesktopRemoteUpdates", () => { yield* settle; assert.equal(harness.quitAndInstalls(), 0); - harness.emit("update-downloaded", { version: "1.2.4" }); yield* Deferred.succeed(releaseBackgroundCheck, undefined); yield* Fiber.join(backgroundCheck); yield* settle; diff --git a/apps/desktop/src/updates/DesktopUpdates.test.ts b/apps/desktop/src/updates/DesktopUpdates.test.ts index 7ee2ff5dd51c1..da08e427235aa 100644 --- a/apps/desktop/src/updates/DesktopUpdates.test.ts +++ b/apps/desktop/src/updates/DesktopUpdates.test.ts @@ -125,7 +125,7 @@ describe("DesktopUpdates", () => { ).pipe(Effect.provide(harness.layer)); }); - it.effect("checks for newer releases after an update has been downloaded", () => { + it.effect("re-checks an offered update without announcing it again", () => { const harness = makeHarness(); return Effect.scoped( @@ -138,14 +138,23 @@ describe("DesktopUpdates", () => { releaseNotes: "## What's changed\n- fix: queued update", }); yield* flushCallbacks; + const offeredStates = harness.sentStates.length; + + yield* updates.check("poll"); + harness.emit("update-available", { version: "1.2.4" }); + yield* flushCallbacks; + assert.equal(harness.sentStates.length, offeredStates); + harness.emit("update-downloaded", { version: "1.2.4" }); yield* flushCallbacks; + const downloadedStates = harness.sentStates.length; const result = yield* updates.check("poll"); assert.isTrue(result.checked); harness.emit("update-available", { version: "1.2.4" }); yield* flushCallbacks; + assert.equal(harness.sentStates.length, downloadedStates); const unchangedState = yield* updates.getState; assert.equal(unchangedState.status, "downloaded"); @@ -267,15 +276,26 @@ describe("DesktopUpdates", () => { ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer))); }); - it.effect( - "rejects install while a refresh check is in progress and releases the reservation", - () => + it.effect.each([ + { action: "download", offer: "update-available", found: null, accepted: true }, + { action: "install", offer: "update-downloaded", found: null, accepted: true }, + { action: "download", offer: "update-available", found: "1.2.5", accepted: true }, + { action: "install", offer: "update-downloaded", found: "1.2.5", accepted: false }, + ] as const)( + "a $action waiting out a refresh check acts on what it found ($found)", + ({ action, offer, found, accepted }) => Effect.gen(function* () { const checkStarted = yield* Deferred.make(); const releaseCheck = yield* Deferred.make(); const harness = makeHarness({ checkForUpdates: Deferred.succeed(checkStarted, undefined).pipe( Effect.andThen(Deferred.await(releaseCheck)), + // electron-updater emits the check's outcome before its promise resolves. + Effect.andThen( + Effect.sync(() => { + if (found !== null) harness.emit("update-available", { version: found }); + }), + ), ), }); @@ -283,22 +303,20 @@ describe("DesktopUpdates", () => { Effect.gen(function* () { const updates = yield* DesktopUpdates.DesktopUpdates; yield* updates.configure; - harness.emit("update-downloaded", { version: "1.2.4" }); + harness.emit(offer, { version: "1.2.4" }); yield* flushCallbacks; - const checkFiber = yield* updates.check("manual").pipe(Effect.forkScoped); + const checkFiber = yield* updates.check("poll").pipe(Effect.forkScoped); yield* Deferred.await(checkStarted); - - const installResult = yield* updates.install; - assert.isFalse(installResult.accepted); + const actionFiber = yield* updates[action].pipe(Effect.forkScoped); + yield* flushCallbacks; yield* Deferred.succeed(releaseCheck, undefined); - const checkResult = yield* Fiber.join(checkFiber); - assert.isTrue(checkResult.checked); - - const followUpCheck = yield* updates.check("manual"); - assert.isTrue(followUpCheck.checked); - assert.equal(harness.checkCount(), 2); + assert.isTrue((yield* Fiber.join(checkFiber)).checked); + assert.equal((yield* Fiber.join(actionFiber)).accepted, accepted); + const state = yield* updates.getState; + assert.equal(state.availableVersion, found ?? "1.2.4"); + if (action === "download") assert.equal(state.status, "downloading"); }), ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer))); }), diff --git a/apps/desktop/src/updates/DesktopUpdates.ts b/apps/desktop/src/updates/DesktopUpdates.ts index db31e0bc112ba..055c6574391a6 100644 --- a/apps/desktop/src/updates/DesktopUpdates.ts +++ b/apps/desktop/src/updates/DesktopUpdates.ts @@ -63,7 +63,7 @@ const CHANNEL_CHANGE_RETRY_DELAY = Duration.seconds(1); const CHANNEL_CHANGE_RETRIES = 30; const AUTO_UPDATE_STARTUP_DELAY = "15 seconds"; const AUTO_UPDATE_POLL_INTERVAL = "4 hours"; -const PREPARED_INSTALL_CHECK_WAIT = Duration.seconds(90); +const UPDATE_CHECK_WAIT = Duration.seconds(90); type UpdateAction = "check" | "download" | "install" | "install-recovery" | "channel"; @@ -318,6 +318,10 @@ function getCanRetryFromState(state: DesktopUpdateState): boolean { return state.availableVersion !== null || state.downloadedVersion !== null; } +function isOffered(state: DesktopUpdateState): boolean { + return state.status === "available" || state.status === "downloaded"; +} + function shouldBroadcastDownloadProgress( currentState: DesktopUpdateState, nextPercent: number, @@ -518,6 +522,23 @@ export const make = Effect.gen(function* () { ), ); + // Re-runs admit after each finished action, so a caller waiting on a check decides on its result. + const admitAfterCheck = Effect.fn("desktop.updates.admitAfterCheck")(function* ( + admit: Effect.Effect<"admitted" | "refused" | "wait-for-check">, + ) { + const actionCompletions = yield* PubSub.subscribe(finishedUpdateActions); + let admission = yield* stateMutex.withPermits(1)(admit); + while (admission === "wait-for-check") { + const finishedAction = yield* PubSub.take(actionCompletions).pipe( + Effect.timeoutOption(UPDATE_CHECK_WAIT), + ); + admission = Option.isNone(finishedAction) + ? "refused" + : yield* stateMutex.withPermits(1)(admit); + } + return admission; + }); + const applyAutoUpdaterChannel = Effect.fn("desktop.updates.applyAutoUpdaterChannel")(function* ( channel: DesktopUpdateChannel, ) { @@ -559,8 +580,10 @@ export const make = Effect.gen(function* () { if (actionReservation === "acquire" && !(yield* tryStartUpdateAction("check"))) return false; const check = Effect.gen(function* () { - const checkedAt = yield* currentIsoTimestamp; - yield* setState(reduceDesktopUpdateStateOnCheckStart(state, checkedAt)); + // An offer stays on screen while re-checking, so finding it again changes nothing. + if (!isOffered(state)) { + yield* setState(reduceDesktopUpdateStateOnCheckStart(state, yield* currentIsoTimestamp)); + } yield* logUpdaterInfo("checking for updates", { reason }); // The flag is shared updater state, so it flips only while this check holds the reservation. @@ -597,15 +620,30 @@ export const make = Effect.gen(function* () { }); const downloadAvailableUpdate = Effect.gen(function* () { - const state = yield* Ref.get(updateStateRef); - if (!(yield* Ref.get(updaterConfiguredRef)) || state.status !== "available") { - return { accepted: false, completed: false }; - } - - if (!(yield* tryStartUpdateAction("download"))) { + const admission = yield* Effect.scoped( + admitAfterCheck( + Effect.gen(function* () { + const state = yield* Ref.get(updateStateRef); + if (!(yield* Ref.get(updaterConfiguredRef)) || state.status !== "available") { + return "refused" as const; + } + const activeAction = yield* Ref.get(activeUpdateActionRef); + if (Option.isSome(activeAction)) { + return activeAction.value === "check" + ? ("wait-for-check" as const) + : ("refused" as const); + } + return (yield* tryStartUpdateAction("download")) + ? ("admitted" as const) + : ("refused" as const); + }), + ), + ); + if (admission === "refused") { return { accepted: false, completed: false }; } + const state = yield* Ref.get(updateStateRef); return yield* Effect.gen(function* () { yield* setState(reduceDesktopUpdateStateOnDownloadStart(state)); yield* electronUpdater.setDisableDifferentialDownload( @@ -798,47 +836,35 @@ export const make = Effect.gen(function* () { const installDownloadedUpdate = (expectedVersion?: string) => Effect.scoped( Effect.gen(function* () { - const actionCompletions = yield* PubSub.subscribe(finishedUpdateActions); - let admission: "admitted" | "refused" | "wait-for-check" = "wait-for-check"; - while (admission === "wait-for-check") { - admission = yield* stateMutex.withPermits(1)( - Effect.gen(function* () { - const state = yield* Ref.get(updateStateRef); - const activeAction = yield* Ref.get(activeUpdateActionRef); - const hasExpectedDownload = - state.downloadedVersion !== null && - (expectedVersion === undefined || state.downloadedVersion === expectedVersion); - if ( - (yield* Ref.get(desktopState.quitting)) || - !(yield* Ref.get(updaterConfiguredRef)) || - !hasExpectedDownload - ) { - return "refused" as const; - } - if (Option.isSome(activeAction)) { - return activeAction.value === "check" && expectedVersion !== undefined - ? ("wait-for-check" as const) - : ("refused" as const); - } - const hasInstallableDownload = - state.status === "downloaded" || - (state.status === "error" && - (state.errorContext === null || state.errorContext === "install")); - if (!hasInstallableDownload) return "refused" as const; - return (yield* tryStartUpdateAction("install")) - ? ("admitted" as const) + const admission = yield* admitAfterCheck( + Effect.gen(function* () { + const state = yield* Ref.get(updateStateRef); + const activeAction = yield* Ref.get(activeUpdateActionRef); + const hasExpectedDownload = + state.downloadedVersion !== null && + (expectedVersion === undefined || state.downloadedVersion === expectedVersion); + if ( + (yield* Ref.get(desktopState.quitting)) || + !(yield* Ref.get(updaterConfiguredRef)) || + !hasExpectedDownload + ) { + return "refused" as const; + } + if (Option.isSome(activeAction)) { + return activeAction.value === "check" + ? ("wait-for-check" as const) : ("refused" as const); - }), - ); - if (admission === "wait-for-check") { - const finishedAction = yield* PubSub.take(actionCompletions).pipe( - Effect.timeoutOption(PREPARED_INSTALL_CHECK_WAIT), - ); - if (Option.isNone(finishedAction)) { - admission = "refused"; } - } - } + const hasInstallableDownload = + state.status === "downloaded" || + (state.status === "error" && + (state.errorContext === null || state.errorContext === "install")); + if (!hasInstallableDownload) return "refused" as const; + return (yield* tryStartUpdateAction("install")) + ? ("admitted" as const) + : ("refused" as const); + }), + ); if (admission === "refused") { return { accepted: false, completed: false, failed: false }; } @@ -982,6 +1008,7 @@ export const make = Effect.gen(function* () { yield* Ref.set(lastLoggedDownloadMilestoneRef, -1); return; } + if (isOffered(state) && state.availableVersion === info.version) return; const checkedAt = yield* currentIsoTimestamp; const { releaseNotes, omittedReleaseCount } = normalizeDesktopUpdateReleaseNotes( @@ -1161,6 +1188,8 @@ export const make = Effect.gen(function* () { ), configure: Effect.gen(function* () { const context = yield* Effect.context(); + // Runs synchronously up to the first await, so a check's outcome is applied before the + // check's promise resolves and wakes the actions waiting on it. const runEffect = (effect: Effect.Effect) => { void Effect.runPromiseWith(context)(effect); }; diff --git a/apps/desktop/src/window/DesktopApplicationMenu.test.ts b/apps/desktop/src/window/DesktopApplicationMenu.test.ts index 612ec441ba99b..46004ca302295 100644 --- a/apps/desktop/src/window/DesktopApplicationMenu.test.ts +++ b/apps/desktop/src/window/DesktopApplicationMenu.test.ts @@ -3,7 +3,9 @@ import { assert, describe, it } from "@effect/vitest"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import type { DesktopUpdateCheckResult, DesktopUpdateState } from "@t3tools/contracts"; import * as Electron from "electron"; import { vi } from "vite-plus/test"; @@ -18,6 +20,7 @@ import * as DesktopApplicationMenu from "./DesktopApplicationMenu.ts"; import * as DesktopConfig from "../app/DesktopConfig.ts"; import * as DesktopEnvironment from "../app/DesktopEnvironment.ts"; import * as DesktopUpdates from "../updates/DesktopUpdates.ts"; +import { createInitialDesktopUpdateState } from "../updates/updateMachine.ts"; import * as DesktopWindow from "./DesktopWindow.ts"; const environmentInput = { @@ -56,27 +59,37 @@ const layerElectronApp = Layer.succeed(ElectronApp.ElectronApp, { on: () => Effect.void, } satisfies ElectronApp.ElectronApp["Service"]); -const layerElectronDialog = Layer.succeed(ElectronDialog.ElectronDialog, { - pickFolder: () => Effect.succeedNone, - pickFiles: () => Effect.succeed([]), - showMessageBox: () => Effect.succeed({ response: 0, checkboxChecked: false }), - showErrorBox: () => Effect.void, -} satisfies ElectronDialog.ElectronDialog["Service"]); - -const layerDesktopUpdates = Layer.succeed(DesktopUpdates.DesktopUpdates, { - getState: Effect.die("unexpected getState"), - isActionActive: Effect.succeed(false), - isInstallActive: Effect.succeed(false), - subscribe: Effect.die("unexpected subscribe"), - emitState: Effect.void, - disabledReason: Effect.succeedNone, - configure: Effect.void, - setChannel: () => Effect.die("unexpected setChannel"), - check: () => Effect.die("unexpected check"), - download: Effect.die("unexpected download"), - install: Effect.die("unexpected install"), - installPrepared: () => Effect.die("unexpected installPrepared"), -} satisfies DesktopUpdates.DesktopUpdates["Service"]); +interface MenuServices { + readonly checkResult?: DesktopUpdateCheckResult; + readonly shownMessageBox?: Deferred.Deferred; +} + +const layerElectronDialog = ({ shownMessageBox }: MenuServices) => + Layer.succeed(ElectronDialog.ElectronDialog, { + pickFolder: () => Effect.succeedNone, + pickFiles: () => Effect.succeed([]), + showMessageBox: (options) => + (shownMessageBox ? Deferred.succeed(shownMessageBox, options) : Effect.void).pipe( + Effect.as({ response: options.cancelId ?? 0, checkboxChecked: false }), + ), + showErrorBox: () => Effect.void, + } satisfies ElectronDialog.ElectronDialog["Service"]); + +const layerDesktopUpdates = ({ checkResult }: MenuServices) => + Layer.succeed(DesktopUpdates.DesktopUpdates, { + getState: Effect.die("unexpected getState"), + isActionActive: Effect.succeed(false), + isInstallActive: Effect.succeed(false), + subscribe: Effect.die("unexpected subscribe"), + emitState: Effect.void, + disabledReason: Effect.succeedNone, + configure: Effect.void, + setChannel: () => Effect.die("unexpected setChannel"), + check: () => (checkResult ? Effect.succeed(checkResult) : Effect.die("unexpected check")), + download: Effect.die("unexpected download"), + install: Effect.die("unexpected install"), + installPrepared: () => Effect.die("unexpected installPrepared"), + } satisfies DesktopUpdates.DesktopUpdates["Service"]); const layerDesktopWindow = (selectedAction: Deferred.Deferred) => Layer.succeed(DesktopWindow.DesktopWindow, { @@ -113,6 +126,7 @@ const configureMenu = ( selectedAction: Deferred.Deferred, applicationMenuTemplate: Deferred.Deferred, environment: Partial = {}, + services: MenuServices = {}, ) => Effect.gen(function* () { const menu = yield* DesktopApplicationMenu.DesktopApplicationMenu; @@ -122,8 +136,8 @@ const configureMenu = ( DesktopApplicationMenu.layer.pipe( Layer.provideMerge(layerElectronMenu(applicationMenuTemplate)), Layer.provideMerge(layerDesktopWindow(selectedAction)), - Layer.provideMerge(layerDesktopUpdates), - Layer.provideMerge(layerElectronDialog), + Layer.provideMerge(layerDesktopUpdates(services)), + Layer.provideMerge(layerElectronDialog(services)), Layer.provideMerge(layerElectronApp), Layer.provideMerge( DesktopEnvironment.layer({ ...environmentInput, ...environment }).pipe( @@ -134,6 +148,54 @@ const configureMenu = ( ), ); +const checkForUpdatesFromMacMenu = (state: Partial) => + Effect.gen(function* () { + const applicationMenuTemplate = + yield* Deferred.make(); + const shownMessageBox = yield* Deferred.make(); + yield* configureMenu( + yield* Deferred.make(), + applicationMenuTemplate, + { platform: "darwin" }, + { + checkResult: { + checked: true, + state: { + ...createInitialDesktopUpdateState( + "0.1.5", + { hostArch: "arm64", appArch: "arm64", runningUnderArm64Translation: false }, + "latest", + ), + enabled: true, + ...state, + }, + }, + shownMessageBox, + }, + ); + + const appMenu = (yield* Deferred.await(applicationMenuTemplate))[0]; + if (!Array.isArray(appMenu?.submenu)) { + throw new Error("Expected the macOS app menu submenu to be an array."); + } + const checkForUpdates = appMenu.submenu.find((item) => item.label === "Check for Updates..."); + if (typeof checkForUpdates?.click !== "function") { + throw new Error("Expected Check for Updates... menu item to have a click handler."); + } + + // Every stub completes synchronously, so the menu action has finished when click returns. + checkForUpdates.click( + {} as Electron.MenuItem, + {} as Electron.BrowserWindow, + {} as KeyboardEvent, + ); + const dialog = yield* Deferred.poll(shownMessageBox); + if (Option.isNone(dialog)) { + throw new Error("Check for Updates... finished without showing any dialog."); + } + return yield* dialog.value; + }); + describe("DesktopApplicationMenu", () => { it.effect("leaves the accelerator to Chromium instead of injecting a paste", () => Effect.gen(function* () { @@ -285,4 +347,25 @@ describe("DesktopApplicationMenu", () => { assert.equal(yield* Deferred.await(selectedAction), "main-reload"); }), ); + it.effect("tells the user which update the menu check found", () => + Effect.gen(function* () { + const dialog = yield* checkForUpdatesFromMacMenu({ + status: "available", + availableVersion: "0.1.7", + }); + assert.include(`${dialog.title ?? ""} ${dialog.message} ${dialog.detail ?? ""}`, "0.1.7"); + }), + ); + + it.effect("tells the user a downloaded update is ready when the menu check runs", () => + Effect.gen(function* () { + const dialog = yield* checkForUpdatesFromMacMenu({ + status: "downloaded", + availableVersion: "0.1.7", + downloadedVersion: "0.1.7", + downloadPercent: 100, + }); + assert.include(`${dialog.title ?? ""} ${dialog.message} ${dialog.detail ?? ""}`, "0.1.7"); + }), + ); }); diff --git a/apps/desktop/src/window/DesktopApplicationMenu.ts b/apps/desktop/src/window/DesktopApplicationMenu.ts index 44d2c234f8358..b4025ebfde8ef 100644 --- a/apps/desktop/src/window/DesktopApplicationMenu.ts +++ b/apps/desktop/src/window/DesktopApplicationMenu.ts @@ -64,6 +64,9 @@ const runMainContentsCommand = Effect.fn("desktop.menu.runMainContentsCommand")( yield* desktopWindow.runMainContentsCommand(command); }); +const describeUpdate = (version: string | null) => + version === null ? "A new version of T3 Code" : `T3 Code ${version}`; + const checkForUpdatesFromMenu = Effect.gen(function* () { const updates = yield* DesktopUpdates.DesktopUpdates; const electronDialog = yield* ElectronDialog.ElectronDialog; @@ -77,6 +80,35 @@ const checkForUpdatesFromMenu = Effect.gen(function* () { message: `T3 Code ${updateState.currentVersion} is currently the newest version available.`, buttons: ["OK"], }); + } else if (updateState.status === "available") { + const { response } = yield* electronDialog.showMessageBox({ + type: "info", + title: "Update available", + message: `${describeUpdate(updateState.availableVersion)} is available.`, + detail: `You're running T3 Code ${updateState.currentVersion}.`, + buttons: ["Download", "Later"], + defaultId: 0, + cancelId: 1, + }); + if (response === 0) yield* updates.download; + } else if (updateState.status === "downloading") { + yield* electronDialog.showMessageBox({ + type: "info", + title: "Update downloading", + message: `${describeUpdate(updateState.availableVersion)} is already downloading.`, + buttons: ["OK"], + }); + } else if (updateState.status === "downloaded") { + const { response } = yield* electronDialog.showMessageBox({ + type: "info", + title: "Update ready", + message: `${describeUpdate(updateState.downloadedVersion ?? updateState.availableVersion)} is ready to install.`, + detail: "T3 Code will restart to install it. Any running tasks will be interrupted.", + buttons: ["Restart", "Later"], + defaultId: 0, + cancelId: 1, + }); + if (response === 0) yield* updates.install; } else if (updateState.status === "error") { yield* electronDialog.showMessageBox({ type: "warning", diff --git a/apps/marketing/src/pages/[...locale]/index.astro b/apps/marketing/src/pages/[...locale]/index.astro index 3d8d44568d448..e8f4b5f1b5fa5 100644 --- a/apps/marketing/src/pages/[...locale]/index.astro +++ b/apps/marketing/src/pages/[...locale]/index.astro @@ -1234,6 +1234,8 @@ const mobileEndorsementRows = [ section { padding: 56px 0; } .sec-cta { padding: 80px 0; } .container { padding-left: 20px; padding-right: 20px; } + /* A nowrap tag widens its column past the grid, which then clips the other column. */ + .harness-tag { white-space: normal; } .endorsements-head { margin-bottom: 40px; } @@ -1265,4 +1267,8 @@ const mobileEndorsementRows = [ font-size: 11px; } } + + @media (max-width: 360px) { + .harness { padding-left: 12px; padding-right: 12px; } + } diff --git a/apps/mobile/modules/t3-native-controls/ios/T3NativeControlsModule.swift b/apps/mobile/modules/t3-native-controls/ios/T3NativeControlsModule.swift index af67e80afebb4..5b3d84aedcee3 100644 --- a/apps/mobile/modules/t3-native-controls/ios/T3NativeControlsModule.swift +++ b/apps/mobile/modules/t3-native-controls/ios/T3NativeControlsModule.swift @@ -10,6 +10,9 @@ public final class T3NativeControlsModule: Module { private let presentationSources = T3PresentationSources() private var videoPresentation: T3NativeVideoPresentation? private var filePresentation: T3NativeFilePresentation? + /// The last file preview that closed. Written on main, read synchronously from JS. + private let filePreviewActivity = NSLock() + private var finishedFilePreview: String? public func definition() -> ModuleDefinition { Events("videoPlaybackChange") @@ -94,6 +97,12 @@ public final class T3NativeControlsModule: Module { file.present(urls: urls, titles: titles, selectedIndex: selectedIndex, from: presenter) }.runOnQueue(.main) + // A tap can reach JS before the old viewer's close does; this tells it whether that viewer is gone. + // A presentation main has not started yet reads as still open. + Function("isFilePreviewFinished") { (identifier: String) -> Bool in + self.filePreviewActivity.withLock { self.finishedFilePreview == identifier } + } + // A nil URL marks the item as one that could not be resolved. AsyncFunction("updateFile") { (identifier: String, index: Int, url: URL?) in if self.filePresentation?.identifier == identifier { self.filePresentation?.update(index: index, url: url) } @@ -294,15 +303,22 @@ public final class T3NativeControlsModule: Module { guard filePresentation == nil, videoPresentation == nil, appContext?.utilities?.currentViewController() != nil else { throw URLError(.cannotLoadFromNetwork) } - let file = T3NativeFilePresentation(identifier: identifier, sources: presentationSources, - sourceIdentifiers: sourceIdentifiers) { [weak self] error in - self?.filePresentation = nil - if let error { promise.reject(error) } else { promise.resolve(nil) } - } + let file = T3NativeFilePresentation( + identifier: identifier, sources: presentationSources, sourceIdentifiers: sourceIdentifiers, + onFinish: { [weak self] in self?.setFinishedFilePreview(identifier) }, + completion: { [weak self] error in + self?.filePresentation = nil + if let error { promise.reject(error) } else { promise.resolve(nil) } + } + ) filePresentation = file return file } + private func setFinishedFilePreview(_ identifier: String) { + filePreviewActivity.withLock { finishedFilePreview = identifier } + } + private func presentFile(url: URL, title: String, sourceIdentifier: String, identifier: String, promise: Promise) throws { let file = try makeFilePresentation(sourceIdentifiers: [sourceIdentifier], identifier: identifier, promise: promise) diff --git a/apps/mobile/modules/t3-native-controls/ios/T3NativeFilePresentation.swift b/apps/mobile/modules/t3-native-controls/ios/T3NativeFilePresentation.swift index 791e39b2840c0..979e87edc1b0e 100644 --- a/apps/mobile/modules/t3-native-controls/ios/T3NativeFilePresentation.swift +++ b/apps/mobile/modules/t3-native-controls/ios/T3NativeFilePresentation.swift @@ -8,232 +8,217 @@ private final class FilePreviewItem: NSObject, QLPreviewItem { var previewItemTitle: String? } -private enum FilePreviewState { case loading, ready, failed } - private final class FilePreviewController: QLPreviewController { var onAppear: (() -> Void)? - // Quick Look shows a blank page for an item without a file, so loading and failure are ours to show. - private let spinner = UIActivityIndicatorView(style: .large) - private let failure = UILabel() - var state = FilePreviewState.ready { - didSet { if isViewLoaded { showState() } } - } - - override func viewDidLoad() { - super.viewDidLoad() - failure.text = "This image could not be loaded." - failure.textColor = .secondaryLabel - failure.textAlignment = .center - failure.numberOfLines = 0 - for status in [spinner, failure] as [UIView] { - status.isUserInteractionEnabled = false - status.translatesAutoresizingMaskIntoConstraints = false - view.addSubview(status) - NSLayoutConstraint.activate([ - status.centerXAnchor.constraint(equalTo: view.centerXAnchor), - status.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: 64), - status.widthAnchor.constraint(lessThanOrEqualTo: view.widthAnchor, constant: -48), - ]) - } - showState() - } - - override func viewDidLayoutSubviews() { - super.viewDidLayoutSubviews() - view.bringSubviewToFront(spinner) - view.bringSubviewToFront(failure) - } + var onDismiss: (() -> Void)? override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) onAppear?() } - private func showState() { - if state == .loading { spinner.startAnimating() } else { spinner.stopAnimating() } - failure.isHidden = state != .failed + // Quick Look's own didDismiss callback can lag well behind the screen being tappable again, + // so a tap on the thumbnail in that gap would land while JS still thinks the viewer is open. + override func viewDidDisappear(_ animated: Bool) { + super.viewDidDisappear(animated) + if isBeingDismissed { onDismiss?() } } } +/// How long the gallery waits for siblings once the selected file is ready; later ones are left out. +private let siblingGraceNanoseconds: UInt64 = 1_000_000_000 +/// A load faster than this zooms straight from the thumbnail without a spinner. +private let spinnerDelayNanoseconds: UInt64 = 250_000_000 + +/// Quick Look only ever receives pages whose file is on disk: a page refreshed after it first +/// rendered blank keeps a stale scroll offset, so drags scroll the image instead of paging or dismissing. final class T3NativeFilePresentation: NSObject, QLPreviewControllerDataSource, QLPreviewControllerDelegate, UIAdaptivePresentationControllerDelegate { let identifier: String private var controller: FilePreviewController? private let completion: (Error?) -> Void + private let onFinish: () -> Void private weak var sources: T3PresentationSources? private let sourceIdentifiers: [String] - private var items: [FilePreviewItem] = [] + private var titles: [String] = [] private var urls: [URL?] = [] - private var states: [FilePreviewState] = [] + /// A prepared file, or nil while loading or after failing; `settled` tells those apart. + private var files: [URL?] = [] + private var settled: [Bool] = [] + private var downloads: [Int: Task] = [:] private var selectedIndex = 0 + /// The pages Quick Look shows, as indices into `files`. + private var pages: [Int] = [] + private var items: [FilePreviewItem] = [] private weak var presenter: UIViewController? - /// Files that arrived while their page was off screen; Quick Look may still hold the blank page. - private var staleIndices = Set() - private var currentIndexObservation: NSKeyValueObservation? - private var download: (index: Int, task: Task)? - private var placeholder: Task? + private var grace: Task? + private var spinnerDelay: Task? + private var spinner: UIView? private var openError: Error? private var dismissRequested = false private var finished = false init(identifier: String, sources: T3PresentationSources, sourceIdentifiers: [String], - completion: @escaping (Error?) -> Void) { + onFinish: @escaping () -> Void, completion: @escaping (Error?) -> Void) { self.identifier = identifier self.sources = sources self.sourceIdentifiers = sourceIdentifiers + self.onFinish = onFinish self.completion = completion super.init() } /// Downloads the file before presenting so Quick Look can refuse a format the caller should share instead. func present(url: URL, title: String, from presenter: UIViewController) { - load(urls: [url], titles: [title], selectedIndex: 0, from: presenter, opensWhileLoading: false) + present(urls: [url], titles: [title], selectedIndex: 0, from: presenter) } - /// Opens the selected image once it is ready, or a loading page if it is slow, and loads the rest - /// of the gallery behind it so a slow or broken sibling never holds the viewer back. + /// Loads the gallery in parallel and opens once the selected file is ready, with whichever + /// siblings are ready by the end of a short grace, so a slow or broken one never holds it back. func present(urls: [URL?], titles: [String], selectedIndex: Int, from presenter: UIViewController) { - load(urls: urls, titles: titles, selectedIndex: selectedIndex, from: presenter, opensWhileLoading: true) + self.titles = titles + self.urls = urls + self.selectedIndex = selectedIndex + self.presenter = presenter + files = Array(repeating: nil, count: urls.count) + settled = Array(repeating: false, count: urls.count) + spinnerDelay = Task { @MainActor [self] in + try? await Task.sleep(nanoseconds: spinnerDelayNanoseconds) + guard !Task.isCancelled else { return } + showSpinner() + } + for index in urls.indices { download(index) } } /// Delivers a URL that was still resolving when the gallery opened, or nil when it never will. func update(index: Int, url: URL?) { - guard !finished, urls.indices.contains(index), urls[index] == nil, states[index] == .loading else { return } + guard !finished, controller == nil, urls.indices.contains(index), urls[index] == nil, + !settled[index] + else { return } guard let url else { - failed(index, error: URLError(.resourceUnavailable)) + settle(index, result: .failure(URLError(.resourceUnavailable))) return } urls[index] = url - loadNext() - } - - private func load(urls: [URL?], titles: [String], selectedIndex: Int, from presenter: UIViewController, - opensWhileLoading: Bool) { - items = titles.map { title in - let item = FilePreviewItem() - item.previewItemTitle = title - return item - } - self.urls = urls - self.selectedIndex = selectedIndex - self.presenter = presenter - states = Array(repeating: .loading, count: urls.count) - if opensWhileLoading { - // A short grace keeps the zoom from the thumbnail into a loaded image when the file is quick. - placeholder = Task { @MainActor [self] in - try? await Task.sleep(nanoseconds: 250_000_000) - guard !Task.isCancelled, !finished, controller == nil else { return } - show() - } - } - loadNext() + download(index) } - /// Downloads one file at a time, nearest the page on screen first. The page on screen takes over - /// from a background download, which restarts later. - private func loadNext() { - guard !finished, !dismissRequested else { return } - let current = controller?.currentPreviewItemIndex ?? selectedIndex - guard let next = urls.indices - .filter({ urls[$0] != nil && states[$0] == .loading }) - .min(by: { abs($0 - current) < abs($1 - current) }) - else { return } - if let download { - guard next == current, download.index != current else { return } - download.task.cancel() - } - guard let url = urls[next] else { return } - let title = items[next].previewItemTitle ?? "" - let task = Task { @MainActor [self] in + private func download(_ index: Int) { + guard let url = urls[index], downloads[index] == nil else { return } + let title = titles[index] + downloads[index] = Task { @MainActor [self] in let result: Result do { result = .success(try await Self.prepareFile(url: url, title: title)) } catch { result = .failure(error) } - guard !finished, !Task.isCancelled else { - if case .success(let file) = result { - try? FileManager.default.removeItem(at: file.deletingLastPathComponent()) - } - return - } - download = nil - switch result { - case .success(let file): loaded(next, file: file) - case .failure(let error): failed(next, error: error) - } - loadNext() + downloads[index] = nil + settle(index, result: result) } - download = (next, task) } - private func loaded(_ index: Int, file: URL) { - // Quick Look knows which formats it renders; refuse before presenting so the caller - // can fall back instead of showing an "unsupported format" page. - guard QLPreviewController.canPreview(file as NSURL) else { - try? FileManager.default.removeItem(at: file.deletingLastPathComponent()) - failed(index, error: NSError( - domain: "T3NativePresentation", - code: 3, - userInfo: [NSLocalizedDescriptionKey: "This file type cannot be previewed on this device."] - )) + private func settle(_ index: Int, result: Result) { + guard !finished, controller == nil, !dismissRequested else { + if case .success(let file) = result { Self.remove(file) } return } - items[index].previewItemURL = file - states[index] = .ready - if controller != nil { refresh(index) } else if index == selectedIndex { show() } - } - - private func failed(_ index: Int, error: Error) { - guard index != selectedIndex else { + settled[index] = true + if let error = store(index, result: result), index == selectedIndex { openError = error dismiss() return } - states[index] = .failed - refresh(index) + guard files[selectedIndex] != nil else { return } + if settled.allSatisfy({ $0 }) { + show() + } else if grace == nil { + grace = Task { @MainActor [self] in + try? await Task.sleep(nanoseconds: siblingGraceNanoseconds) + guard !Task.isCancelled else { return } + show() + } + } + } + + private func store(_ index: Int, result: Result) -> Error? { + switch result { + case .success(let file): + // Quick Look knows which formats it renders; refuse before presenting so the caller + // can fall back instead of showing an "unsupported format" page. + guard QLPreviewController.canPreview(file as NSURL) else { + Self.remove(file) + return NSError( + domain: "T3NativePresentation", + code: 3, + userInfo: [NSLocalizedDescriptionKey: "This file type cannot be previewed on this device."] + ) + } + files[index] = file + return nil + case .failure(let error): + return error + } } private func show() { + guard !finished, controller == nil, !dismissRequested else { return } guard let presenter else { finish(); return } - placeholder?.cancel() + cancelLoading() + pages = files.indices.filter { files[$0] != nil } + items = pages.map { index in + let item = FilePreviewItem() + item.previewItemURL = files[index] + item.previewItemTitle = titles[index] + return item + } let preview = FilePreviewController() preview.delegate = self preview.dataSource = self - preview.currentPreviewItemIndex = selectedIndex + preview.currentPreviewItemIndex = pages.firstIndex(of: selectedIndex) ?? 0 preview.onAppear = { [weak self] in self?.resumePendingDismissal() } + preview.onDismiss = { [weak self] in self?.finish() } controller = preview - preview.state = states[selectedIndex] - currentIndexObservation = preview.observe(\.currentPreviewItemIndex) { [weak self] _, _ in - DispatchQueue.main.async { self?.currentItemChanged() } - } presenter.present(preview, animated: !UIAccessibility.isReduceMotionEnabled) { [self] in resumePendingDismissal() } preview.presentationController?.delegate = self } - private func refresh(_ index: Int) { - guard let controller else { return } - guard controller.currentPreviewItemIndex == index else { - if states[index] == .ready { staleIndices.insert(index) } - return - } - if states[index] == .ready { controller.refreshCurrentPreviewItem() } - controller.state = states[index] + /// Shows over the tapped thumbnail that a slow open is on its way. + private func showSpinner() { + guard !finished, controller == nil, spinner == nil, + sourceIdentifiers.indices.contains(selectedIndex), + let source = sources?.view(for: sourceIdentifiers[selectedIndex]), + let window = source.window + else { return } + let backing = UIView(frame: CGRect(x: 0, y: 0, width: 44, height: 44)) + backing.backgroundColor = UIColor.black.withAlphaComponent(0.55) + backing.layer.cornerRadius = 22 + backing.isUserInteractionEnabled = false + let indicator = UIActivityIndicatorView(style: .medium) + indicator.color = .white + indicator.center = CGPoint(x: 22, y: 22) + indicator.startAnimating() + backing.addSubview(indicator) + backing.center = source.convert(CGPoint(x: source.bounds.midX, y: source.bounds.midY), to: window) + window.addSubview(backing) + spinner = backing } - private func currentItemChanged() { - guard !finished, let controller, states.indices.contains(controller.currentPreviewItemIndex) else { return } - let index = controller.currentPreviewItemIndex - if staleIndices.remove(index) != nil { controller.refreshCurrentPreviewItem() } - controller.state = states[index] - loadNext() + private func cancelLoading() { + for task in downloads.values { task.cancel() } + downloads.removeAll() + grace?.cancel() + grace = nil + spinnerDelay?.cancel() + spinnerDelay = nil + spinner?.removeFromSuperview() + spinner = nil } func dismiss() { dismissRequested = true - download?.task.cancel() guard !finished else { return } guard let controller else { finish(); return } // Drain Close from viewDidAppear after opening or cancelling an interactive dismissal. @@ -257,10 +242,10 @@ final class T3NativeFilePresentation: NSObject, QLPreviewControllerDataSource, private func sourceView(for item: QLPreviewItem) -> UIView? { guard !UIAccessibility.isReduceMotionEnabled, - let index = items.firstIndex(where: { $0 === item }), - sourceIdentifiers.indices.contains(index) + let page = items.firstIndex(where: { $0 === item }), + sourceIdentifiers.indices.contains(pages[page]) else { return nil } - return sources?.view(for: sourceIdentifiers[index]) + return sources?.view(for: sourceIdentifiers[pages[page]]) } func previewController(_ controller: QLPreviewController, transitionViewFor item: QLPreviewItem) -> UIView? { @@ -278,24 +263,20 @@ final class T3NativeFilePresentation: NSObject, QLPreviewControllerDataSource, func presentationControllerDidDismiss(_ presentationController: UIPresentationController) { finish() } - private func finish(error: Error? = nil) { + private func finish() { guard !finished else { return } finished = true - download?.task.cancel() - download = nil - placeholder?.cancel() - placeholder = nil - currentIndexObservation = nil - for item in items { - if let file = item.previewItemURL { - try? FileManager.default.removeItem(at: file.deletingLastPathComponent()) - } - } + cancelLoading() + for file in files.compactMap({ $0 }) { Self.remove(file) } + files.removeAll() items.removeAll() - urls.removeAll() - states.removeAll() - let result = error ?? openError - DispatchQueue.main.async { [completion] in completion(result) } + DispatchQueue.main.async { [completion, openError] in completion(openError) } + // After queueing the completion, so a new presentation JS starts on seeing this lands behind it. + onFinish() + } + + private static func remove(_ file: URL) { + try? FileManager.default.removeItem(at: file.deletingLastPathComponent()) } /// Copy original bytes so preview and sharing do not mutate a draft or workspace file. @@ -305,6 +286,7 @@ final class T3NativeFilePresentation: NSObject, QLPreviewControllerDataSource, try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) do { let download = directory.appendingPathComponent("original") + var mimeType: String? if url.isFileURL { try FileManager.default.copyItem(at: url, to: download) } else if url.scheme == "data" { @@ -317,6 +299,7 @@ final class T3NativeFilePresentation: NSObject, QLPreviewControllerDataSource, guard let response = response as? HTTPURLResponse, (200..<300).contains(response.statusCode) else { throw URLError(.badServerResponse) } + mimeType = response.mimeType try FileManager.default.moveItem(at: temporaryFile, to: download) } try Task.checkCancellation() @@ -330,7 +313,8 @@ final class T3NativeFilePresentation: NSObject, QLPreviewControllerDataSource, type = detectedType } else if CGPDFDocument(download as CFURL) != nil { type = .pdf - } else if originalExtension.lowercased() == "svg" { + } else if originalExtension.lowercased() == "svg" || mimeType == "image/svg+xml" { + // ImageIO cannot read SVG, and served images such as QR codes often have no extension. type = .svg } let fileExtension: String diff --git a/apps/mobile/src/components/ui/AndroidAnchoredMenu.android.tsx b/apps/mobile/src/components/ui/AndroidAnchoredMenu.android.tsx index a17e48c2604c7..f9e3b2ac01249 100644 --- a/apps/mobile/src/components/ui/AndroidAnchoredMenu.android.tsx +++ b/apps/mobile/src/components/ui/AndroidAnchoredMenu.android.tsx @@ -61,6 +61,10 @@ export function AndroidAnchoredMenu(props: AndroidAnchoredMenuProps) { setPath([]); setOverlay(null); }; + // The in-window menu is pinned to the trigger's spot above the keyboard, which is stale once it hides. + if (anchor?.keyboardWasVisible === true && !keyboardVisible) { + close(); + } const open = () => { anchorNode?.measureInWindow((x, y, width, height) => { diff --git a/apps/mobile/src/components/ui/FilePreviewModal.tsx b/apps/mobile/src/components/ui/FilePreviewModal.tsx index aff82eae479cd..eba89cdb28c9b 100644 --- a/apps/mobile/src/components/ui/FilePreviewModal.tsx +++ b/apps/mobile/src/components/ui/FilePreviewModal.tsx @@ -31,6 +31,7 @@ const NativeControls = requireNativeModule<{ ): Promise; updateFile(identifier: string, index: number, uri: string | null): Promise; dismissFile(identifier: string): Promise; + isFilePreviewFinished(identifier: string): boolean; }>("T3NativeControls"); // Null tells the viewer an image failed; undefined means its URL has not arrived yet. @@ -38,10 +39,11 @@ const nativeUri = (image: FilePreviewImage) => (image.failed ? null : image.uri) function NativeFilePreview(props: FilePreviewViewerProps) { const identifier = useId(); - // Later URLs reach the open viewer through updateFile instead of presenting again. + // Later URLs reach the native presentation through updateFile instead of presenting again. const [presented] = useState(props.source); const delivered = useRef<(string | null | undefined)[]>([]); const onRequestClose = useEffectEvent(props.onRequestClose); + const onPresent = useEffectEvent((isFinished: () => boolean) => props.onPresent?.(isFinished)); const onOpenError = useEffectEvent((error: unknown) => { if (props.onOpenError) props.onOpenError(error); else Dialog.alert("Could not open preview", "The file could not be loaded. Please try again."); @@ -51,7 +53,7 @@ function NativeFilePreview(props: FilePreviewViewerProps) { useEffect(() => { let canceled = false; let presentation: Promise; - // Images open while still loading; other files must download first so Quick Look can refuse them. + // Images hand over before every URL resolves; other files must download first so Quick Look can refuse them. if (presented.kind === "image") { const { images, selectedIndex } = presented; delivered.current = images.map((image) => image.uri); @@ -71,6 +73,7 @@ function NativeFilePreview(props: FilePreviewViewerProps) { identifier, ); } + onPresent(() => NativeControls.isFilePreviewFinished(identifier)); void presentation .catch((error: unknown) => { if (!canceled) onOpenError(error); diff --git a/apps/mobile/src/components/ui/FilePreviewModal.types.ts b/apps/mobile/src/components/ui/FilePreviewModal.types.ts index 37dd9ea9e16b0..4311776b0ad9e 100644 --- a/apps/mobile/src/components/ui/FilePreviewModal.types.ts +++ b/apps/mobile/src/components/ui/FilePreviewModal.types.ts @@ -54,4 +54,6 @@ export interface FilePreviewViewerProps { readonly source: ResolvedFilePreviewSource; readonly onRequestClose: () => void; readonly onOpenError?: (error: unknown) => void; + /** Called once the viewer hands its file to a native presentation, with a check for its close. */ + readonly onPresent?: (isFinished: () => boolean) => void; } diff --git a/apps/mobile/src/components/ui/FilePreviewSession.test.tsx b/apps/mobile/src/components/ui/FilePreviewSession.test.tsx index a5b51aa5cf4b3..8a38a70605cd6 100644 --- a/apps/mobile/src/components/ui/FilePreviewSession.test.tsx +++ b/apps/mobile/src/components/ui/FilePreviewSession.test.tsx @@ -1,4 +1,4 @@ -import { act, useState } from "react"; +import { act, useEffect, useState } from "react"; import { createRoot } from "react-dom/client"; import { expect, it, vi } from "vite-plus/test"; import { @@ -14,6 +14,7 @@ const harness = vi.hoisted(() => ({ alert: vi.fn(), previews: [] as unknown[], mounts: 0, + presentationFinished: false, })); vi.mock("../../state/assets", () => ({ refreshAssetUrl: harness.refreshAssetUrl })); @@ -32,6 +33,9 @@ import { FilePreviewSession } from "./FilePreviewSession"; function Viewer(props: FilePreviewViewerProps) { useState(() => harness.mounts++); harness.previews.push(props.source); + const { onPresent } = props; + // Stands in for the native presentation starting. + useEffect(() => onPresent?.(() => harness.presentationFinished), [onPresent]); return null; } @@ -171,3 +175,70 @@ it("names the checked path when the server cannot find the file", async () => { ); expect(harness.alert.mock.calls[0]?.[1]).not.toMatch(/reconnect/i); }); + +it.each([ + // Handed to native but not yet started there, or still on screen. + ["image", false, 1], + ["image", true, 2], + // A PDF is still resolving here, so its viewer never presented and a re-render must not restart it. + ["pdf", true, 1], +] as const)( + "a re-tap of the open %s restarts the preview only once its native viewer closed (closed: %s)", + async (kind, finished, starts) => { + (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + harness.presentationFinished = finished; + harness.mounts = 0; + harness.refreshAssetUrl.mockReset(); + if (kind === "image") harness.refreshAssetUrl.mockResolvedValue("https://signed.test/a.png"); + else harness.refreshAssetUrl.mockReturnValue(new Promise(() => {})); + const selected: FilePreviewItem = { ...image("https://github.com/a.png"), kind }; + const root = createRoot(document.createElement("div")); + await using _root = { [Symbol.asyncDispose]: () => act(async () => root.unmount()) }; + const render = () => + act(async () => + root.render( + {}} + progressiveGallery + Viewer={Viewer} + />, + ), + ); + await render(); + await render(); + expect(harness.refreshAssetUrl).toHaveBeenCalledTimes(starts); + }, +); + +it("does not carry a presented viewer over to a different item that is still resolving", async () => { + (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + harness.presentationFinished = true; + harness.refreshAssetUrl.mockReset(); + harness.refreshAssetUrl.mockImplementation((_environmentId, resource) => + resource.url.endsWith("a.png") + ? Promise.resolve("https://signed.test/a.png") + : new Promise(() => {}), + ); + const shown = image("https://github.com/a.png"); + const resolving: FilePreviewItem = { ...image("https://github.com/b.pdf"), kind: "pdf" }; + const root = createRoot(document.createElement("div")); + await using _root = { [Symbol.asyncDispose]: () => act(async () => root.unmount()) }; + const render = (item: FilePreviewItem) => + act(async () => + root.render( + {}} + progressiveGallery + Viewer={Viewer} + />, + ), + ); + await render(shown); + await render(resolving); + await render(resolving); + expect( + harness.refreshAssetUrl.mock.calls.filter(([, r]) => r.url.endsWith("b.pdf")), + ).toHaveLength(1); +}); diff --git a/apps/mobile/src/components/ui/FilePreviewSession.tsx b/apps/mobile/src/components/ui/FilePreviewSession.tsx index 5df8acf001e03..a7a60ce5555b4 100644 --- a/apps/mobile/src/components/ui/FilePreviewSession.tsx +++ b/apps/mobile/src/components/ui/FilePreviewSession.tsx @@ -97,6 +97,7 @@ function ResolvedFilePreview( readonly source: FilePreviewSource; readonly onRequestClose: () => void; readonly onOpenError?: (error: unknown) => void; + readonly onPresent: (isFinished: () => boolean) => void; }, ) { const { progressiveGallery, Viewer } = props; @@ -161,6 +162,7 @@ function ResolvedFilePreview( ); @@ -205,6 +207,7 @@ function ResolvedFilePreview( }} onRequestClose={props.onRequestClose} onOpenError={onOpenError} + onPresent={props.onPresent} /> ); } @@ -220,15 +223,43 @@ export function FilePreviewSession(props: FilePreviewModalProps & FilePreviewSes ? null : { ...props.source, gallery: filePreviewGallery(props.source, group) }; usePreviewPresentation(source && filePreviewKey(source), props.onRequestClose); + // A tap can land after the native viewer closed but before its close reached the caller, which + // still holds the same item; that tap only opens a new viewer under a new key. + // Only a viewer that presented and has since closed reopens; one still resolving never does. + const [opening, setOpening] = useState<{ + readonly source: FilePreviewModalProps["source"]; + readonly count: number; + readonly presented: { readonly isFinished: () => boolean } | null; + }>({ source: props.source, count: 0, presented: null }); + if (opening.source !== props.source) { + const sameItem = + opening.source !== null && + props.source !== null && + filePreviewKey(opening.source) === filePreviewKey(props.source); + const reopened = sameItem && opening.presented?.isFinished() === true; + setOpening({ + source: props.source, + count: opening.count + (reopened ? 1 : 0), + presented: sameItem && !reopened ? opening.presented : null, + }); + } + const { count } = opening; + const onPresent = (isFinished: () => boolean) => + setOpening((current) => + current.count === count && current.presented === null + ? { ...current, presented: { isFinished } } + : current, + ); if (!source) return null; return ( ); diff --git a/apps/mobile/src/features/home/HomeScreen.tsx b/apps/mobile/src/features/home/HomeScreen.tsx index 8110cca26793d..6f5db6a52f59c 100644 --- a/apps/mobile/src/features/home/HomeScreen.tsx +++ b/apps/mobile/src/features/home/HomeScreen.tsx @@ -469,7 +469,6 @@ export function HomeScreen(props: HomeScreenProps) { selectedThreadKey) } project={projectByKey.get(pendingScopeKey) ?? null} - projectTitle={v2ProjectTitleByProjectKey.get(pendingScopeKey)} environmentLabel={ Object.keys(props.savedConnectionsById).length > 1 ? (props.savedConnectionsById[item.pendingTask.environmentId]?.environmentLabel ?? diff --git a/apps/mobile/src/features/home/thread-swipe-actions.tsx b/apps/mobile/src/features/home/thread-swipe-actions.tsx index 532badd9b35cb..5a0305ca23a86 100644 --- a/apps/mobile/src/features/home/thread-swipe-actions.tsx +++ b/apps/mobile/src/features/home/thread-swipe-actions.tsx @@ -512,7 +512,9 @@ export function ThreadSwipeable(props: ThreadSwipeableProps) { overshootRight renderRightActions={renderRightActions} rightThreshold={actionsWidth * 0.42} - simultaneousWith={props.simultaneousWith} + // Only iPad trackpad pans need rows to swipe while the list scrolls; on Android touch it + // lets a diagonal swipe scroll the list, which the scroll gate turns into a closed row. + simultaneousWith={Platform.OS === "ios" ? props.simultaneousWith : undefined} > { /* oxlint-disable react/refs -- The render callback receives a close/open handler; only invoking that handler accesses the ref. */ diff --git a/apps/mobile/src/features/layout/createWorkspaceStackNavigator.ios.tsx b/apps/mobile/src/features/layout/createWorkspaceStackNavigator.ios.tsx index 7a67a3b50ea8c..fb144bdd16c7e 100644 --- a/apps/mobile/src/features/layout/createWorkspaceStackNavigator.ios.tsx +++ b/apps/mobile/src/features/layout/createWorkspaceStackNavigator.ios.tsx @@ -538,7 +538,6 @@ function WorkspaceStackView(props: ViewProps & { readonly nativeColumns: boolean