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/ci-full.yml b/.github/workflows/ci-full.yml
index cfd9c9979e351..f7e19f78c2ac7 100644
--- a/.github/workflows/ci-full.yml
+++ b/.github/workflows/ci-full.yml
@@ -456,15 +456,7 @@ jobs:
run: >-
vp run test:cached -- --shard ${{ matrix.shard }}/${{ strategy.job-total }}
--uncached apps/server/integration/transferBudgetV2.integration.test.ts
- --verify-hits 1 --report "${{ runner.temp }}/test-cache-${{ matrix.shard }}.json" apps/server
-
- - name: Upload test cache measurements
- if: always() && steps.changes.outputs.test_server != 'false'
- uses: actions/upload-artifact@v7
- with:
- name: test-cache-${{ matrix.shard }}
- path: ${{ runner.temp }}/test-cache-${{ matrix.shard }}.json
- if-no-files-found: error
+ --verify-hits 1 apps/server
# integration/transferBudgetV2.integration.test.ts writes the report; exactly one shard
# produces these files. Gating the upload on their presence keeps a
diff --git a/.github/workflows/issue-vouch.yml b/.github/workflows/issue-vouch.yml
index 02b18fbcc7875..6186c333c0287 100644
--- a/.github/workflows/issue-vouch.yml
+++ b/.github/workflows/issue-vouch.yml
@@ -41,9 +41,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 =
@@ -75,4 +80,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/scripts/ensure-electron-runtime.mjs b/apps/desktop/scripts/ensure-electron-runtime.mjs
index 933a763dfa354..741a2d9ee85d8 100644
--- a/apps/desktop/scripts/ensure-electron-runtime.mjs
+++ b/apps/desktop/scripts/ensure-electron-runtime.mjs
@@ -209,6 +209,10 @@ export function ensureElectronRuntime() {
return electronPath;
}
+export function setup() {
+ ensureElectronRuntime();
+}
+
// `file://${argv[1]}` never matches on Windows (drive letters need `file:///C:/`).
if (process.argv[1] && NodeURL.pathToFileURL(process.argv[1]).href === import.meta.url) {
const electronPath = ensureElectronRuntime();
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/app/stdioErrors.test.ts b/apps/desktop/src/app/stdioErrors.test.ts
new file mode 100644
index 0000000000000..ccfa3ed951178
--- /dev/null
+++ b/apps/desktop/src/app/stdioErrors.test.ts
@@ -0,0 +1,22 @@
+import * as NodeOS from "node:os";
+import { assert, it } from "vite-plus/test";
+
+import { handleStdioError } from "./stdioErrors.ts";
+
+const errorWithCode = (code: string, errno?: number) =>
+ Object.assign(new Error(code), { code, errno });
+const EDQUOT_ERRNO = NodeOS.constants.errno.EDQUOT;
+
+it.each(["EPIPE", "ENOSPC"])("ignores %s on console output", (code) => {
+ assert.doesNotThrow(() => handleStdioError(errorWithCode(code)));
+});
+
+// Node reports EDQUOT as UNKNOWN because libuv has no name for it.
+it.skipIf(EDQUOT_ERRNO === undefined)("ignores EDQUOT on console output", () => {
+ assert.doesNotThrow(() => handleStdioError(errorWithCode("UNKNOWN", -(EDQUOT_ERRNO ?? 0))));
+});
+
+it("rethrows other console output errors", () => {
+ assert.throws(() => handleStdioError(errorWithCode("EIO")), "EIO");
+ assert.throws(() => handleStdioError(errorWithCode("UNKNOWN", -5)), "UNKNOWN");
+});
diff --git a/apps/desktop/src/app/stdioErrors.ts b/apps/desktop/src/app/stdioErrors.ts
new file mode 100644
index 0000000000000..b23c0e89e79a8
--- /dev/null
+++ b/apps/desktop/src/app/stdioErrors.ts
@@ -0,0 +1,13 @@
+import * as NodeOS from "node:os";
+
+// libuv has no name for EDQUOT, so Node reports it as code "UNKNOWN" with the raw errno.
+const EDQUOT_ERRNO = NodeOS.constants.errno.EDQUOT;
+
+// Redirected console output can fail when its log volume is full.
+export function handleStdioError(error: unknown): void {
+ if (typeof error === "object" && error !== null) {
+ if ("code" in error && (error.code === "EPIPE" || error.code === "ENOSPC")) return;
+ if (EDQUOT_ERRNO !== undefined && "errno" in error && error.errno === -EDQUOT_ERRNO) return;
+ }
+ throw error;
+}
diff --git a/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts b/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts
index 4b6b25da1246a..be4784dcba51b 100644
--- a/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts
+++ b/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts
@@ -386,7 +386,7 @@ describe("DesktopBackendConfiguration", () => {
);
assert.equal(config.runningDistro, "Ubuntu");
- assert.deepEqual(config.args.slice(0, 2), ["-d", "Ubuntu"]);
+ assert.deepEqual(config.args.slice(0, 5), ["-d", "Ubuntu", "--cd", "~", "--exec"]);
assert.deepEqual(observedDistros, ["Ubuntu", "Ubuntu", "Ubuntu"]);
assert.isTrue(Option.isNone(config.preflightFailure));
}).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
@@ -449,6 +449,8 @@ describe("DesktopBackendConfiguration", () => {
assert.deepEqual(config.args, [
"-d",
"Ubuntu",
+ "--cd",
+ "~",
"--exec",
"env",
`PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:${resolvedPath}`,
@@ -664,6 +666,8 @@ describe("DesktopBackendConfiguration", () => {
assert.deepEqual(config.args, [
"-d",
"Ubuntu",
+ "--cd",
+ "~",
"--exec",
"env",
"PATH=/home/test user's/.nvm/versions/node/v22.0.0/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/home/test user/bin:/opt/test's tools/bin:/usr/bin:/bin",
diff --git a/apps/desktop/src/backend/DesktopBackendConfiguration.ts b/apps/desktop/src/backend/DesktopBackendConfiguration.ts
index cf5e0ab19002a..26037f5a4a076 100644
--- a/apps/desktop/src/backend/DesktopBackendConfiguration.ts
+++ b/apps/desktop/src/backend/DesktopBackendConfiguration.ts
@@ -754,6 +754,9 @@ const resolveWslStartConfig = Effect.fn("desktop.backendConfiguration.resolveWsl
...baseConfig,
args: [
...distroArgs,
+ // WSL otherwise inherits the Windows-mounted desktop working directory.
+ "--cd",
+ "~",
"--exec",
"env",
`PATH=${launchPath}`,
diff --git a/apps/desktop/src/electron/ElectronMenu.ts b/apps/desktop/src/electron/ElectronMenu.ts
index 4ff3df6bf10f0..540326346edf8 100644
--- a/apps/desktop/src/electron/ElectronMenu.ts
+++ b/apps/desktop/src/electron/ElectronMenu.ts
@@ -1,4 +1,4 @@
-import type { ContextMenuItem } from "@t3tools/contracts";
+import type { ContextMenuItem, ContextMenuSource } from "@t3tools/contracts";
import * as HostProcess from "@t3tools/shared/HostProcess";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
@@ -17,6 +17,7 @@ export interface ElectronMenuContextInput {
readonly window: Electron.BrowserWindow;
readonly items: readonly ContextMenuItem[];
readonly position: Option.Option;
+ readonly source: Option.Option;
}
export interface ElectronMenuTemplateInput {
@@ -259,7 +260,11 @@ export const make = Effect.gen(function* () {
callback: () => complete(Option.none()),
}),
});
- menu.popup(popupOptions);
+ menu.popup(
+ Option.isSome(input.source)
+ ? { ...popupOptions, sourceType: input.source.value }
+ : popupOptions,
+ );
} catch (cause) {
if (completed) {
return;
diff --git a/apps/desktop/src/electron/ElectronWindow.test.ts b/apps/desktop/src/electron/ElectronWindow.test.ts
index 9eb41ed4e2402..eac944722e73b 100644
--- a/apps/desktop/src/electron/ElectronWindow.test.ts
+++ b/apps/desktop/src/electron/ElectronWindow.test.ts
@@ -148,6 +148,34 @@ describe("ElectronWindow", () => {
}).pipe(Effect.provide(layerTestFor("win32"))),
);
+ it.effect("reports which windows were created with a title bar overlay", () =>
+ Effect.gen(function* () {
+ const framed = { isDestroyed: () => false };
+ const overlay = { isDestroyed: () => false };
+ browserWindowMock
+ .mockImplementationOnce(function FramedWindowMock() {
+ return framed;
+ })
+ .mockImplementationOnce(function OverlayWindowMock() {
+ return overlay;
+ });
+ const electronWindow = yield* ElectronWindow.ElectronWindow;
+ yield* electronWindow.create({});
+ yield* electronWindow.create({
+ titleBarStyle: "hidden",
+ titleBarOverlay: { color: "#01000000", height: 40 },
+ });
+ getAllWindowsMock.mockReturnValue([framed, overlay, { isDestroyed: () => false }]);
+
+ const seen: Array = [];
+ yield* electronWindow.syncAllAppearance((_window, { titleBarOverlay }) =>
+ Effect.sync(() => seen.push(titleBarOverlay)),
+ );
+
+ assert.deepEqual(seen, [false, true, false]);
+ }).pipe(Effect.provide(layerTestFor("win32"))),
+ );
+
it.effect("preserves destroy failures and continues with later windows", () =>
Effect.gen(function* () {
const cause = new Error("window destroy failed");
diff --git a/apps/desktop/src/electron/ElectronWindow.ts b/apps/desktop/src/electron/ElectronWindow.ts
index 15a117a52b050..b5f89969e66c7 100644
--- a/apps/desktop/src/electron/ElectronWindow.ts
+++ b/apps/desktop/src/electron/ElectronWindow.ts
@@ -125,7 +125,10 @@ export class ElectronWindow extends Context.Service<
readonly sendAll: (channel: string, ...args: readonly unknown[]) => Effect.Effect;
readonly destroyAll: Effect.Effect;
readonly syncAllAppearance: (
- sync: (window: Electron.BrowserWindow) => Effect.Effect,
+ sync: (
+ window: Electron.BrowserWindow,
+ appearance: { readonly titleBarOverlay: boolean },
+ ) => Effect.Effect,
) => Effect.Effect;
}
>()("@t3tools/desktop/electron/ElectronWindow") {}
@@ -145,6 +148,7 @@ export const make = Effect.gen(function* () {
yield* Effect.addFinalizer(() => Effect.sync(() => windowsForegroundFocus?.close()));
const mainWindowRef = yield* Ref.make>(Option.none());
const auxiliaryWindows = new WeakSet();
+ const titleBarOverlayWindows = new WeakSet();
const listWindows = Effect.try({
try: () => Electron.BrowserWindow.getAllWindows(),
@@ -241,6 +245,9 @@ export const make = Effect.gen(function* () {
try: () => {
const window = new Electron.BrowserWindow(options);
if (behavior?.auxiliary === true) auxiliaryWindows.add(window);
+ if (options.titleBarOverlay !== undefined && options.titleBarOverlay !== false) {
+ titleBarOverlayWindows.add(window);
+ }
return window;
},
catch: (cause) => new ElectronWindowCreateError({ options: diagnosticOptions, cause }),
@@ -383,14 +390,17 @@ export const make = Effect.gen(function* () {
}
}),
syncAllAppearance: Effect.fn("desktop.electron.window.syncAllAppearance")(function* (
- sync: (window: Electron.BrowserWindow) => Effect.Effect,
+ sync: (
+ window: Electron.BrowserWindow,
+ appearance: { readonly titleBarOverlay: boolean },
+ ) => Effect.Effect,
) {
const windows = yield* listWindows;
for (const window of windows) {
if (yield* isWindowDestroyed(window)) {
continue;
}
- yield* sync(window);
+ yield* sync(window, { titleBarOverlay: titleBarOverlayWindows.has(window) });
}
}),
});
diff --git a/apps/desktop/src/ipc/DesktopIpcHandlers.ts b/apps/desktop/src/ipc/DesktopIpcHandlers.ts
index 9f2f68be61520..57d7101cf9ec7 100644
--- a/apps/desktop/src/ipc/DesktopIpcHandlers.ts
+++ b/apps/desktop/src/ipc/DesktopIpcHandlers.ts
@@ -50,6 +50,7 @@ import {
probeRemoteEditors,
revealWindow,
pickFolder,
+ toLocalBackendPath,
pickProjectFavicon,
pickThemeFiles,
setTheme,
@@ -145,6 +146,7 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers"
yield* ipc.handle(setWslOnly);
yield* ipc.handle(pickFolder);
+ yield* ipc.handle(toLocalBackendPath);
yield* ipc.handle(pickProjectFavicon);
yield* ipc.handle(pickThemeFiles);
yield* ipc.handle(setTheme);
diff --git a/apps/desktop/src/ipc/channels.ts b/apps/desktop/src/ipc/channels.ts
index 0e422f9bc7356..4de0a23af35b3 100644
--- a/apps/desktop/src/ipc/channels.ts
+++ b/apps/desktop/src/ipc/channels.ts
@@ -1,4 +1,5 @@
export const PICK_FOLDER_CHANNEL = "desktop:pick-folder";
+export const TO_LOCAL_BACKEND_PATH_CHANNEL = "desktop:to-local-backend-path";
export const SET_NOTIFICATION_BADGE_CHANNEL = "desktop:set-notification-badge";
export const PICK_PROJECT_FAVICON_CHANNEL = "desktop:pick-project-favicon";
export const PICK_THEME_FILES_CHANNEL = "desktop:pick-theme-files";
@@ -100,6 +101,7 @@ export const PREVIEW_SET_AUDIO_MUTED_CHANNEL = "desktop:preview-set-audio-muted"
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..757e1e463f538 100644
--- a/apps/desktop/src/ipc/methods/preview.ts
+++ b/apps/desktop/src/ipc/methods/preview.ts
@@ -13,6 +13,7 @@ import {
DesktopPreviewScreenshotArtifactSchema,
DesktopPreviewSetAudioMutedInputSchema,
DesktopPreviewSetShownInputSchema,
+ DesktopPreviewSetCaptureDrawnInputSchema,
DesktopPreviewSetColorSchemeInputSchema,
DesktopPreviewSetZoomFactorInputSchema,
BrowserImportResult,
@@ -234,6 +235,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",
@@ -488,6 +498,7 @@ export const methods = [
setZoomFactor,
setAudioMuted,
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 fece3327ce92d..6a52d89ad9810 100644
--- a/apps/desktop/src/ipc/methods/window.test.ts
+++ b/apps/desktop/src/ipc/methods/window.test.ts
@@ -2,6 +2,8 @@ import { assert, describe, it } from "@effect/vitest";
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
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 { currentDesktopBootstrapToken } from "@t3tools/shared/desktopBootstrapToken";
import * as Clock from "effect/Clock";
@@ -28,6 +30,7 @@ import * as DesktopBackendManager from "../../backend/DesktopBackendManager.ts";
import * as DesktopBackendPool from "../../backend/DesktopBackendPool.ts";
import * as DesktopAppSettings from "../../settings/DesktopAppSettings.ts";
import * as DesktopManagedPolicy from "../../app/DesktopManagedPolicy.ts";
+import * as DesktopWslEnvironment from "../../wsl/DesktopWslEnvironment.ts";
import * as ElectronDialog from "../../electron/ElectronDialog.ts";
import * as ElectronWindow from "../../electron/ElectronWindow.ts";
import * as IpcChannels from "../channels.ts";
@@ -39,6 +42,7 @@ import {
probeRemoteEditors,
readMedia,
syncHtmlFullscreen,
+ toLocalBackendPath,
} from "./window.ts";
const readyWslConfig: DesktopBackendManager.DesktopBackendStartConfig = {
@@ -195,6 +199,47 @@ describe("getLocalEnvironmentBootstraps", () => {
});
});
+describe("toLocalBackendPath", () => {
+ const { runningDistro: _, ...windowsConfig } = readyWslConfig;
+ it.effect("converts paths through wslpath only for backends running in WSL", () =>
+ Effect.gen(function* () {
+ const convert = (backendId: string, path = "C:\\Users\\me\\project") =>
+ toLocalBackendPath.handler({ backendId, path });
+ assert.strictEqual(yield* convert("primary"), "C:\\Users\\me\\project");
+ assert.strictEqual(yield* convert("wsl:default"), "/drives/c/Users/me/project");
+ assert.strictEqual(yield* convert("wsl:missing"), null);
+ assert.strictEqual(
+ yield* convert("wsl:default", "\\\\wsl.localhost\\ubuntu\\home\\me\\repo"),
+ "/home/me/repo",
+ );
+ assert.strictEqual(yield* convert("wsl:default", "\\\\wsl$\\Debian\\home\\me\\repo"), null);
+ assert.strictEqual(
+ yield* convert("primary", "\\\\wsl$\\Debian\\home\\me\\repo"),
+ "\\\\wsl$\\Debian\\home\\me\\repo",
+ );
+ }).pipe(
+ Effect.provide(
+ Layer.mergeAll(
+ DesktopBackendPool.layerTest([
+ {
+ ...defaultWslInstance,
+ id: DesktopBackendManager.BackendInstanceId("primary"),
+ currentConfig: Effect.succeedSome(windowsConfig),
+ },
+ defaultWslInstance,
+ ]),
+ DesktopWslEnvironment.layerTest({
+ windowsToWslPath: (distro, windowsPath) =>
+ distro === "Ubuntu" && windowsPath === "C:\\Users\\me\\project"
+ ? Option.some("/drives/c/Users/me/project")
+ : Option.none(),
+ }),
+ ),
+ ),
+ ),
+ );
+});
+
describe("installRelayTelemetryEnabled", () => {
// The renderer reads this over sync IPC, so the answer must not wait on the filesystem.
const relayTelemetryEnabled = (
@@ -484,3 +529,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 accc57d0032c6..8674c0ae65dfb 100644
--- a/apps/desktop/src/ipc/methods/window.ts
+++ b/apps/desktop/src/ipc/methods/window.ts
@@ -1,5 +1,6 @@
import {
ContextMenuItemSchema,
+ ContextMenuSource,
DesktopAppBrandingSchema,
DesktopEnvironmentBootstrapSchema,
DesktopMediaReadSchema,
@@ -16,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";
@@ -26,6 +28,7 @@ import { currentDesktopBootstrapToken } from "@t3tools/shared/desktopBootstrapTo
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
+import * as DesktopBackendManager from "../../backend/DesktopBackendManager.ts";
import * as DesktopBackendPool from "../../backend/DesktopBackendPool.ts";
import * as DesktopLocalEnvironmentAuth from "../../backend/DesktopLocalEnvironmentAuth.ts";
import * as DesktopEnvironment from "../../app/DesktopEnvironment.ts";
@@ -59,6 +62,7 @@ const ContextMenuPosition = Schema.Struct({
const ContextMenuInput = Schema.Struct({
items: Schema.Array(ContextMenuItemSchema),
position: Schema.optionalKey(ContextMenuPosition),
+ source: Schema.optionalKey(ContextMenuSource),
});
function toWebSocketBaseUrl(httpBaseUrl: URL): string {
@@ -209,6 +213,20 @@ export const getLocalEnvironmentBearerToken = DesktopIpc.makeIpcMethod({
}),
});
+// Ask the distro: its automount root is configurable, so /mnt/ is only the default.
+const windowsPathToWsl = Effect.fn("desktop.ipc.window.windowsPathToWsl")(function* (
+ distro: string | null,
+ windowsPath: string,
+) {
+ const linuxUncPath = wslUncPathToLinuxPath(windowsPath);
+ if (linuxUncPath !== null) return Option.some(linuxUncPath);
+ const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment;
+ return yield* wslEnvironment.windowsToWslPath(
+ extractDistroFromUncPath(windowsPath) ?? distro,
+ windowsPath,
+ );
+});
+
export const pickFolder = DesktopIpc.makeIpcMethod({
channel: IpcChannels.PICK_FOLDER_CHANNEL,
payload: Schema.UndefinedOr(PickFolderOptionsSchema),
@@ -255,20 +273,29 @@ export const pickFolder = DesktopIpc.makeIpcMethod({
if (!useWsl) {
return selectedPath.value;
}
-
- const linuxUncPath = wslUncPathToLinuxPath(selectedPath.value);
- if (linuxUncPath !== null) {
- return linuxUncPath;
- }
-
- const converted = yield* wslEnvironment.windowsToWslPath(
- extractDistroFromUncPath(selectedPath.value) ?? wslDistro,
- selectedPath.value,
- );
+ const converted = yield* windowsPathToWsl(wslDistro, selectedPath.value);
return Option.getOrElse(converted, () => selectedPath.value);
}),
});
+export const toLocalBackendPath = DesktopIpc.makeIpcMethod({
+ channel: IpcChannels.TO_LOCAL_BACKEND_PATH_CHANNEL,
+ payload: Schema.Struct({ backendId: Schema.String, path: Schema.String }),
+ result: Schema.NullOr(Schema.String),
+ handler: Effect.fn("desktop.ipc.window.toLocalBackendPath")(function* ({ backendId, path }) {
+ const pool = yield* DesktopBackendPool.DesktopBackendPool;
+ const instance = yield* pool.get(DesktopBackendManager.BackendInstanceId(backendId));
+ if (Option.isNone(instance)) return null;
+ const config = yield* instance.value.currentConfig;
+ if (Option.isNone(config) || Option.isSome(config.value.preflightFailure)) return null;
+ const { runningDistro } = config.value;
+ if (runningDistro === undefined) return path;
+ const uncDistro = extractDistroFromUncPath(path);
+ if (uncDistro !== null && uncDistro.toLowerCase() !== runningDistro.toLowerCase()) return null;
+ return Option.getOrNull(yield* windowsPathToWsl(runningDistro, path));
+ }),
+});
+
export const pickProjectFavicon = DesktopIpc.makeIpcMethod({
channel: IpcChannels.PICK_PROJECT_FAVICON_CHANNEL,
payload: Schema.UndefinedOr(Schema.String),
@@ -321,6 +348,7 @@ export const showContextMenu = DesktopIpc.makeIpcMethod({
window: window.value,
items: input.items,
position: Option.fromNullishOr(input.position),
+ source: Option.fromNullishOr(input.source),
});
return Option.getOrNull(selectedItemId);
}),
@@ -405,20 +433,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/main.ts b/apps/desktop/src/main.ts
index d52f3960d4b3c..178e2a3ead56e 100644
--- a/apps/desktop/src/main.ts
+++ b/apps/desktop/src/main.ts
@@ -1,10 +1,10 @@
import * as MacPermissions from "./permissions/MacPermissions.ts";
import { applyProductEnvironment } from "@t3tools/shared/productIdentity";
applyProductEnvironment(process.env);
+import { handleStdioError } from "./app/stdioErrors.ts";
+
for (const stream of [process.stdout, process.stderr]) {
- stream.on("error", (err: NodeJS.ErrnoException) => {
- if (err.code !== "EPIPE") throw err;
- });
+ stream.on("error", handleStdioError);
}
import * as NodeHttpClient from "@effect/platform-node/NodeHttpClient";
diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.ts
index 6414743ac3b2f..f0f9648173dc8 100644
--- a/apps/desktop/src/preload.ts
+++ b/apps/desktop/src/preload.ts
@@ -238,14 +238,17 @@ contextBridge.exposeInMainWorld("desktopBridge", {
setWslDistro: (distro) => ipcRenderer.invoke(IpcChannels.SET_WSL_DISTRO_CHANNEL, distro),
setWslOnly: (enabled) => ipcRenderer.invoke(IpcChannels.SET_WSL_ONLY_CHANNEL, enabled),
pickFolder: (options) => ipcRenderer.invoke(IpcChannels.PICK_FOLDER_CHANNEL, options),
+ toLocalBackendPath: (backendId, path) =>
+ ipcRenderer.invoke(IpcChannels.TO_LOCAL_BACKEND_PATH_CHANNEL, { backendId, path }),
pickProjectFavicon: (initialPath) =>
ipcRenderer.invoke(IpcChannels.PICK_PROJECT_FAVICON_CHANNEL, initialPath),
pickThemeFiles: () => ipcRenderer.invoke(IpcChannels.PICK_THEME_FILES_CHANNEL, undefined),
setTheme: (theme) => ipcRenderer.invoke(IpcChannels.SET_THEME_CHANNEL, theme),
- showContextMenu: (items, position) =>
+ showContextMenu: (items, position, source) =>
ipcRenderer.invoke(IpcChannels.CONTEXT_MENU_CHANNEL, {
items,
...(position === undefined ? {} : { position }),
+ ...(source === undefined ? {} : { source }),
}),
receiveProviderAuthCallback: (url: string) =>
ipcRenderer.invoke(IpcChannels.RECEIVE_PROVIDER_AUTH_CALLBACK_CHANNEL, url),
@@ -411,6 +414,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/BrowserImport/ChromiumCookies.test.ts b/apps/desktop/src/preview/BrowserImport/ChromiumCookies.test.ts
index 92ab35320dab7..eb4dd3143eefb 100644
--- a/apps/desktop/src/preview/BrowserImport/ChromiumCookies.test.ts
+++ b/apps/desktop/src/preview/BrowserImport/ChromiumCookies.test.ts
@@ -358,6 +358,29 @@ describe("readChromiumCookieDatabase", () => {
}).pipe(Effect.provide(NodeServices.layer)),
);
+ it.effect("reads a cookie database the browser has emptied as having no cookies", () =>
+ Effect.gen(function* () {
+ const fileSystem = yield* FileSystem.FileSystem;
+ const directory = yield* fileSystem.makeTempDirectoryScoped({
+ prefix: "t3code-chromium-cookies-",
+ });
+ const filename = `${directory}/Cookies`;
+ yield* Effect.gen(function* () {
+ const sql = yield* SqlClient.SqlClient;
+ yield* sql`create table scratch (id integer)`;
+ yield* sql`drop table scratch`;
+ }).pipe(Effect.provide(NodeSqliteClient.layer({ filename })));
+
+ const result = yield* readChromiumCookieDatabase(
+ filename,
+ { cbcV10: Buffer.from("0123456789abcdef") },
+ "darwin",
+ );
+
+ expect(result).toEqual({ cookies: [], undecryptable: 0, undecryptableHosts: [] });
+ }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
+ );
+
it.effect("skips partitioned cookies without breaking pre-CHIPS schemas", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
diff --git a/apps/desktop/src/preview/BrowserImport/ChromiumCookies.ts b/apps/desktop/src/preview/BrowserImport/ChromiumCookies.ts
index 63fef9fb3c808..91cbfa03aac7d 100644
--- a/apps/desktop/src/preview/BrowserImport/ChromiumCookies.ts
+++ b/apps/desktop/src/preview/BrowserImport/ChromiumCookies.ts
@@ -181,6 +181,10 @@ export const readChromiumCookieDatabase = Effect.fn("ChromiumCookies.readChromiu
function* (snapshotPath: string, keys: ChromiumKeyMaterial, platform: NodeJS.Platform) {
const result = yield* Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
+ // Chromium razes a damaged jar to a file with no tables and rebuilds it on its next write.
+ const tables =
+ yield* sql`select 1 from sqlite_master where type = 'table' and name = 'cookies'`;
+ if (tables.length === 0) return { rows: [], schemaVersion: 0 };
const schemaVersion = yield* sql`select value from meta where key = 'version' limit 1`.pipe(
Effect.flatMap(decodeSchemaVersion),
Effect.map(([row]) => row.value),
diff --git a/apps/desktop/src/preview/BrowserImport/Sources.ts b/apps/desktop/src/preview/BrowserImport/Sources.ts
index 20a35752ed979..6ecd546a1ad57 100644
--- a/apps/desktop/src/preview/BrowserImport/Sources.ts
+++ b/apps/desktop/src/preview/BrowserImport/Sources.ts
@@ -345,6 +345,12 @@ const countProfileCookies = Effect.fnUntraced(function* (
if (database === undefined) return undefined;
return yield* Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
+ // readChromiumCookieDatabase imports a razed jar as empty; Firefox has no such reader guard.
+ if (definition.engine !== "firefox") {
+ const tables =
+ yield* sql`select 1 from sqlite_master where type = 'table' and name = 'cookies'`;
+ if (tables.length === 0) return 0;
+ }
const rows =
definition.engine === "firefox"
? yield* sql`select count(*) as count from moz_cookies where originAttributes = ''`
diff --git a/apps/desktop/src/preview/CdpRelay.test.ts b/apps/desktop/src/preview/CdpRelay.test.ts
index ccc2b868720b4..564b4dc57d6f4 100644
--- a/apps/desktop/src/preview/CdpRelay.test.ts
+++ b/apps/desktop/src/preview/CdpRelay.test.ts
@@ -9,6 +9,7 @@ import {
const makeTarget = (
send: CdpRelayTarget["send"],
setDownloadDirectory: CdpRelayTarget["setDownloadDirectory"] = () => {},
+ ackScreencastFrame: CdpRelayTarget["ackScreencastFrame"] = () => {},
): CdpRelayTarget => ({
send,
targetId: async () => "GUEST-TARGET",
@@ -17,6 +18,7 @@ const makeTarget = (
userAgent: () => "Electron",
setDownloadDirectory,
receivesScreencast: () => true,
+ ackScreencastFrame,
});
const makeRelay = (target: CdpRelayTarget, write: (raw: string) => void) =>
@@ -138,9 +140,13 @@ describe("CDP relay", () => {
describe("CDP relay extra sessions", () => {
it("gives a second page session the page's commands and events", async () => {
- const send = vi.fn(async () => ({}));
+ const send = vi.fn(async () => ({}));
const written: Array> = [];
- const relay = makeRelay(makeTarget(send), (raw) => written.push(JSON.parse(raw)));
+ const nativeAcks: Array = [];
+ const relay = makeRelay(
+ makeTarget(send, undefined, (frameId) => nativeAcks.push(frameId)),
+ (raw) => written.push(JSON.parse(raw)),
+ );
relay.receive(JSON.stringify({ id: 1, method: "Target.setAutoAttach", params: {} }));
relay.receive(JSON.stringify({ id: 2, method: "Target.attachToBrowserTarget" }));
await settle();
@@ -170,8 +176,63 @@ describe("CDP relay extra sessions", () => {
await settle();
expect(send).toHaveBeenLastCalledWith("Page.startScreencast", {}, undefined, extra);
written.length = 0;
- relay.event("Page.screencastFrame", { data: "x" }, undefined);
- expect(written.map((m) => m["sessionId"])).toEqual(["t3-preview-page", extra]);
+ const frame = (frameId: number) =>
+ relay.event("Page.screencastFrame", { data: "x", sessionId: frameId }, undefined);
+ const ack = (sessionId: string, frameId: number) =>
+ relay.receive(
+ JSON.stringify({
+ id: 6,
+ method: "Page.screencastFrameAck",
+ params: { sessionId: frameId },
+ sessionId,
+ }),
+ );
+ const delivered = () => {
+ const frames = written
+ .filter((m) => m["method"])
+ .map((m) => [m["sessionId"], (m["params"] as { sessionId?: number }).sessionId]);
+ written.length = 0;
+ return frames;
+ };
+ frame(1);
+ expect(delivered()).toEqual([
+ ["t3-preview-page", 1],
+ [extra, 1],
+ ]);
+ // A session that has not acknowledged its frame gets only the newest one, on its ack.
+ for (let i = 2; i < 100; i++) frame(i);
+ expect(delivered()).toEqual([]);
+ // Frames every session is busy for stay unacknowledged, so Chromium pauses at its in-flight limit.
+ expect(nativeAcks).toEqual([1]);
+ ack(extra, 1);
+ await settle();
+ expect(delivered()).toEqual([[extra, 99]]);
+ // Each consumer ack lets Chromium send one more frame.
+ expect(nativeAcks).toEqual([1, 2]);
+ ack(extra, 99);
+ await settle();
+ expect(delivered()).toEqual([]);
+ expect(nativeAcks).toEqual([1, 2, 3]);
+ frame(100);
+ expect(delivered()).toEqual([[extra, 100]]);
+ ack(extra, 99);
+ await settle();
+ frame(101);
+ expect(delivered()).toEqual([]);
+ expect(send.mock.calls.some(([method]) => method === "Page.screencastFrameAck")).toBe(false);
+ // A restart keeps the unacknowledged frame's slot until its own acknowledgement.
+ relay.receive(JSON.stringify({ id: 7, method: "Page.stopScreencast", sessionId: extra }));
+ relay.receive(JSON.stringify({ id: 8, method: "Page.startScreencast", sessionId: extra }));
+ await settle();
+ delivered();
+ frame(102);
+ expect(delivered()).toEqual([]);
+ ack(extra, 100);
+ await settle();
+ expect(delivered()).toEqual([[extra, 102]]);
+ // Other events still reach a session while its frame is unacknowledged.
+ relay.event("Page.loadEventFired", { timestamp: 1 }, undefined);
+ expect(delivered().map(([session]) => session)).toEqual(["t3-preview-page", extra]);
});
});
diff --git a/apps/desktop/src/preview/CdpRelay.ts b/apps/desktop/src/preview/CdpRelay.ts
index 658e1cf70623d..e9f3cf509b446 100644
--- a/apps/desktop/src/preview/CdpRelay.ts
+++ b/apps/desktop/src/preview/CdpRelay.ts
@@ -11,6 +11,8 @@ export interface CdpRelayTarget {
readonly sessionDetached?: (owner: string) => void;
/** Whether a page session, by owner as `send` names it, gets the page's screencast frames. */
readonly receivesScreencast: (owner: string | undefined) => boolean;
+ /** Acknowledges a native screencast frame, letting Chromium send the next one. */
+ readonly ackScreencastFrame: (frameId: number) => void;
/** The page's own CDP target id; Playwright keys the main frame by it. */
readonly targetId: () => Promise;
readonly url: () => string;
@@ -103,6 +105,20 @@ export function createCdpRelayConnection(
let downloadEventsEnabled = false;
/** Relay-created page sessions share one real debugger; child frame sessions retain their own ids. */
const sessions = new Map([[PAGE_SESSION_ID, "page"]]);
+ // Each page session holds one unacknowledged frame and keeps the newest one skipped meanwhile.
+ const unackedFrames = new Map();
+ const skippedFrames = new Map>();
+ // Chromium keeps a few frames in flight and reuses one frame id per run, so pacing it means
+ // leaving frames every session is busy for unacknowledged and releasing one per consumer ack.
+ const heldNativeFrames: Array = [];
+ const releaseHeldFramesWithoutHolders = () => {
+ if (skippedFrames.size === 0)
+ for (const frameId of heldNativeFrames.splice(0)) target.ackScreencastFrame(frameId);
+ };
+ const sendFrame = (sessionId: string, params: Record) => {
+ unackedFrames.set(sessionId, params["sessionId"] as number);
+ send({ method: "Page.screencastFrame", params, sessionId });
+ };
let sessionSequence = 0;
const newSession = (kind: "browser" | "page") => {
const sessionId = `t3-preview-${kind}-${++sessionSequence}`;
@@ -170,6 +186,9 @@ export function createCdpRelayConnection(
const sessionId = command.params?.["sessionId"];
if (typeof sessionId === "string" && sessionId !== PAGE_SESSION_ID) {
sessions.delete(sessionId);
+ unackedFrames.delete(sessionId);
+ skippedFrames.delete(sessionId);
+ releaseHeldFramesWithoutHolders();
target.sessionDetached?.(sessionId);
}
return {};
@@ -202,6 +221,27 @@ export function createCdpRelayConnection(
}
// Playwright asks for this on every page; the host emulates focus only while it is in use.
if (command.method === "Emulation.setFocusEmulationEnabled") return Promise.resolve({});
+ if (command.method === "Page.screencastFrameAck" && child === undefined) {
+ // A restart keeps the slot too, or restarting would let frames past an unacknowledged one.
+ const sessionId = command.sessionId!;
+ if (unackedFrames.get(sessionId) === command.params?.["sessionId"]) {
+ unackedFrames.delete(sessionId);
+ const skipped = skippedFrames.get(sessionId);
+ skippedFrames.delete(sessionId);
+ if (
+ skipped !== undefined &&
+ target.receivesScreencast(sessionId === PAGE_SESSION_ID ? undefined : sessionId)
+ )
+ sendFrame(sessionId, skipped);
+ const released = heldNativeFrames.shift();
+ if (released !== undefined) target.ackScreencastFrame(released);
+ }
+ return Promise.resolve({});
+ }
+ if (command.method === "Page.stopScreencast" && child === undefined) {
+ skippedFrames.delete(command.sessionId!);
+ releaseHeldFramesWithoutHolders();
+ }
// The shared debugger keeps Runtime enabled after an earlier connection, and a repeated
// enable reports no existing contexts; Playwright waits for them, so reset once per connection.
if (command.method === "Runtime.enable" && child === undefined) {
@@ -262,15 +302,29 @@ export function createCdpRelayConnection(
send({ method, params, sessionId });
return;
}
- for (const [id, kind] of sessions) {
- if (kind !== "page") continue;
- if (
- method === "Page.screencastFrame" &&
- !target.receivesScreencast(id === PAGE_SESSION_ID ? undefined : id)
- )
- continue;
- send({ method, params, sessionId: id });
+ if (method === "Page.screencastFrame") {
+ const frame = (params ?? {}) as Record;
+ const frameId = frame["sessionId"];
+ if (typeof frameId !== "number") return;
+ let held = false;
+ let delivered = false;
+ for (const [id, kind] of sessions) {
+ if (kind !== "page") continue;
+ if (!target.receivesScreencast(id === PAGE_SESSION_ID ? undefined : id)) continue;
+ if (unackedFrames.has(id)) {
+ skippedFrames.set(id, frame);
+ held = true;
+ } else {
+ sendFrame(id, frame);
+ delivered = true;
+ }
+ }
+ if (held && !delivered) heldNativeFrames.push(frameId);
+ else target.ackScreencastFrame(frameId);
+ return;
}
+ for (const [id, kind] of sessions)
+ if (kind === "page") send({ method, params, sessionId: id });
},
};
}
diff --git a/apps/desktop/src/preview/DesktopBrowserHost.test.ts b/apps/desktop/src/preview/DesktopBrowserHost.test.ts
index d6f25d66aa810..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);
@@ -1157,6 +1191,13 @@ describe("DesktopBrowserHost", () => {
debuggee.refuse(6);
debuggee.release();
expect([yield* Queue.take(replies), yield* Queue.take(replies)].toSorted()).toEqual([5, 6]);
+ yield* raw({
+ id: 7,
+ method: "Page.screencastFrameAck",
+ params: { sessionId: 1 },
+ sessionId: "t3-preview-page-1",
+ });
+ expect(yield* Queue.take(replies)).toBe(7);
yield* settle;
frames.length = 0;
debuggee.emit("Page.screencastFrame", { data: "frame", sessionId: 2 });
@@ -1236,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);
@@ -1271,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);
@@ -1335,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 296be2fa6709f..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"
@@ -421,6 +450,10 @@ export const make = Effect.gen(function* () {
dropSessionHolds(tab, owner);
},
receivesScreencast: (owner) => tab.screencasts.has(owner),
+ ackScreencastFrame: (frameId) =>
+ void debuggee
+ .sendCommand("Page.screencastFrameAck", { sessionId: frameId })
+ .catch(() => {}),
targetId: () =>
debuggee
.sendCommand("Target.getTargetInfo")
@@ -583,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 });
};
@@ -659,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 802cd315b8e60..2091ff3c7f8f2 100644
--- a/apps/desktop/src/preview/Manager.test.ts
+++ b/apps/desktop/src/preview/Manager.test.ts
@@ -349,6 +349,47 @@ const makeTestPreviewWebContents = (
} as unknown as TestPreviewWebContents;
};
+const makeStillImage = (pixels = "fresh-png") => ({
+ toPNG: () => Buffer.from(pixels),
+ toJPEG: () => Buffer.from(pixels),
+ getSize: () => ({ width: 100, height: 80 }),
+});
+
+const makeTestStillImageWebContents = (...args: Parameters) => {
+ const wc = makeTestPreviewWebContents(...args);
+ Object.assign(wc, { isDevToolsOpened: () => false });
+ holdStillImagePaint(wc, Promise.resolve());
+ return wc;
+};
+
+const holdStillImagePaint = (
+ wc: TestPreviewWebContents,
+ paint: Promise | Array>,
+) => {
+ vi.mocked(wc.debugger.sendCommand).mockImplementation(async (method) => {
+ if (method === "Page.getFrameTree") return { frameTree: { frame: { id: "main" } } };
+ if (method === "Page.createIsolatedWorld") return { executionContextId: 7 };
+ if (method === "Runtime.evaluate") {
+ await (Array.isArray(paint) ? paint.shift() : paint);
+ return { result: { value: true } };
+ }
+ return undefined;
+ });
+};
+
+const setupStill = (manager: PreviewManager.PreviewManager["Service"], paint = Promise.resolve()) =>
+ Effect.gen(function* () {
+ const image = makeStillImage();
+ const capturePage = vi.fn<() => Promise>().mockResolvedValue(image);
+ const wc = makeTestStillImageWebContents(capturePage);
+ holdStillImagePaint(wc, paint);
+ fromId.mockReturnValue(wc);
+ yield* manager.createTab("tab_still");
+ yield* manager.registerWebview("tab_still", wc.id);
+ yield* manager.setColorScheme("tab_still", "system");
+ return { image, capturePage, wc, capture: manager.captureScreenshot("tab_still") };
+ });
+
const setupRecordingRaceTabs = (manager: PreviewManager.PreviewManager["Service"]) =>
Effect.gen(function* () {
const capturePage = vi.fn(async () => ({
@@ -576,6 +617,32 @@ describe("PreviewManager", () => {
webviewSend.mockClear();
});
+ effectIt.effect("preserves recording artifacts saved in the same millisecond", () =>
+ withManager((manager) =>
+ Effect.gen(function* () {
+ const stored = new Map();
+ const save = (path: string, bytes: Uint8Array) => {
+ stored.set(path, Uint8Array.from(bytes));
+ return undefined;
+ };
+ writeFile.mockImplementationOnce(save).mockImplementationOnce(save);
+ const firstBytes = new Uint8Array([1, 2, 3]);
+ const secondBytes = new Uint8Array([4, 5, 6]);
+ const [first, second] = yield* Effect.all(
+ [
+ manager.saveRecording("tab_first", "video/webm", firstBytes),
+ manager.saveRecording("tab_second", "video/webm", secondBytes),
+ ],
+ { concurrency: "unbounded" },
+ );
+
+ expect(first.path).not.toBe(second.path);
+ expect(stored.get(first.path)).toEqual(firstBytes);
+ expect(stored.get(second.path)).toEqual(secondBytes);
+ }),
+ ),
+ );
+
effectIt.effect.each([false, true])(
"preserves simultaneous same-name downloads with an existing destination: %s",
(existing) =>
@@ -617,6 +684,7 @@ describe("PreviewManager", () => {
attach: () => {},
detach: () => {},
setShown: () => {},
+ setCaptureDrawn: () => {},
loadFailed: () => {},
humanStartedDownload: () => true,
agentLedPage: () => false,
@@ -1824,6 +1892,30 @@ describe("PreviewManager", () => {
),
);
+ effectIt.effect("captures final pixels after warmup fails and paint readiness settles", () =>
+ withManager((manager) =>
+ Effect.gen(function* () {
+ const paint = Promise.withResolvers();
+ const { capturePage, wc, capture } = yield* setupStill(manager, paint.promise);
+ capturePage
+ .mockRejectedValueOnce(new Error("UnknownVizError"))
+ .mockRejectedValueOnce(new Error("UnknownVizError"))
+ .mockRejectedValueOnce(new Error("UnknownVizError"))
+ .mockResolvedValue(makeStillImage("final-png"));
+ const fiber = yield* capture.pipe(Effect.forkChild({ startImmediately: true }));
+ yield* TestClock.adjust(300);
+ expect(capturePage).toHaveBeenCalledTimes(3);
+ expect(writeFile).not.toHaveBeenCalled();
+ expect(wc.setBackgroundThrottling.mock.calls).toEqual([[false]]);
+ paint.resolve();
+ const artifact = yield* Fiber.join(fiber);
+ expect(capturePage).toHaveBeenCalledTimes(4);
+ expect(writeFile.mock.calls).toEqual([[artifact.path, Buffer.from("final-png")]]);
+ expect(wc.setBackgroundThrottling.mock.calls).toEqual([[false], [true]]);
+ }),
+ ),
+ );
+
effectIt.effect("preserves both screenshots of the same site in the same millisecond", () =>
withManager((manager) =>
Effect.gen(function* () {
@@ -1837,6 +1929,8 @@ describe("PreviewManager", () => {
const capturePage = vi
.fn<() => Promise>>()
.mockResolvedValueOnce(pngImage(firstPng))
+ .mockResolvedValueOnce(pngImage(firstPng))
+ .mockResolvedValueOnce(pngImage(secondPng))
.mockResolvedValueOnce(pngImage(secondPng));
fromId.mockReturnValue(makeTestPreviewWebContents(capturePage));
yield* manager.createTab("tab_1");
@@ -1857,6 +1951,115 @@ describe("PreviewManager", () => {
),
);
+ effectIt.effect(
+ "waits for paint before capturing and restores rendering after overlapping requests",
+ () =>
+ withManager((manager) =>
+ Effect.gen(function* () {
+ const paints = [Promise.withResolvers(), Promise.withResolvers()];
+ const pendingPaints = paints.map((paint) => paint.promise);
+ const { image, capturePage, wc, capture } = yield* setupStill(manager);
+ holdStillImagePaint(wc, pendingPaints);
+ const first = Promise.withResolvers();
+ const second = Promise.withResolvers();
+ capturePage
+ .mockResolvedValueOnce(makeStillImage("discarded-warmup"))
+ .mockResolvedValueOnce(makeStillImage("discarded-warmup"))
+ .mockReturnValueOnce(first.promise)
+ .mockReturnValueOnce(second.promise);
+ const hostThrottling = vi.fn();
+ yield* manager.setMainWindow({
+ isDestroyed: () => false,
+ once: vi.fn(),
+ webContents: { setBackgroundThrottling: hostThrottling },
+ } as never);
+ const one = yield* capture.pipe(Effect.forkChild({ startImmediately: true }));
+ const two = yield* capture.pipe(Effect.forkChild({ startImmediately: true }));
+ yield* TestClock.adjust(0);
+ expect(capturePage).toHaveBeenCalledTimes(2);
+ expect(pendingPaints).toHaveLength(0);
+ expect(writeFile).not.toHaveBeenCalled();
+ expect(hostThrottling.mock.calls).toEqual([[false]]);
+ expect(wc.setBackgroundThrottling.mock.calls).toEqual([[false]]);
+ paints.forEach((paint) => paint.resolve());
+ yield* TestClock.adjust(0);
+ expect(capturePage).toHaveBeenCalledTimes(4);
+ first.resolve(image);
+ yield* Fiber.join(one);
+ expect(wc.setBackgroundThrottling.mock.calls).toEqual([[false]]);
+ second.resolve(image);
+ yield* Fiber.join(two);
+ const saved = writeFile.mock.calls.map(([, bytes]) => bytes);
+ expect(saved).toEqual([image.toPNG(), image.toPNG()]);
+ expect(hostThrottling.mock.calls).toEqual([[false], [true]]);
+ expect(wc.setBackgroundThrottling.mock.calls).toEqual([[false], [true]]);
+ }),
+ ),
+ );
+
+ effectIt.effect("keeps picture-in-picture rendering after a still image completes", () =>
+ withManager((manager) =>
+ Effect.gen(function* () {
+ const { image, capturePage, wc, capture } = yield* setupStill(manager);
+ const pending = Promise.withResolvers();
+ capturePage
+ .mockResolvedValueOnce(image)
+ .mockResolvedValueOnce(makeStillImage("discarded-warmup"))
+ .mockReturnValueOnce(pending.promise);
+ const { pictureInPictureWindow } = makeTestPictureInPictureWindow();
+ browserWindowConstructor.mockImplementation(function () {
+ return pictureInPictureWindow;
+ });
+ yield* manager.openPictureInPicture("tab_still");
+ const still = yield* capture.pipe(Effect.forkChild({ startImmediately: true }));
+ yield* TestClock.adjust(0);
+ expect(capturePage).toHaveBeenCalledTimes(3);
+ expect(writeFile).not.toHaveBeenCalled();
+ pending.resolve(image);
+ yield* Fiber.join(still);
+ expect(writeFile.mock.calls.map((call) => call[1])).toEqual([Buffer.from("fresh-png")]);
+ expect(wc.setBackgroundThrottling.mock.calls).toEqual([[false]]);
+ yield* manager.closePictureInPicture("tab_still");
+ expect(wc.setBackgroundThrottling.mock.calls).toEqual([[false], [true]]);
+ }),
+ ),
+ );
+
+ effectIt.effect("keeps a pending still image rendering when recording ends", () =>
+ withManager((manager) =>
+ Effect.gen(function* () {
+ const { image, capturePage, wc, capture } = yield* setupStill(manager);
+ const pending = Promise.withResolvers();
+ capturePage.mockResolvedValueOnce(image).mockReturnValue(pending.promise);
+ yield* manager.startRecording("tab_still");
+ const fiber = yield* capture.pipe(Effect.forkChild({ startImmediately: true }));
+ yield* TestClock.adjust(0);
+ yield* manager.stopRecording("tab_still");
+ expect(wc.setBackgroundThrottling.mock.calls).toEqual([[false]]);
+ pending.resolve(image);
+ yield* Fiber.join(fiber);
+ expect(wc.setBackgroundThrottling.mock.calls).toEqual([[false], [true]]);
+ }),
+ ),
+ );
+
+ effectIt.effect("saves available pixels when paint readiness never settles", () =>
+ withManager((manager) =>
+ Effect.gen(function* () {
+ const paint = Promise.withResolvers();
+ const { capturePage, wc, capture } = yield* setupStill(manager, paint.promise);
+ const first = yield* Effect.exit(capture).pipe(
+ Effect.forkChild({ startImmediately: true }),
+ );
+ yield* TestClock.adjust(1_001);
+ expect(Exit.isSuccess(yield* Fiber.join(first))).toBe(true);
+ expect(capturePage).toHaveBeenCalledTimes(2);
+ expect(writeFile.mock.calls.map((call) => call[1])).toEqual([Buffer.from("fresh-png")]);
+ expect(wc.setBackgroundThrottling.mock.calls).toEqual([[false], [true]]);
+ }),
+ ),
+ );
+
effectIt.effect("keeps every recorded guest unthrottled until its frame capture stops", () =>
withManager((manager) =>
Effect.gen(function* () {
@@ -2260,6 +2463,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())),
@@ -2580,6 +2784,116 @@ describe("PreviewManager", () => {
),
);
+ effectIt.effect(
+ "publishes human ownership only on transitions while retaining every recording press",
+ () =>
+ withManager((manager) =>
+ Effect.gen(function* () {
+ let humanInput: ((input: unknown) => void) | undefined;
+ const contents = makeTestPreviewWebContents(async () => ({
+ toJPEG: () => Buffer.from("frame"),
+ getSize: () => ({ width: 800, height: 600 }),
+ }));
+ contents.ipc.on = (channel, callback) => {
+ if (channel === "preview:human-input")
+ humanInput = (input) => callback({} as Electron.IpcMainEvent, input);
+ return contents.ipc;
+ };
+ fromId.mockReturnValue(contents);
+ yield* manager.createTab("tab_human");
+ yield* manager.registerWebview("tab_human", 42);
+ yield* manager.startRecording("tab_human", {
+ showKeyPresses: true,
+ showMousePresses: true,
+ });
+ const controllers: string[] = [];
+ const feedback = yield* Queue.unbounded();
+ webviewSend.mockImplementation((channel) => {
+ if (channel === "preview:recording-controller") Queue.offerUnsafe(feedback, undefined);
+ });
+ yield* manager.subscribeStateChanges((_tabId, state) =>
+ Effect.sync(() => {
+ controllers.push(state.controller);
+ }),
+ );
+ for (const press of [
+ { kind: "pointer", x: 10, y: 20, button: 0 },
+ { kind: "pointer", x: 30, y: 40, button: 0 },
+ { kind: "key", key: "a", code: "KeyA" },
+ ]) {
+ humanInput?.(press);
+ yield* Queue.take(feedback);
+ }
+ expect(controllers).toEqual(["human"]);
+ expect(
+ webviewSend.mock.calls.filter(
+ ([channel]) => channel === "preview:recording-controller",
+ ),
+ ).toEqual([
+ ["preview:recording-controller", "human", { x: 10, y: 20 }],
+ ["preview:recording-controller", "human", { x: 30, y: 40 }],
+ ["preview:recording-controller", "human", undefined],
+ ]);
+ yield* TestClock.adjust(750);
+ expect(controllers).toEqual(["human", "none"]);
+ }),
+ ),
+ );
+
+ effectIt.effect("keeps human ownership until the last input's idle deadline", () =>
+ withManager((manager) =>
+ Effect.gen(function* () {
+ let humanInput: ((input: unknown) => void) | undefined;
+ const contents = makeTestPreviewWebContents(async () => ({
+ toJPEG: () => Buffer.from("frame"),
+ getSize: () => ({ width: 800, height: 600 }),
+ }));
+ contents.ipc.on = (channel, callback) => {
+ if (channel === "preview:human-input")
+ humanInput = (input) => callback({} as Electron.IpcMainEvent, input);
+ return contents.ipc;
+ };
+ fromId.mockReturnValue(contents);
+ yield* manager.createTab("tab_idle");
+ yield* manager.registerWebview("tab_idle", 42);
+ const controllers: string[] = [];
+ yield* manager.subscribeStateChanges((_tabId, state) =>
+ Effect.sync(() => {
+ controllers.push(state.controller);
+ }),
+ );
+ const press = () => humanInput?.({ kind: "key", key: "a", code: "KeyA" });
+ press();
+ yield* TestClock.adjust(500);
+ press();
+ yield* TestClock.adjust(749);
+ expect(controllers).toEqual(["human"]);
+ yield* TestClock.adjust(1);
+ expect(controllers).toEqual(["human", "none"]);
+
+ press();
+ yield* TestClock.adjust(500);
+ const staleInput = humanInput;
+ const replacement = makeTestPreviewWebContents(
+ async () => ({
+ toJPEG: () => Buffer.from("frame"),
+ getSize: () => ({ width: 800, height: 600 }),
+ }),
+ 43,
+ );
+ replacement.ipc.on = contents.ipc.on;
+ contents.isDestroyed = () => true;
+ fromId.mockImplementation((id) => (id === 43 ? replacement : null));
+ yield* manager.registerWebview("tab_idle", 43);
+ expect(controllers.at(-1)).toBe("none");
+ const count = controllers.length;
+ staleInput?.({ kind: "key", key: "b", code: "KeyB" });
+ yield* TestClock.adjust(750);
+ expect(controllers).toHaveLength(count);
+ }),
+ ),
+ );
+
effectIt.effect("gates recording decorations and isolates failed subscribers", () =>
withManager((manager) =>
Effect.gen(function* () {
diff --git a/apps/desktop/src/preview/Manager.ts b/apps/desktop/src/preview/Manager.ts
index eba18ab631dd0..32ac876996c81 100644
--- a/apps/desktop/src/preview/Manager.ts
+++ b/apps/desktop/src/preview/Manager.ts
@@ -387,7 +387,8 @@ interface ManagedListeners {
readonly webContents: Electron.WebContents;
}
-type FrameCaptureConsumer = "picture-in-picture" | "recording";
+// Each still-image request owns a separate, short-lived rendering lease.
+type FrameCaptureConsumer = "picture-in-picture" | "recording" | symbol;
interface FrameCaptureSession {
readonly recordingInputOptions?: RecordingInputOptions;
@@ -888,7 +889,6 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
const update = Effect.fn("PreviewManager.update")(function* (
tabId: string,
patch: Partial,
- humanPoint?: { readonly x: number; readonly y: number },
) {
const updatedAt = yield* currentIso;
const next = yield* SynchronizedRef.modify(tabsRef, (tabs) => {
@@ -904,17 +904,6 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
});
// syncTabAudible can commit after this update; emitIfCurrent prevents publishing a stale snapshot.
if (Option.isSome(next)) {
- if (patch.controller !== undefined && next.value.webContentsId != null) {
- const capture = (yield* SynchronizedRef.get(frameCaptureSessionsRef)).get(tabId);
- const webContentsId = next.value.webContentsId;
- if (capture?.consumers.has("recording")) {
- yield* attempt({ operation: "recording.controller", tabId }, () => {
- const contents = webContents.fromId(webContentsId);
- if (contents && !contents.isDestroyed())
- contents.send(RECORDING_CONTROLLER_CHANNEL, patch.controller, humanPoint);
- }).pipe(Effect.ignore);
- }
- }
yield* emitIfCurrent(tabId, next.value);
}
});
@@ -1107,28 +1096,13 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
),
scope,
);
- const handleDebuggerMessage = Effect.fnUntraced(function* (
- method: string,
- params: Record,
- ) {
- if (method === "Page.screencastFrame") {
- const sessionId = params["sessionId"];
- if (typeof sessionId === "number") {
- yield* attemptPromise(
- {
- operation: "ackScreencastFrame",
- webContentsId: wc.id,
- },
- () => wcDebugger.sendCommand("Page.screencastFrameAck", { sessionId }),
- ).pipe(Effect.ignore);
- }
- }
+ const handleDebuggerMessage = Effect.fnUntraced(function* (method: string) {
if (method === "Runtime.consoleAPICalled" || method === "Runtime.exceptionThrown") {
yield* Queue.offer(consoleReleases, undefined);
}
});
- const onMessage: BrowserControlSession["onMessage"] = (_event, method, params) => {
- runFork(handleDebuggerMessage(method, params));
+ const onMessage: BrowserControlSession["onMessage"] = (_event, method) => {
+ runFork(handleDebuggerMessage(method));
};
const control: BrowserControlSession = {
webContentsId: wc.id,
@@ -1443,21 +1417,75 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
}),
);
};
+ let humanInputWorker = false;
+ let humanInputDeadline = 0;
+ let listening = true;
+ const publishHumanController = Effect.fn("PreviewManager.publishHumanController")(function* (
+ controller: "human" | "none",
+ humanPoint?: { readonly x: number; readonly y: number },
+ ) {
+ const now = yield* currentMillis;
+ const updatedAt = yield* currentIso;
+ const result = yield* SynchronizedRef.modify(tabsRef, (tabs) => {
+ const current = tabs.get(tabId);
+ if (
+ !current ||
+ current.webContentsId !== wc.id ||
+ (controller === "human"
+ ? !listening || webContents.fromId(wc.id) !== wc
+ : current.controller !== "human" || humanInputDeadline > now)
+ )
+ return [undefined, tabs] as const;
+ const changed = current.controller !== controller;
+ const state = changed ? { ...current, controller, updatedAt } : current;
+ return [
+ { state, changed },
+ changed
+ ? replaceMap(tabs, (copy) => {
+ copy.set(tabId, state);
+ })
+ : tabs,
+ ] as const;
+ });
+ if (!result) return;
+ const capture = (yield* SynchronizedRef.get(frameCaptureSessionsRef)).get(tabId);
+ if (capture?.consumers.has("recording")) {
+ yield* attempt({ operation: "recording.controller", tabId }, () => {
+ if (!wc.isDestroyed()) wc.send(RECORDING_CONTROLLER_CHANNEL, controller, humanPoint);
+ }).pipe(Effect.ignore);
+ }
+ if (result.changed) yield* emitIfCurrent(tabId, result.state);
+ });
+ yield* Scope.addFinalizer(
+ scope,
+ Effect.gen(function* () {
+ listening = false;
+ humanInputDeadline = 0;
+ yield* publishHumanController("none");
+ }),
+ );
const handleHumanInput = Effect.fn("PreviewManager.handleHumanInput")(function* (
rawSignal?: unknown,
) {
- yield* update(
- tabId,
- { controller: "human" },
+ if (!listening) return;
+ humanInputDeadline = (yield* currentMillis) + 750;
+ if (!humanInputWorker) {
+ humanInputWorker = true;
+ yield* Effect.gen(function* () {
+ let remaining: number;
+ while ((remaining = humanInputDeadline - (yield* currentMillis)) > 0) {
+ yield* Effect.sleep(remaining);
+ }
+ humanInputWorker = false;
+ yield* publishHumanController("none");
+ }).pipe(Effect.forkIn(scope));
+ }
+ yield* publishHumanController(
+ "human",
isPreviewInputSignal(rawSignal) && rawSignal.kind === "pointer"
? { x: rawSignal.x, y: rawSignal.y }
: undefined,
);
- yield* Effect.sleep(750);
- const tabs = yield* SynchronizedRef.get(tabsRef);
- if (tabs.get(tabId)?.controller === "human") {
- yield* update(tabId, { controller: "none" });
- }
});
const recordingInput = (_event: unknown, input: unknown) => {
if (!isRecordingInput(input)) return;
@@ -1799,7 +1827,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(
[
@@ -2607,12 +2638,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);
}
}
});
@@ -2651,7 +2691,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
const [createdAt, millis, image] = yield* Effect.all([
currentIso,
currentMillis,
- capturePageWithRetry(
+ captureStillImage(
{
operation: "captureScreenshot.capturePage",
tabId,
@@ -2699,6 +2739,100 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
};
});
+ const captureStillImage = Effect.fn("PreviewManager.captureStillImage")(function* (
+ errorContext: PreviewOperationContext,
+ tabId: string,
+ wc: Electron.WebContents,
+ ) {
+ const consumer = Symbol("still-image");
+ return yield* Effect.acquireUseRelease(
+ startFrameCapture(tabId, consumer),
+ () =>
+ Effect.gen(function* () {
+ // A DOM mutation can precede its compositor frame even in a shown
+ // window. Keep the original guest rendering through the next paint;
+ // a hidden guest otherwise returns old pixels or never completes.
+ const probe = Effect.fn("PreviewManager.probeStillImagePaint")(function* (
+ send: (
+ method: string,
+ params?: Record,
+ ) => Effect.Effect,
+ ) {
+ // CDP executes against the current document without Electron's
+ // did-stop-loading gate. Isolate scheduling globals from page code.
+ const tree = (yield* send("Page.getFrameTree")) as
+ | { frameTree?: { frame?: { id?: string } } }
+ | undefined;
+ const frameId = tree?.frameTree?.frame?.id;
+ if (typeof frameId !== "string")
+ return yield* new PreviewOperationError({
+ ...errorContext,
+ cause: new Error("The preview paint frame is unavailable."),
+ });
+ const world = (yield* send("Page.createIsolatedWorld", {
+ frameId,
+ worldName: "t3-preview-still-image",
+ })) as { executionContextId?: number } | undefined;
+ if (typeof world?.executionContextId !== "number")
+ return yield* new PreviewOperationError({
+ ...errorContext,
+ cause: new Error("The preview paint context is unavailable."),
+ });
+ const response = (yield* send("Runtime.evaluate", {
+ // Settle and release scheduled work when only timers keep running.
+ // The outer deadline still bounds a frozen renderer.
+ expression: `new Promise(resolve => { let frame; const timer = setTimeout(() => { cancelAnimationFrame(frame); resolve(false); }, ${CAPTURE_PAGE_ATTEMPT_TIMEOUT_MS}); frame = requestAnimationFrame(() => { frame = requestAnimationFrame(() => { clearTimeout(timer); resolve(true); }); }); })`,
+ contextId: world.executionContextId,
+ awaitPromise: true,
+ returnByValue: true,
+ })) as { result?: { value?: unknown }; exceptionDetails?: unknown } | undefined;
+ if (response?.exceptionDetails || response?.result?.value !== true)
+ return yield* new PreviewOperationError({
+ ...errorContext,
+ cause: new Error("The preview paint boundary was not confirmed."),
+ });
+ });
+ const paintReady = Effect.gen(function* () {
+ // Only use an existing owned session; never attach or displace
+ // another debugger to obtain a screenshot.
+ const control = (yield* SynchronizedRef.get(controlSessionsRef)).get(wc.id);
+ if (!control)
+ return yield* new PreviewOperationError({
+ ...errorContext,
+ cause: new Error("The preview paint session is unavailable."),
+ });
+ return yield* probe((method, params) =>
+ attemptPromise(errorContext, () => control.debugger.sendCommand(method, params)),
+ );
+ }).pipe(
+ Effect.timeout(CAPTURE_PAGE_ATTEMPT_TIMEOUT_MS),
+ Effect.catch((error) =>
+ Effect.logWarning(
+ "Preview paint readiness was not confirmed; capturing available pixels with mutation freshness unconfirmed.",
+ { tabId, webContentsId: wc.id, error },
+ ),
+ ),
+ );
+ // Minimized guests can suspend frames even with throttling disabled.
+ // A native capture can resume them; discard its pixels and read again
+ // after the bounded paint probe.
+ const warmup = capturePageWithRetry(errorContext, tabId, wc).pipe(
+ Effect.catchTags({
+ PreviewOperationError: (error) =>
+ Effect.logWarning("Preview warmup capture failed; continuing with final capture.", {
+ tabId,
+ webContentsId: wc.id,
+ error,
+ }),
+ }),
+ );
+ yield* Effect.all([paintReady, warmup], { concurrency: 2, discard: true });
+ return yield* capturePageWithRetry(errorContext, tabId, wc);
+ }),
+ () => stopFrameCapture(tabId, consumer),
+ );
+ });
+
const capturePreviewFrame = Effect.fn("PreviewManager.capturePreviewFrame")(function* (
tabId: string,
) {
@@ -3381,7 +3515,8 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
data: Uint8Array,
) {
const [createdAt, millis] = yield* Effect.all([currentIso, currentMillis]);
- const id = `browser-recording-${millis.toString(36)}`;
+ const uuid = yield* random.uuidV4();
+ const id = `browser-recording-${millis.toString(36)}-${uuid.slice(0, 8)}`;
const extension = recordingFileExtension(mimeType);
const artifactPath = path.join(resolvedArtifactDirectory, `${id}.${extension}`);
yield* fileSystem.makeDirectory(resolvedArtifactDirectory, { recursive: true }).pipe(
@@ -3395,7 +3530,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
}),
),
);
- yield* fileSystem.writeFile(artifactPath, data).pipe(
+ yield* fileSystem.writeFile(artifactPath, data, { flag: "wx" }).pipe(
Effect.mapError(
(cause) =>
new PreviewOperationError({
@@ -3593,6 +3728,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
setAnnotationSendEnabled,
setAudioMuted,
setShown,
+ setCaptureDrawn,
setColorScheme,
setMainWindow,
setForwardedShortcuts: (shortcuts: ReadonlyArray) =>
@@ -3809,6 +3945,7 @@ export class PreviewManager extends Context.Service<
audioMuted: boolean,
) => 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,
@@ -3971,6 +4108,7 @@ export const make = Effect.gen(function* PreviewManagerMake() {
setZoomFactor: operations.setZoomFactor,
setAudioMuted: operations.setAudioMuted,
setShown: operations.setShown,
+ setCaptureDrawn: operations.setCaptureDrawn,
openDevTools: operations.openDevTools,
clearCookies: Effect.fn("PreviewManager.clearCookies")(function* (partitions) {
yield* browserSession
diff --git a/apps/desktop/src/shell/DesktopShellEnvironment.test.ts b/apps/desktop/src/shell/DesktopShellEnvironment.test.ts
index 7d6a5a4f9fe97..e723e1629a7bb 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),
@@ -486,7 +507,7 @@ describe("DesktopShellEnvironment", () => {
Effect.gen(function* () {
const env: NodeJS.ProcessEnv = {
SHELL: "/bin/zsh",
- PATH: "/Users/test/.local/bin:/usr/bin",
+ PATH: " /Users/test/.local/bin:/usr/bin",
};
const commands: ChildProcess.Command[] = [];
@@ -496,7 +517,7 @@ describe("DesktopShellEnvironment", () => {
handler: (command) => {
commands.push(command);
return envOutput({
- PATH: "/opt/homebrew/bin:/usr/bin",
+ PATH: "/opt/homebrew/bin:/usr/bin:/opt/bin ",
SSH_AUTH_SOCK: "/tmp/secretive.sock",
HOMEBREW_PREFIX: "/opt/homebrew",
});
@@ -505,7 +526,7 @@ describe("DesktopShellEnvironment", () => {
assert.equal(commands.length, 1);
assert.equal(commands[0]?._tag === "StandardCommand" ? commands[0].command : "", "/bin/zsh");
- assert.equal(env.PATH, "/opt/homebrew/bin:/usr/bin:/Users/test/.local/bin");
+ assert.equal(env.PATH, "/opt/homebrew/bin:/usr/bin:/opt/bin : /Users/test/.local/bin");
assert.equal(env.SSH_AUTH_SOCK, "/tmp/secretive.sock");
assert.equal(env.HOMEBREW_PREFIX, "/opt/homebrew");
assert.isTrue(prepared);
@@ -621,6 +642,39 @@ describe("DesktopShellEnvironment", () => {
}),
);
+ it.effect.each([
+ {
+ name: "hydrates both Android SDK names when neither is inherited",
+ inherited: {},
+ expected: { ANDROID_HOME: "/shell/android-home", ANDROID_SDK_ROOT: "/shell/android-root" },
+ },
+ {
+ // The device host reads ANDROID_HOME before ANDROID_SDK_ROOT, so a shell
+ // ANDROID_HOME next to an inherited ANDROID_SDK_ROOT would change the SDK.
+ name: "keeps an inherited ANDROID_SDK_ROOT selected over a login-shell ANDROID_HOME",
+ inherited: { ANDROID_SDK_ROOT: "/inherited/android-sdk" },
+ expected: { ANDROID_HOME: undefined, ANDROID_SDK_ROOT: "/inherited/android-sdk" },
+ },
+ ])("$name", ({ inherited, expected }) =>
+ Effect.gen(function* () {
+ const env: NodeJS.ProcessEnv = { SHELL: "/bin/zsh", PATH: "/usr/bin", ...inherited };
+
+ yield* runShellEnvironment({
+ env,
+ platform: "darwin",
+ handler: () =>
+ envOutput({
+ PATH: "/usr/bin",
+ ANDROID_HOME: "/shell/android-home",
+ ANDROID_SDK_ROOT: "/shell/android-root",
+ }),
+ });
+
+ assert.equal(env.ANDROID_HOME, expected.ANDROID_HOME);
+ assert.equal(env.ANDROID_SDK_ROOT, expected.ANDROID_SDK_ROOT);
+ }),
+ );
+
it.effect("keeps mise's PATH record with the login shell PATH", () =>
Effect.gen(function* () {
const env: NodeJS.ProcessEnv = {
@@ -678,6 +732,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 2bce5b3676ca0..0a1d3e96f9bd5 100644
--- a/apps/desktop/src/shell/DesktopShellEnvironment.ts
+++ b/apps/desktop/src/shell/DesktopShellEnvironment.ts
@@ -3,6 +3,7 @@ import {
applyShellEnvironment,
buildEnvironmentCaptureCommand,
listLoginShellCandidates,
+ mergePathValues,
readUserLoginShell,
setWindowsPath,
} from "@t3tools/shared/shell";
@@ -14,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";
@@ -27,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 {
@@ -88,6 +98,8 @@ export class DesktopShellEnvironment extends Context.Service<
const LOGIN_SHELL_ENV_NAMES = [
"PATH",
+ "ANDROID_HOME",
+ "ANDROID_SDK_ROOT",
"DBUS_SESSION_BUS_ADDRESS",
"DISPLAY",
"LANG",
@@ -115,6 +127,7 @@ const LOGIN_SHELL_ENV_NAMES = [
] as const;
const WINDOWS_PROFILE_ENV_NAMES = ["PATH", "FNM_DIR", "FNM_MULTISHELL_PATH"] as const;
const LOCALE_ENV_NAMES = ["LANG", "LC_ALL", "LC_CTYPE"] as const;
+const ANDROID_SDK_ENV_NAMES = ["ANDROID_HOME", "ANDROID_SDK_ROOT"] as const;
const FALLBACK_LC_CTYPE = "en_US.UTF-8";
const WINDOWS_SHELL_CANDIDATES = ["pwsh.exe", "powershell.exe"] as const;
const LOGIN_SHELL_TIMEOUT = Duration.seconds(5);
@@ -122,6 +135,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(
@@ -129,10 +156,12 @@ const trimNonEmpty = (value: string | null | undefined): Option.Option =
Option.filter((entry) => entry.length > 0),
);
-const pathDelimiter = (platform: NodeJS.Platform) => (platform === "win32" ? ";" : ":");
+// POSIX directory names may begin or end with whitespace; mergePathValues trims only on Windows.
+const nonEmptyPath = (value: string | null | undefined): Option.Option =>
+ Option.fromNullishOr(value).pipe(Option.filter((entry) => entry.length > 0));
const readEnvPath = (env: NodeJS.ProcessEnv): Option.Option =>
- trimNonEmpty(env.PATH ?? env.Path ?? env.path);
+ nonEmptyPath(env.PATH ?? env.Path ?? env.path);
const normalizeRuntimeDir = (value: string): string => value.replace(/\/+$/u, "");
@@ -151,39 +180,16 @@ const linuxRuntimeDirCandidates = (
return candidates.filter((candidate) => candidate.length > 0);
};
-const pathComparisonKey = (entry: string, platform: NodeJS.Platform) => {
- const normalized = entry.trim().replace(/^"+|"+$/g, "");
- return platform === "win32" ? normalized.toLowerCase() : normalized;
-};
-
-const sanitizePathEntry = (entry: string, platform: NodeJS.Platform) =>
- platform === "win32" ? entry.replaceAll('"', "") : entry;
-
const mergePaths = (
platform: NodeJS.Platform,
values: ReadonlyArray>,
-): Option.Option => {
- const delimiter = pathDelimiter(platform);
- const entries: string[] = [];
- const seen = new Set();
-
- for (const value of values) {
- if (Option.isNone(value)) continue;
-
- for (const entry of value.value.split(delimiter)) {
- const sanitized = sanitizePathEntry(entry.trim(), platform);
- if (sanitized.length === 0) continue;
-
- const key = pathComparisonKey(sanitized, platform);
- if (key.length === 0 || seen.has(key)) continue;
-
- seen.add(key);
- entries.push(sanitized);
- }
- }
-
- return entries.length > 0 ? Option.some(entries.join(delimiter)) : Option.none();
-};
+): Option.Option =>
+ Option.fromNullishOr(
+ values.reduce(
+ (merged, value) => mergePathValues(merged, Option.getOrUndefined(value), platform),
+ undefined,
+ ),
+ );
const knownWindowsCliDirs = (env: NodeJS.ProcessEnv): ReadonlyArray => [
...trimNonEmpty(env.APPDATA).pipe(
@@ -263,6 +269,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,
@@ -281,7 +288,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], {
@@ -347,6 +354,7 @@ const readLoginShellEnvironment = (
names: ReadonlyArray,
env: NodeJS.ProcessEnv,
timeout: Duration.Duration,
+ terminateGrace: Duration.Duration,
): Effect.Effect<
EnvironmentPatch,
DesktopShellEnvironmentCommandTimeoutError,
@@ -360,6 +368,7 @@ const readLoginShellEnvironment = (
args: ["-ilc", buildEnvironmentCaptureCommand(shell, names)],
env,
timeout,
+ terminateGrace,
}).pipe(Effect.map((output) => extractEnvironment(output, names)));
const readLaunchctlPath = (env: NodeJS.ProcessEnv) =>
@@ -376,6 +385,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 {};
@@ -393,7 +403,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) {
@@ -411,8 +422,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 },
);
@@ -436,6 +452,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,
@@ -446,22 +465,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({})),
);
},
}),
@@ -482,7 +507,7 @@ const installPosixEnvironment = Effect.fn("desktop.shellEnvironment.installPosix
? yield* readLaunchctlPath(config.env)
: Option.none();
const mergedPath = mergePaths(config.platform, [
- trimNonEmpty(shellEnvironment.PATH).pipe(Option.orElse(() => launchctlPath)),
+ nonEmptyPath(shellEnvironment.PATH).pipe(Option.orElse(() => launchctlPath)),
readEnvPath(config.env),
]);
@@ -534,6 +559,16 @@ const installPosixEnvironment = Effect.fn("desktop.shellEnvironment.installPosix
config.env.S2CODE_TELEMETRY_ENABLED?.trim() || config.env.SHUV2CODE_TELEMETRY_ENABLED?.trim();
if (telemetryEnabled) config.env.T3CODE_TELEMETRY_ENABLED = telemetryEnabled;
else delete config.env.T3CODE_TELEMETRY_ENABLED;
+ // The device host picks the Android SDK from ANDROID_HOME before ANDROID_SDK_ROOT,
+ // so a profile-only ANDROID_HOME must not shadow an inherited ANDROID_SDK_ROOT.
+ if (ANDROID_SDK_ENV_NAMES.every((name) => Option.isNone(trimNonEmpty(config.env[name])))) {
+ for (const name of ANDROID_SDK_ENV_NAMES) {
+ const value = trimNonEmpty(shellEnvironment[name]);
+ if (Option.isSome(value)) {
+ config.env[name] = value.value;
+ }
+ }
+ }
// Hydrate locale variables together; inherited LC_ALL can override LANG or LC_CTYPE.
if (
@@ -570,7 +605,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),
+ };
},
);
@@ -654,38 +692,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 a37c40d716167..b4e554a3e3ddb 100644
--- a/apps/desktop/src/updates/DesktopRemoteUpdates.test.ts
+++ b/apps/desktop/src/updates/DesktopRemoteUpdates.test.ts
@@ -105,6 +105,29 @@ describe("DesktopRemoteUpdates", () => {
assert.equal(terminals[0]?.requestId, "req-1");
assert.equal(harness.quitAndInstalls(), 0);
+ yield* Queue.offer(requests, request("req-retry"));
+ yield* settle;
+ assert.deepEqual(
+ terminalReports(reports).map((report) => report.outcome),
+ ["ready-to-install", "ready-to-install"],
+ );
+ assert.equal(terminalReports(reports)[1]?.requestId, "req-retry");
+ assert.equal(terminalReports(reports)[1]?.preparedRequestId, "req-1");
+ assert.equal(harness.quitAndInstalls(), 0);
+ assert.equal(harness.downloadCount(), 1);
+
+ yield* Queue.offer(requests, {
+ ...request("req-other-track"),
+ channel: "nightly",
+ targetVersion: "1.2.4-nightly.20261027.1",
+ });
+ yield* settle;
+ assert.equal(terminalReports(reports)[2]?.outcome, "failed");
+ assert.equal(
+ terminalReports(reports)[2]?.reason,
+ "A prepared desktop update is already in progress.",
+ );
+
yield* Queue.offer(commits, {
version: 1,
type: "commitDesktopUpdate",
@@ -122,6 +145,49 @@ describe("DesktopRemoteUpdates", () => {
);
});
+ it.effect("does not renew the preparation lease when a retry recovers its token", () => {
+ const harness = makeHarness();
+
+ return runRemoteUpdatesTest(harness, ({ reports, requests, commits }) =>
+ Effect.gen(function* () {
+ harness.emit("update-downloaded", { version: "1.2.4" });
+ yield* settle;
+ yield* Queue.offer(requests, request("req-original"));
+ yield* settle;
+
+ yield* TestClock.adjust(Duration.minutes(4));
+ harness.emit("update-available", { version: "1.2.4" });
+ yield* settle;
+ yield* Queue.offer(requests, request("req-retry"));
+ yield* settle;
+ assert.equal(terminalReports(reports)[1]?.preparedRequestId, "req-original");
+
+ yield* TestClock.adjust(Duration.minutes(1));
+ yield* Queue.offer(commits, {
+ version: 1,
+ type: "commitDesktopUpdate",
+ requestId: "req-original",
+ });
+ yield* settle;
+ assert.equal(
+ terminalReports(reports)[2]?.reason,
+ "This desktop update is no longer prepared.",
+ );
+ assert.equal(harness.quitAndInstalls(), 0);
+
+ yield* Queue.offer(requests, request("req-new"));
+ yield* settle;
+ yield* Queue.offer(commits, {
+ version: 1,
+ type: "commitDesktopUpdate",
+ requestId: "req-new",
+ });
+ yield* settle;
+ assert.equal(harness.quitAndInstalls(), 1);
+ }),
+ );
+ });
+
// Release channels are separate installations, so a packaged host refuses a remote crossing.
it.effect("refuses to switch a packaged Stable host to Nightly", () => {
// In-memory settings keep the channel write off real disk I/O.
@@ -688,7 +754,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,
@@ -698,7 +764,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/DesktopRemoteUpdates.ts b/apps/desktop/src/updates/DesktopRemoteUpdates.ts
index 560e2e78d4bb1..ce2f23ab3e781 100644
--- a/apps/desktop/src/updates/DesktopRemoteUpdates.ts
+++ b/apps/desktop/src/updates/DesktopRemoteUpdates.ts
@@ -32,6 +32,8 @@ const PREPARED_UPDATE_TTL = Duration.minutes(5);
interface PreparedUpdate {
readonly requestId: string;
+ readonly channel: DesktopTelemetryRequestDesktopUpdate["channel"];
+ readonly targetVersion: DesktopTelemetryRequestDesktopUpdate["targetVersion"];
readonly downloadedVersion: string;
readonly status: "prepared" | "committing" | "failed";
readonly failureReason?: string;
@@ -67,7 +69,11 @@ export const listen: Effect.Effect<
const publishReport = (
state: DesktopUpdateState,
- terminal?: { readonly outcome: DesktopUpdateRemoteOutcome; readonly reason?: string },
+ terminal?: {
+ readonly outcome: DesktopUpdateRemoteOutcome;
+ readonly reason?: string;
+ readonly preparedRequestId?: string;
+ },
explicitRequestId?: string,
): Effect.Effect => {
const reason = normalizeRemoteUpdateReason(terminal?.reason);
@@ -82,6 +88,9 @@ export const listen: Effect.Effect<
? { requestId: requestId.value }
: {}),
...(terminal === undefined ? {} : { outcome: terminal.outcome }),
+ ...(terminal?.preparedRequestId === undefined
+ ? {}
+ : { preparedRequestId: terminal.preparedRequestId }),
...(reason ? { reason } : {}),
state,
}),
@@ -167,8 +176,22 @@ export const listen: Effect.Effect<
: ([current, current] as const),
);
if (Option.isSome(prepared) && prepared.value.status !== "failed") {
+ const state = yield* updates.getState;
+ if (
+ prepared.value.status === "prepared" &&
+ prepared.value.channel === request.channel &&
+ prepared.value.targetVersion === request.targetVersion &&
+ state.downloadedVersion === prepared.value.downloadedVersion
+ ) {
+ yield* publishReport(
+ state,
+ { outcome: "ready-to-install", preparedRequestId: prepared.value.requestId },
+ request.requestId,
+ );
+ return;
+ }
yield* publishReport(
- yield* updates.getState,
+ state,
{
outcome: "failed",
reason: "A prepared desktop update is already in progress.",
@@ -301,6 +324,8 @@ export const listen: Effect.Effect<
preparedUpdateRef,
Option.some({
requestId: request.requestId,
+ channel: request.channel,
+ targetVersion: request.targetVersion,
downloadedVersion: state.downloadedVersion,
status: "prepared",
expiresAt:
diff --git a/apps/desktop/src/updates/DesktopUpdates.test.ts b/apps/desktop/src/updates/DesktopUpdates.test.ts
index 7c7a05cd69039..dc85f6a7e3cdc 100644
--- a/apps/desktop/src/updates/DesktopUpdates.test.ts
+++ b/apps/desktop/src/updates/DesktopUpdates.test.ts
@@ -177,7 +177,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(
@@ -190,14 +190,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");
@@ -319,15 +328,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 });
+ }),
+ ),
),
});
@@ -335,22 +355,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 56298cebf0861..c2e9a5cf465c0 100644
--- a/apps/desktop/src/updates/DesktopUpdates.ts
+++ b/apps/desktop/src/updates/DesktopUpdates.ts
@@ -65,7 +65,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";
@@ -332,6 +332,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,
@@ -536,6 +540,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,
) {
@@ -577,8 +598,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.
@@ -615,15 +638,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(
@@ -816,47 +854,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 };
}
@@ -1000,6 +1026,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(
@@ -1179,6 +1206,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 c309d6b409d91..962723160d215 100644
--- a/apps/desktop/src/window/DesktopApplicationMenu.ts
+++ b/apps/desktop/src/window/DesktopApplicationMenu.ts
@@ -33,6 +33,7 @@ export class DesktopApplicationMenu extends Context.Service<
>()("@t3tools/desktop/window/DesktopApplicationMenu") {}
type DesktopApplicationMenuRuntimeServices =
+ | DesktopEnvironment.DesktopEnvironment
| DesktopUpdates.DesktopUpdates
| DesktopWindow.DesktopWindow
| ElectronDialog.ElectronDialog;
@@ -64,7 +65,11 @@ const runMainContentsCommand = Effect.fn("desktop.menu.runMainContentsCommand")(
yield* desktopWindow.runMainContentsCommand(command);
});
+const describeUpdate = (displayName: string, version: string | null) =>
+ version === null ? `A new version of ${displayName}` : `${displayName} ${version}`;
+
const checkForUpdatesFromMenu = Effect.gen(function* () {
+ const { displayName } = yield* DesktopEnvironment.DesktopEnvironment;
const updates = yield* DesktopUpdates.DesktopUpdates;
const electronDialog = yield* ElectronDialog.ElectronDialog;
const result = yield* updates.check("menu");
@@ -74,9 +79,38 @@ const checkForUpdatesFromMenu = Effect.gen(function* () {
yield* electronDialog.showMessageBox({
type: "info",
title: "You're up to date!",
- message: `S2Code ${updateState.currentVersion} is currently the newest version available.`,
+ message: `${displayName} ${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(displayName, updateState.availableVersion)} is available.`,
+ detail: `You're running ${displayName} ${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(displayName, updateState.availableVersion)} is already downloading.`,
+ buttons: ["OK"],
+ });
+ } else if (updateState.status === "downloaded") {
+ const { response } = yield* electronDialog.showMessageBox({
+ type: "info",
+ title: "Update ready",
+ message: `${describeUpdate(displayName, updateState.downloadedVersion ?? updateState.availableVersion)} is ready to install.`,
+ detail: `${displayName} 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/desktop/src/window/DesktopWindow.test.ts b/apps/desktop/src/window/DesktopWindow.test.ts
index 6918d54d0adde..2fb0b50cdfad6 100644
--- a/apps/desktop/src/window/DesktopWindow.test.ts
+++ b/apps/desktop/src/window/DesktopWindow.test.ts
@@ -208,17 +208,20 @@ const layerElectronTheme = Layer.succeed(ElectronTheme.ElectronTheme, {
onUpdated: () => Effect.void,
} satisfies ElectronTheme.ElectronTheme["Service"]);
-const layerDesktopEnvironment = DesktopEnvironment.layer(environmentInput).pipe(
- Layer.provide(
- Layer.mergeAll(
- NodeServices.layer,
- DesktopConfig.layerTest({
- T3CODE_PORT: "3773",
- VITE_DEV_SERVER_URL: "http://127.0.0.1:5733",
- }),
+const layerDesktopEnvironmentFor = (platform: NodeJS.Platform) =>
+ DesktopEnvironment.layer({ ...environmentInput, platform }).pipe(
+ Layer.provide(
+ Layer.mergeAll(
+ NodeServices.layer,
+ DesktopConfig.layerTest({
+ T3CODE_PORT: "3773",
+ VITE_DEV_SERVER_URL: "http://127.0.0.1:5733",
+ }),
+ ),
),
- ),
-);
+ );
+
+const layerDesktopEnvironment = layerDesktopEnvironmentFor(environmentInput.platform);
const desktopWindowBoundsEquivalence = Schema.toEquivalence(
DesktopAppSettings.DesktopWindowBoundsSchema,
@@ -244,6 +247,12 @@ function layerTest(input: {
readonly previewZoomReapplies?: number[];
readonly onReveal?: (window: Electron.BrowserWindow) => void;
readonly focusedWindow?: Electron.BrowserWindow;
+ readonly fallbackWindow?: Electron.BrowserWindow;
+ readonly platform?: NodeJS.Platform;
+ readonly appearanceWindows?: ReadonlyArray<{
+ readonly window: Electron.BrowserWindow;
+ readonly titleBarOverlay: boolean;
+ }>;
readonly primaryPasteEnabled?: boolean;
readonly previewPasskeyBridgeEnabled?: boolean;
}) {
@@ -292,7 +301,9 @@ function layerTest(input: {
Effect.as(input.window),
),
main: Ref.get(input.mainWindow),
- currentMainOrFirst: Ref.get(input.mainWindow),
+ currentMainOrFirst: Ref.get(input.mainWindow).pipe(
+ Effect.map(Option.orElse(() => Option.fromNullishOr(input.fallbackWindow ?? null))),
+ ),
focusedMainOrFirst:
input.focusedWindow === undefined
? Ref.get(input.mainWindow)
@@ -303,7 +314,14 @@ function layerTest(input: {
reveal: (window) => Effect.sync(() => input.onReveal?.(window)),
sendAll: () => Effect.void,
destroyAll: input.destroyAll ?? Effect.void,
- syncAllAppearance: (sync) => sync(input.window),
+ syncAllAppearance: (sync) =>
+ input.appearanceWindows === undefined
+ ? sync(input.window, { titleBarOverlay: true })
+ : Effect.forEach(
+ input.appearanceWindows,
+ ({ window, titleBarOverlay }) => sync(window, { titleBarOverlay }),
+ { discard: true },
+ ),
} satisfies ElectronWindow.ElectronWindow["Service"]);
return DesktopWindow.layer.pipe(
@@ -315,7 +333,9 @@ function layerTest(input: {
recordMetrics: () => Effect.void,
shutdown: Effect.void,
}),
- layerDesktopEnvironment,
+ input.platform === undefined
+ ? layerDesktopEnvironment
+ : layerDesktopEnvironmentFor(input.platform),
layerDesktopAppSettings,
layerDesktopClientSettings,
layerDesktopServerExposure,
@@ -424,7 +444,8 @@ const makeSplashScenario = (createOutcomes: readonly (Electron.BrowserWindow | n
reveal: (window) => Ref.update(revealedWindows, (windows) => [...windows, window]),
sendAll: () => Effect.void,
destroyAll: Effect.void,
- syncAllAppearance: (sync) => (fallbackWindow ? sync(fallbackWindow) : Effect.void),
+ syncAllAppearance: (sync) =>
+ fallbackWindow ? sync(fallbackWindow, { titleBarOverlay: true }) : Effect.void,
} satisfies ElectronWindow.ElectronWindow["Service"];
const layer = DesktopWindow.layer.pipe(
@@ -827,7 +848,7 @@ describe("DesktopWindow", () => {
}),
);
- it.effect("reloads and inspects the main window even when a popup has focus", () =>
+ it.effect("routes menu commands to the main window even when a popup has focus", () =>
Effect.gen(function* () {
const fakeWindow = makeFakeBrowserWindow();
const popup = makeFakeBrowserWindow();
@@ -847,7 +868,10 @@ describe("DesktopWindow", () => {
yield* desktopWindow.runMainContentsCommand("reload");
yield* desktopWindow.runMainContentsCommand("forceReload");
yield* desktopWindow.runMainContentsCommand("toggleDevTools");
+ yield* desktopWindow.dispatchMenuAction("open-settings");
+ assert.deepEqual(fakeWindow.send.mock.calls, [["desktop:menu-action", "open-settings"]]);
+ assert.equal(popup.send.mock.calls.length, 0);
assert.equal(fakeWindow.reload.mock.calls.length, 1);
assert.equal(fakeWindow.reloadIgnoringCache.mock.calls.length, 1);
assert.equal(fakeWindow.toggleDevTools.mock.calls.length, 1);
@@ -858,6 +882,38 @@ describe("DesktopWindow", () => {
}),
);
+ it.effect("recreates main for Settings when only an unregistered popup survives", () =>
+ Effect.gen(function* () {
+ const main = makeFakeBrowserWindow();
+ const auxiliary = makeFakeBrowserWindow();
+ const createCount = yield* Ref.make(0);
+ const mainWindow = yield* Ref.make>(Option.none());
+
+ yield* Effect.gen(function* () {
+ const windows = yield* DesktopWindow.DesktopWindow;
+ yield* windows.dispatchMenuAction("open-settings");
+ assert.deepEqual(main.send.mock.calls, [["desktop:menu-action", "open-settings"]]);
+ assert.equal(auxiliary.send.mock.calls.length, 0);
+ assert.equal(yield* Ref.get(createCount), 1);
+ assert.strictEqual(yield* windows.ensureMain, main.window);
+ assert.equal(yield* Ref.get(createCount), 1);
+ }).pipe(
+ Effect.provide(
+ layerTest({
+ window: main.window,
+ createCount,
+ mainWindow,
+ fallbackWindow: auxiliary.window,
+ desktopSettings: {
+ ...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
+ localEnvironmentEnabled: false,
+ },
+ }),
+ ),
+ );
+ }),
+ );
+
it.effect("does not open main or splash windows once quitting has started", () =>
Effect.gen(function* () {
const fake = makeFakeBrowserWindow();
@@ -1171,6 +1227,36 @@ describe("DesktopWindow", () => {
}),
);
+ it.effect("updates title bar overlays only on windows created with one", () =>
+ Effect.gen(function* () {
+ const framed = makeFakeBrowserWindow();
+ vi.mocked(framed.window.setTitleBarOverlay).mockImplementation(() => {
+ throw new TypeError("Titlebar overlay is not enabled");
+ });
+ const overlay = makeFakeBrowserWindow();
+ const layer = layerTest({
+ window: overlay.window,
+ createCount: yield* Ref.make(0),
+ mainWindow: yield* Ref.make>(Option.none()),
+ platform: "win32",
+ appearanceWindows: [
+ { window: framed.window, titleBarOverlay: false },
+ { window: overlay.window, titleBarOverlay: true },
+ ],
+ });
+
+ yield* Effect.gen(function* () {
+ const desktopWindow = yield* DesktopWindow.DesktopWindow;
+ yield* desktopWindow.syncAppearance;
+ }).pipe(Effect.provide(layer));
+
+ assert.deepEqual(vi.mocked(framed.window.setBackgroundColor).mock.calls, [["#ffffff"]]);
+ assert.lengthOf(vi.mocked(framed.window.setTitleBarOverlay).mock.calls, 0);
+ assert.deepEqual(vi.mocked(overlay.window.setBackgroundColor).mock.calls, [["#ffffff"]]);
+ assert.lengthOf(vi.mocked(overlay.window.setTitleBarOverlay).mock.calls, 1);
+ }),
+ );
+
it.effect.each([
{ window: "normal", write: "flush" },
{ window: "normal", write: "debounce" },
diff --git a/apps/desktop/src/window/DesktopWindow.ts b/apps/desktop/src/window/DesktopWindow.ts
index d5e99cfd1ef7e..01cb4c00048c8 100644
--- a/apps/desktop/src/window/DesktopWindow.ts
+++ b/apps/desktop/src/window/DesktopWindow.ts
@@ -343,6 +343,7 @@ function getWindowTitleBarOptions(
function syncWindowAppearance(
window: Electron.BrowserWindow,
+ hasTitleBarOverlay: boolean,
shouldUseDarkColors: boolean,
platform: NodeJS.Platform,
): Effect.Effect {
@@ -353,7 +354,7 @@ function syncWindowAppearance(
window.setBackgroundColor(getInitialWindowBackgroundColor(shouldUseDarkColors));
const { titleBarOverlay } = getWindowTitleBarOptions(shouldUseDarkColors, platform);
- if (typeof titleBarOverlay === "object") {
+ if (hasTitleBarOverlay && typeof titleBarOverlay === "object") {
window.setTitleBarOverlay(titleBarOverlay);
}
});
@@ -424,7 +425,6 @@ export const make = Effect.gen(function* () {
);
const currentMainWindow = electronWindow.currentMainOrFirst.pipe(Effect.flatMap(withoutSplash));
- const focusedMainWindow = electronWindow.focusedMainOrFirst.pipe(Effect.flatMap(withoutSplash));
const zoomWindow = Effect.fn("desktop.window.zoomWindow")(function* (
window: Electron.BrowserWindow,
@@ -1018,7 +1018,7 @@ export const make = Effect.gen(function* () {
const ensureMain = Effect.gen(function* () {
if (yield* Ref.get(desktopState.quitting)) return Option.none();
- const existingWindow = yield* currentMainWindow;
+ const existingWindow = yield* electronWindow.main;
if (Option.isSome(existingWindow)) {
return existingWindow;
}
@@ -1105,7 +1105,8 @@ export const make = Effect.gen(function* () {
{ reveal = true }: { readonly reveal?: boolean } = {},
) {
if (yield* Ref.get(desktopState.quitting)) return;
- const existingWindow = yield* reveal ? focusedMainWindow : electronWindow.main;
+ // Only the main renderer loads the app preload that listens on these channels.
+ const existingWindow = yield* electronWindow.main;
if (Option.isNone(existingWindow) && (!reveal || (yield* waitingForBackend))) return;
const window = Option.isSome(existingWindow) ? existingWindow : yield* ensureMain;
if (Option.isNone(window) || window.value.isDestroyed()) return;
@@ -1202,8 +1203,8 @@ export const make = Effect.gen(function* () {
}),
syncAppearance: Effect.gen(function* () {
const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors;
- yield* electronWindow.syncAllAppearance((window) =>
- syncWindowAppearance(window, shouldUseDarkColors, environment.platform),
+ yield* electronWindow.syncAllAppearance((window, { titleBarOverlay }) =>
+ syncWindowAppearance(window, titleBarOverlay, shouldUseDarkColors, environment.platform),
);
}).pipe(Effect.withSpan("desktop.window.syncAppearance")),
});
diff --git a/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts b/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts
index 692ef5d7735c0..03c40bb189022 100644
--- a/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts
+++ b/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts
@@ -4,8 +4,11 @@ import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
+import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as Redacted from "effect/Redacted";
+import * as Sink from "effect/Sink";
+import * as Stream from "effect/Stream";
import { ChildProcess, ChildProcessSpawner } from "effect/process";
import { afterAll, expect } from "vite-plus/test";
import { DEFAULT_HOME_DIRECTORY } from "@t3tools/shared/productIdentity";
@@ -25,6 +28,7 @@ import {
buildWslRuntimeProbeScript,
parseResolvedPath,
parseWslRuntimeRoot,
+ windowsToWslPathImpl,
} from "./DesktopWslEnvironment.ts";
// The install script only fails the way this file cares about when a real shell
@@ -569,3 +573,48 @@ describe("makeIsAvailable", () => {
}),
);
});
+
+describe("windowsToWslPathImpl", () => {
+ it.effect("runs wslpath without a shell so folder names stay one literal argument", () =>
+ Effect.gen(function* () {
+ const spawned: Array = [];
+ const stdout = Stream.make(new TextEncoder().encode("/mnt/c/a$b & c;(d)\n"));
+ const spawner = ChildProcessSpawner.make((command) => {
+ spawned.push(command);
+ return Effect.succeed(
+ ChildProcessSpawner.makeHandle({
+ pid: ChildProcessSpawner.ProcessId(1),
+ stdout,
+ stderr: Stream.empty,
+ all: stdout,
+ exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)),
+ isRunning: Effect.succeed(false),
+ kill: () => Effect.void,
+ stdin: Sink.drain,
+ getInputFd: () => Sink.drain,
+ getOutputFd: () => Stream.empty,
+ unref: Effect.succeed(Effect.void),
+ }),
+ );
+ });
+
+ const converted = yield* windowsToWslPathImpl("Ubuntu", "C:\\a$b & c;(d)").pipe(
+ Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
+ );
+
+ assert.deepStrictEqual(converted, Option.some("/mnt/c/a$b & c;(d)"));
+ assert.lengthOf(spawned, 1);
+ const [command] = spawned;
+ assert(command?._tag === "StandardCommand");
+ assert.strictEqual(command.command, "wsl.exe");
+ assert.deepStrictEqual(command.args, [
+ "-d",
+ "Ubuntu",
+ "--exec",
+ "wslpath",
+ "-u",
+ "C:/a$b & c;(d)",
+ ]);
+ }),
+ );
+});
diff --git a/apps/desktop/src/wsl/DesktopWslEnvironment.ts b/apps/desktop/src/wsl/DesktopWslEnvironment.ts
index b6a88d3d228a6..810c03d200919 100644
--- a/apps/desktop/src/wsl/DesktopWslEnvironment.ts
+++ b/apps/desktop/src/wsl/DesktopWslEnvironment.ts
@@ -1093,7 +1093,7 @@ const preWarmImpl = (
}),
).pipe(Effect.timeoutOption(PRE_WARM_TIMEOUT), Effect.ignore);
-const windowsToWslPathImpl = (
+export const windowsToWslPathImpl = (
distro: string | null,
windowsPath: string,
): Effect.Effect, never, ChildProcessSpawner.ChildProcessSpawner> => {
@@ -1104,7 +1104,8 @@ const windowsToWslPathImpl = (
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const command = ChildProcess.make(
"wsl.exe",
- [...buildDistroArgs(distro), "--", "wslpath", "-u", normalized],
+ // --exec skips the distro shell, which would expand `$`, `&` or `;` in folder names.
+ [...buildDistroArgs(distro), "--exec", "wslpath", "-u", normalized],
{
stdin: "ignore",
stdout: "pipe",
diff --git a/apps/desktop/vite.config.ts b/apps/desktop/vite.config.ts
index 33850adf09e61..41d4bf6405ebf 100644
--- a/apps/desktop/vite.config.ts
+++ b/apps/desktop/vite.config.ts
@@ -165,6 +165,9 @@ export default defineConfig({
// The Windows lane runs workspace suites concurrently; filesystem-heavy
// desktop integration tests can exceed Vitest's 5 second default there.
testTimeout: 15_000,
+ // `require("electron")` downloads a missing binary, so concurrent workers race to
+ // extract it into the same dist/. Install it once before any worker starts.
+ globalSetup: ["./scripts/ensure-electron-runtime.mjs"],
projects: [
{
extends: true,
diff --git a/apps/marketing/src/lib/releases.test.ts b/apps/marketing/src/lib/releases.test.ts
new file mode 100644
index 0000000000000..13eaa537dd9f8
--- /dev/null
+++ b/apps/marketing/src/lib/releases.test.ts
@@ -0,0 +1,26 @@
+import { afterEach, describe, expect, it, vi } from "vite-plus/test";
+
+import { fetchLatestRelease } from "./releases";
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+describe("fetchLatestRelease", () => {
+ it.each([
+ ["stable", "https://api.github.com/repos/shuv1337/s2code/releases/latest"],
+ ["nightly", "https://api.github.com/repos/shuv1337/s2code/releases?per_page=10"],
+ ] as const)(
+ "rejects a GitHub API error response for %s instead of returning it as a release",
+ async (channel, url) => {
+ vi.stubGlobal("sessionStorage", { getItem: () => null });
+ const fetch = vi.fn(async () =>
+ Response.json({ message: "API rate limit exceeded" }, { status: 403 }),
+ );
+ vi.stubGlobal("fetch", fetch);
+
+ await expect(fetchLatestRelease(channel)).rejects.toThrow("403");
+ expect(fetch).toHaveBeenCalledWith(url);
+ },
+ );
+});
diff --git a/apps/marketing/src/lib/releases.ts b/apps/marketing/src/lib/releases.ts
index 9a9968189458d..ae2486f30362d 100644
--- a/apps/marketing/src/lib/releases.ts
+++ b/apps/marketing/src/lib/releases.ts
@@ -25,12 +25,18 @@ function cacheKey(channel: ReleaseChannel) {
return `t3code-${channel}-release`;
}
+async function fetchJson(url: string): Promise {
+ const response = await fetch(url);
+ if (!response.ok) throw new Error(`GitHub API responded ${response.status}`);
+ return response.json();
+}
+
async function fetchStable(): Promise {
- return fetch(LATEST_API_URL).then((r) => r.json());
+ return fetchJson(LATEST_API_URL);
}
async function fetchNightly(): Promise {
- const list: Release[] = await fetch(LIST_API_URL).then((r) => r.json());
+ const list = await fetchJson(LIST_API_URL);
const nightly = Array.isArray(list)
? list.find((release) => release.tag_name?.includes("-nightly."))
: undefined;
diff --git a/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift b/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift
index 96551d05bbb55..87029ef29fdaf 100644
--- a/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift
+++ b/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift
@@ -1,7 +1,7 @@
import ExpoModulesCore
import UIKit
-private struct ComposerTokenPayload: Decodable {
+private struct ComposerTokenPayload: Decodable, Equatable {
let type: String
let source: String
let label: String
@@ -9,8 +9,16 @@ private struct ComposerTokenPayload: Decodable {
let accent: String?
let tintsIcon: Bool?
let detail: String?
- let start: Int
- let end: Int
+ var start: Int
+ var end: Int
+
+ func rendersLike(_ other: Self) -> Bool {
+ var moved = other
+ moved.start = start
+ moved.end = end
+ // String == accepts canonically equivalent sources, but their UTF-16 lengths differ.
+ return moved == self && source.utf16.elementsEqual(other.source.utf16)
+ }
}
private struct ComposerSelectionPayload: Decodable, Equatable {
@@ -714,8 +722,10 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro
hasControlledDocument = true
if tokensJson != document.tokensJson {
tokensJson = document.tokensJson
- tokens = decode([ComposerTokenPayload].self, from: document.tokensJson) ?? []
- tokensNeedRebuild = true
+ let nextTokens = decode([ComposerTokenPayload].self, from: document.tokensJson) ?? []
+ // Typing before a chip only moves its offsets; rebuilding then makes iOS autocorrect behind the caret.
+ tokensNeedRebuild = tokensNeedRebuild || !nextTokens.elementsEqual(tokens, by: { $0.rendersLike($1) })
+ tokens = nextTokens
}
let previousSelection = sourceSelection()
value = document.value
@@ -739,6 +749,7 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro
func setPlaceholder(_ placeholder: String) {
placeholderLabel.text = placeholder
+ textView.accessibilityLabel = placeholder
setNeedsLayout()
}
@@ -1330,7 +1341,7 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro
private func documentMatchesExpectedTokens() -> Bool {
let source = value as NSString
- let expectedSources = tokens.compactMap { token -> String? in
+ let expectedChips = tokens.compactMap { token -> (Int, String)? in
guard token.start >= 0,
token.end > token.start,
token.end <= source.length,
@@ -1339,18 +1350,22 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro
) == token.source else {
return nil
}
- return token.source
+ return (token.start, token.source)
}
- var renderedSources: [String] = []
+ var renderedChips: [(Int, String)] = []
+ var sourceOffset = 0
textView.attributedText.enumerateAttribute(
.attachment,
in: NSRange(location: 0, length: textView.attributedText.length)
- ) { value, _, _ in
+ ) { value, range, _ in
if let attachment = value as? ComposerTextAttachment {
- renderedSources.append(attachment.source)
+ renderedChips.append((sourceOffset, attachment.source))
+ sourceOffset += (attachment.source as NSString).length
+ } else {
+ sourceOffset += range.length
}
}
- return renderedSources == expectedSources
+ return renderedChips.elementsEqual(expectedChips, by: ==)
}
}
diff --git a/apps/mobile/modules/t3-composer-editor/tests/ios/main.swift b/apps/mobile/modules/t3-composer-editor/tests/ios/main.swift
index 4435b1022161d..32651e2af6352 100644
--- a/apps/mobile/modules/t3-composer-editor/tests/ios/main.swift
+++ b/apps/mobile/modules/t3-composer-editor/tests/ios/main.swift
@@ -11,13 +11,16 @@ func check(_ passed: Bool, _ message: String) {
extension T3ComposerEditorView {
var editor: UITextView { textView }
var text: String { textView.serializedText() }
+ func chip(at location: Int) -> NSTextAttachment? {
+ textView.textStorage.attribute(.attachment, at: location, effectiveRange: nil) as? NSTextAttachment
+ }
}
-func document(_ value: String, revision: Int, resetGeneration: Int = 0, isNativeEcho: Bool = false) -> String {
+func document(_ value: String, revision: Int, resetGeneration: Int = 0, isNativeEcho: Bool = false, tokensJson: String = "[]") -> String {
let payload: [String: Any] = [
"value": value,
"selection": NSNull(),
- "tokensJson": "[]",
+ "tokensJson": tokensJson,
"mostRecentEventCount": revision,
"isNativeEcho": isNativeEcho,
"resetGeneration": resetGeneration,
@@ -33,10 +36,14 @@ func replace(_ view: T3ComposerEditorView, _ target: String, with replacement: S
editor.replace(editor.textRange(from: start, to: end)!, withText: replacement)
}
-func makeEditor(_ value: String) -> T3ComposerEditorView {
+func mention(_ label: String, at start: Int, source: String = "@README.md") -> String {
+ #"[{"type":"mention","source":"\#(source)","label":"\#(label)","start":\#(start),"end":\#(start + source.utf16.count)}]"#
+}
+
+func makeEditor(_ value: String, tokensJson: String = "[]") -> T3ComposerEditorView {
let view = T3ComposerEditorView()
view.frame = CGRect(x: 0, y: 0, width: 320, height: 200)
- view.setControlledDocumentJson(document(value, revision: 0))
+ view.setControlledDocumentJson(document(value, revision: 0, tokensJson: tokensJson))
check(view.text == value, "Initial controlled value was not applied")
return view
}
@@ -108,6 +115,37 @@ do {
)
}
+// An echo that only shifts a chip keeps the rendered text; moving or relabeling the chip redraws it.
+do {
+ let draft = "hi! @README.md @README.md"
+ let view = makeEditor("hi @README.md @README.md", tokensJson: mention("README.md", at: 3))
+ let rendered = view.chip(at: 3)
+ check(rendered != nil, "Harness could not render the chip")
+ view.editor.selectedRange = NSRange(location: 2, length: 0)
+ view.editor.insertText("!")
+ let revision = view.onComposerChange.payloads.last?["eventCount"] as? Int ?? 0
+ view.setControlledDocumentJson(document(draft, revision: revision, isNativeEcho: true, tokensJson: mention("README.md", at: 4)))
+ check(view.chip(at: 4) === rendered, "An echo that only moved a chip replaced the text")
+ view.setControlledDocumentJson(document(draft, revision: revision, tokensJson: mention("Readme", at: 4)))
+ check((view.chip(at: 4) as? ComposerTextAttachment)?.label == "Readme", "A relabeled chip was not redrawn")
+ view.setControlledDocumentJson(document(draft, revision: revision, tokensJson: mention("Readme", at: 15)))
+ check(view.chip(at: 4) == nil && view.chip(at: 15) != nil, "A chip moved to another copy of its source stayed on the old one")
+}
+
+// A chip source that changes only in Unicode normalization is rebuilt from the new text.
+do {
+ let view = makeEditor("@\u{00E9}", tokensJson: mention("e", at: 0, source: "@\u{00E9}"))
+ view.setControlledDocumentJson(document("@e\u{0301}", revision: 0, tokensJson: mention("e", at: 0, source: "@e\u{0301}")))
+ check(view.text.utf16.elementsEqual("@e\u{0301}".utf16), "A renormalized chip source kept the old text")
+}
+
+// The placeholder label is hidden from VoiceOver, so the text view must carry it.
+do {
+ let view = makeEditor("")
+ view.setPlaceholder("Ask anything")
+ check(view.editor.accessibilityLabel == "Ask anything", "VoiceOver label: \(String(describing: view.editor.accessibilityLabel))")
+}
+
print("composer editor tests passed")
private let dropEditor = ComposerTextView()
diff --git a/apps/mobile/modules/t3-native-controls/ios/T3NativeControlsModule.swift b/apps/mobile/modules/t3-native-controls/ios/T3NativeControlsModule.swift
index a3a4b46b45d5a..c93c7d9969c8b 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) }
@@ -306,15 +315,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/modules/t3-terminal/THIRD_PARTY_NOTICES.md b/apps/mobile/modules/t3-terminal/THIRD_PARTY_NOTICES.md
index 0f8a18d50cbd0..91e74e697bab0 100644
--- a/apps/mobile/modules/t3-terminal/THIRD_PARTY_NOTICES.md
+++ b/apps/mobile/modules/t3-terminal/THIRD_PARTY_NOTICES.md
@@ -21,7 +21,7 @@ The Android terminal renderer vendors upstream `libghostty-vt` shared libraries
The web terminal vendors a WebAssembly build from the same revision and uses the same C ABI.
- Upstream project: https://github.com/ghostty-org/ghostty
-- Vendored revision: `9f62873bf195e4d8a762d768a1405a5f2f7b1697`
+- Vendored revision: `3ff6d08fad56f2d6b81420a27bdc56ee707b453e`
- License: MIT
Ghostty's MIT license applies to the vendored Android and web libraries. Keep this notice and both
diff --git a/apps/mobile/modules/t3-terminal/android/src/main/jniLibs/arm64-v8a/libghostty-vt.so b/apps/mobile/modules/t3-terminal/android/src/main/jniLibs/arm64-v8a/libghostty-vt.so
index e086ca8315565..9e3ed70cf88ad 100755
Binary files a/apps/mobile/modules/t3-terminal/android/src/main/jniLibs/arm64-v8a/libghostty-vt.so and b/apps/mobile/modules/t3-terminal/android/src/main/jniLibs/arm64-v8a/libghostty-vt.so differ
diff --git a/apps/mobile/modules/t3-terminal/android/src/main/jniLibs/armeabi-v7a/libghostty-vt.so b/apps/mobile/modules/t3-terminal/android/src/main/jniLibs/armeabi-v7a/libghostty-vt.so
index 5592142ffce8c..9174c0be80f44 100755
Binary files a/apps/mobile/modules/t3-terminal/android/src/main/jniLibs/armeabi-v7a/libghostty-vt.so and b/apps/mobile/modules/t3-terminal/android/src/main/jniLibs/armeabi-v7a/libghostty-vt.so differ
diff --git a/apps/mobile/modules/t3-terminal/android/src/main/jniLibs/x86/libghostty-vt.so b/apps/mobile/modules/t3-terminal/android/src/main/jniLibs/x86/libghostty-vt.so
index bacab7908336a..db7667ea3559b 100755
Binary files a/apps/mobile/modules/t3-terminal/android/src/main/jniLibs/x86/libghostty-vt.so and b/apps/mobile/modules/t3-terminal/android/src/main/jniLibs/x86/libghostty-vt.so differ
diff --git a/apps/mobile/modules/t3-terminal/android/src/main/jniLibs/x86_64/libghostty-vt.so b/apps/mobile/modules/t3-terminal/android/src/main/jniLibs/x86_64/libghostty-vt.so
index f6e0b646a2fb2..0a1f011f8c133 100755
Binary files a/apps/mobile/modules/t3-terminal/android/src/main/jniLibs/x86_64/libghostty-vt.so and b/apps/mobile/modules/t3-terminal/android/src/main/jniLibs/x86_64/libghostty-vt.so differ
diff --git a/apps/mobile/modules/t3-terminal/scripts/build-libghostty-android.sh b/apps/mobile/modules/t3-terminal/scripts/build-libghostty-android.sh
index 55d994d3b363c..b9e225eff4bcd 100755
--- a/apps/mobile/modules/t3-terminal/scripts/build-libghostty-android.sh
+++ b/apps/mobile/modules/t3-terminal/scripts/build-libghostty-android.sh
@@ -7,7 +7,7 @@ MODULE_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)"
VENDOR_DIR="${MODULE_DIR}/../../../../native/libghostty-vt"
PATCH_DIR="${SCRIPT_DIR}/libghostty-android-patches"
-GHOSTTY_REVISION="${GHOSTTY_REVISION:-9f62873bf195e4d8a762d768a1405a5f2f7b1697}"
+GHOSTTY_REVISION="${GHOSTTY_REVISION:-3ff6d08fad56f2d6b81420a27bdc56ee707b453e}"
GHOSTTY_SOURCE_DIR="${GHOSTTY_SOURCE_DIR:-${HOME}/.cache/t3code/ghostty-${GHOSTTY_REVISION:0:8}}"
GHOSTTY_ZIG_VERSION="${GHOSTTY_ZIG_VERSION:-0.15.2}"
GHOSTTY_ZIG="${GHOSTTY_ZIG:-}"
diff --git a/apps/mobile/src/components/ComposerEditor.ios.test.tsx b/apps/mobile/src/components/ComposerEditor.ios.test.tsx
index f7ce1f9918d85..029f454b902f7 100644
--- a/apps/mobile/src/components/ComposerEditor.ios.test.tsx
+++ b/apps/mobile/src/components/ComposerEditor.ios.test.tsx
@@ -128,7 +128,7 @@ vi.mock("../lib/useUniwindTheme", () => ({ useUniwindTheme: () => ({}) }));
vi.mock("../lib/nativeComposerTheme", () => ({ createNativeComposerTheme: () => ({}) }));
vi.mock("../lib/contextChipIconSource", () => ({ contextChipIconUri: () => "" }));
vi.mock("../features/settings/appearance/useScaledTextRole", () => ({
- useScaledTextRole: () => ({ fontSize: 16, lineHeight: 22 }),
+ useComposerTextRole: () => ({ fontSize: 16, lineHeight: 22 }),
}));
vi.mock("../lib/uuid", () => ({ uuidv4: () => "uuid", randomHex: () => "0000" }));
vi.mock("../state/assets", () => ({ assetEnvironment: {} }));
diff --git a/apps/mobile/src/components/ComposerEditor.tsx b/apps/mobile/src/components/ComposerEditor.tsx
index f7118b95b425f..bae452bad7c48 100644
--- a/apps/mobile/src/components/ComposerEditor.tsx
+++ b/apps/mobile/src/components/ComposerEditor.tsx
@@ -76,7 +76,7 @@ export function ComposerEditor({
props.onChangeText(text);
if (draftKey) {
setComposerDraftContext(draftKey, restored.context);
- appendComposerDraftAttachments(draftKey, restored.attachments, { allowOverflow: true });
+ appendComposerDraftAttachments(draftKey, restored.attachments, { restore: true });
}
};
const [selected, setSelected] = useState<{ source: string; start: number; end: number } | null>(
diff --git a/apps/mobile/src/components/ComposerToolbar.tsx b/apps/mobile/src/components/ComposerToolbar.tsx
index 4fd54085c45f1..fdbf27b6f2c25 100644
--- a/apps/mobile/src/components/ComposerToolbar.tsx
+++ b/apps/mobile/src/components/ComposerToolbar.tsx
@@ -285,6 +285,7 @@ export function ComposerActionButton(props: {
}) {
const { scale, smallIconSize } = useAndroidControlSizing();
const circleSize = Math.round((props.size === "large" ? 44 : 30) * scale);
+ const fadeIcon = props.disabled === true && props.variant !== "danger";
return (
-
+ {/* Fade the icon as one layer: a translucent tint, or opacity on a Tabler icon (which
+ copies it onto every path), stacks where the SVG strokes overlap. */}
+
+
+
);
diff --git a/apps/mobile/src/components/ProjectFavicon.test.tsx b/apps/mobile/src/components/ProjectFavicon.test.tsx
index 62eb2bb6b2ba4..6001257b1287f 100644
--- a/apps/mobile/src/components/ProjectFavicon.test.tsx
+++ b/apps/mobile/src/components/ProjectFavicon.test.tsx
@@ -13,6 +13,9 @@ vi.mock("./ui/AppSymbol", () => ({ SymbolView: () => null }));
vi.mock("./ui/AppText", () => ({
AppText: ({ children }: { children?: ReactNode }) => {children},
}));
+vi.mock("../features/settings/appearance/AppearancePreferencesProvider", () => ({
+ useAppearancePreferences: () => ({ themeAppearance: "light" }),
+}));
vi.mock("../state/assets", async () => {
const { Atom } = await import("effect/reactivity");
const url = Atom.make("https://example.test/favicon.png");
diff --git a/apps/mobile/src/components/ProjectFavicon.tsx b/apps/mobile/src/components/ProjectFavicon.tsx
index 1aa33197321c7..d7fa689c9380c 100644
--- a/apps/mobile/src/components/ProjectFavicon.tsx
+++ b/apps/mobile/src/components/ProjectFavicon.tsx
@@ -1,7 +1,7 @@
import { SymbolView } from "./ui/AppSymbol";
import { AppText } from "./ui/AppText";
import { Image } from "expo-image";
-import { memo, useLayoutEffect, useState } from "react";
+import { memo, useLayoutEffect, useMemo, useState } from "react";
import { View } from "react-native";
import type { EnvironmentId, ProjectIconOverride } from "@t3tools/contracts";
import {
@@ -11,6 +11,7 @@ import {
} from "@t3tools/shared/projectFavicon";
import { useAtomValue } from "@effect/atom-react";
import { Atom } from "effect/reactivity";
+import { useAppearancePreferences } from "../features/settings/appearance/AppearancePreferencesProvider";
import { projectFaviconUrlAtom } from "../state/assets";
import {
countGlyphs,
@@ -20,6 +21,7 @@ import {
resolveProjectIconSymbol,
type ProjectIconGlyph,
} from "../lib/projectIcon";
+import { resolveProjectFaviconColorScheme } from "../lib/projectFaviconColorScheme";
import {
beginProjectFaviconRequest,
@@ -160,6 +162,16 @@ function ProjectFaviconImage(props: {
: "loading",
);
+ const { themeAppearance } = useAppearancePreferences();
+ const requestFaviconUrl = faviconRequest?.faviconUrl;
+ const inlineFaviconUrl = useMemo(
+ () =>
+ requestFaviconUrl?.startsWith("data:")
+ ? resolveProjectFaviconColorScheme(requestFaviconUrl, themeAppearance)
+ : null,
+ [requestFaviconUrl, themeAppearance],
+ );
+
const showImage = faviconRequest !== null && status === "loaded";
const fallbackGlyph = showImage ? null : projectAutoMonogram(props.projectTitle);
@@ -187,11 +199,11 @@ function ProjectFaviconImage(props: {
{
anchorNode?.measureInWindow((x, y, width, height) => {
diff --git a/apps/mobile/src/components/ui/AppSymbol.android.tsx b/apps/mobile/src/components/ui/AppSymbol.android.tsx
index c67bf0426179b..d417bed39b99d 100644
--- a/apps/mobile/src/components/ui/AppSymbol.android.tsx
+++ b/apps/mobile/src/components/ui/AppSymbol.android.tsx
@@ -141,6 +141,7 @@ import IconWifiOff from "@tabler/icons-react-native/IconWifiOff";
import IconWorld from "@tabler/icons-react-native/IconWorld";
import IconX from "@tabler/icons-react-native/IconX";
import type { AndroidSymbol, SFSymbol, SymbolViewProps } from "expo-symbols";
+import { StyleSheet, View } from "react-native";
import { withUniwind } from "uniwind";
const ANDROID_ICON_BY_SF_SYMBOL = {
@@ -373,16 +374,20 @@ function AppSymbolView(props: AppSymbolViewProps) {
return props.fallback ?? null;
}
- return (
+ // react-native-svg applies style.transform to its inner path around (0,0), so a
+ // rotated icon draws outside its box. Transform a wrapping View instead.
+ const transformed = StyleSheet.flatten(props.style)?.transform !== undefined;
+ const icon = (
);
+ return transformed ? {icon} : icon;
}
export const SymbolView = withUniwind(AppSymbolView);
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/connection/environment-owned-data-cleanup.test.ts b/apps/mobile/src/connection/environment-owned-data-cleanup.test.ts
new file mode 100644
index 0000000000000..efe489b0fde35
--- /dev/null
+++ b/apps/mobile/src/connection/environment-owned-data-cleanup.test.ts
@@ -0,0 +1,74 @@
+import { Persistence } from "@t3tools/client-runtime/platform";
+import { EnvironmentId } from "@t3tools/contracts";
+import { describe, expect, it } from "@effect/vitest";
+import * as Effect from "effect/Effect";
+import * as Layer from "effect/Layer";
+import * as Logger from "effect/Logger";
+import { vi } from "vite-plus/test";
+
+const harness = vi.hoisted(() => ({
+ clearOutbox: vi.fn<(environmentId: string) => Promise>(),
+ clearDrafts: vi.fn<(environmentId: string) => Promise>(),
+ clearComposerErrors: vi.fn(),
+}));
+
+vi.mock("../state/thread-outbox-removal", () => ({
+ clearThreadOutboxEnvironment: harness.clearOutbox,
+}));
+vi.mock("../state/use-composer-drafts", () => ({
+ clearComposerDraftsEnvironment: harness.clearDrafts,
+}));
+vi.mock("../state/thread-composer-error", () => ({
+ clearThreadComposerErrorsForEnvironment: harness.clearComposerErrors,
+}));
+
+import * as EnvironmentOwnedDataCleanup from "./environment-owned-data-cleanup";
+
+const ENVIRONMENT_ID = EnvironmentId.make("environment-1");
+
+describe("EnvironmentOwnedDataCleanup", () => {
+ it.effect("waits for the other clears and logs a bounded warning when one rejects", () => {
+ const warnings: Array = [];
+ let releaseDrafts = () => {};
+ let draftsCleared = false;
+ // The drafts clear finishes only after the outbox failure is logged.
+ const logger = Logger.make(({ message }) => {
+ warnings.push(message);
+ releaseDrafts();
+ });
+ return Effect.gen(function* () {
+ harness.clearOutbox.mockRejectedValue(new Error("Some queued messages could not be read."));
+ harness.clearDrafts.mockImplementation(() =>
+ new Promise((resolve) => {
+ releaseDrafts = resolve;
+ }).then(() => {
+ draftsCleared = true;
+ }),
+ );
+
+ const cleanup = yield* Persistence.EnvironmentOwnedDataCleanup;
+ yield* cleanup.clear(ENVIRONMENT_ID);
+
+ expect(draftsCleared).toBe(true);
+ expect(warnings).toEqual([
+ [
+ "Could not clear mobile environment-owned data.",
+ {
+ environmentId: ENVIRONMENT_ID,
+ operation: "outbox",
+ errorType: "error",
+ errorName: "Error",
+ stack: expect.any(String),
+ },
+ ],
+ ]);
+ }).pipe(
+ Effect.provide(
+ Layer.merge(
+ EnvironmentOwnedDataCleanup.layer,
+ Logger.layer([logger], { mergeWithExisting: false }),
+ ),
+ ),
+ );
+ });
+});
diff --git a/apps/mobile/src/connection/environment-owned-data-cleanup.ts b/apps/mobile/src/connection/environment-owned-data-cleanup.ts
new file mode 100644
index 0000000000000..28c6cda29a4d3
--- /dev/null
+++ b/apps/mobile/src/connection/environment-owned-data-cleanup.ts
@@ -0,0 +1,48 @@
+import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors";
+import { Persistence } from "@t3tools/client-runtime/platform";
+import type { EnvironmentId } from "@t3tools/contracts";
+import * as Effect from "effect/Effect";
+import * as Layer from "effect/Layer";
+import * as Schema from "effect/Schema";
+
+import { clearThreadComposerErrorsForEnvironment } from "../state/thread-composer-error";
+import { clearThreadOutboxEnvironment } from "../state/thread-outbox-removal";
+import { clearComposerDraftsEnvironment } from "../state/use-composer-drafts";
+
+class EnvironmentOwnedDataClearError extends Schema.TaggedError()(
+ "EnvironmentOwnedDataClearError",
+ { cause: Schema.Defect() },
+) {}
+
+export const layer = Layer.succeed(
+ Persistence.EnvironmentOwnedDataCleanup,
+ Persistence.EnvironmentOwnedDataCleanup.of({
+ clear: Effect.fn("Persistence.EnvironmentOwnedDataCleanup.clear")(function (environmentId) {
+ // Each clear settles on its own: a failure must not interrupt a clear that is still running.
+ const settle = (
+ operation: "outbox" | "drafts",
+ clear: (environmentId: EnvironmentId) => Promise,
+ ) =>
+ Effect.tryPromise({
+ try: () => clear(environmentId),
+ catch: (cause) => new EnvironmentOwnedDataClearError({ cause }),
+ }).pipe(
+ Effect.catch((error) =>
+ Effect.logWarning("Could not clear mobile environment-owned data.", {
+ environmentId,
+ operation,
+ ...safeErrorLogAttributes(error.cause),
+ }),
+ ),
+ );
+ return Effect.all(
+ [
+ settle("outbox", clearThreadOutboxEnvironment),
+ settle("drafts", clearComposerDraftsEnvironment),
+ Effect.sync(() => clearThreadComposerErrorsForEnvironment(environmentId)),
+ ],
+ { concurrency: "unbounded", discard: true },
+ );
+ }),
+ }),
+);
diff --git a/apps/mobile/src/connection/platform.ts b/apps/mobile/src/connection/platform.ts
index 407016ab484d9..de461f35ab104 100644
--- a/apps/mobile/src/connection/platform.ts
+++ b/apps/mobile/src/connection/platform.ts
@@ -1,8 +1,4 @@
-import {
- ClientCapabilities,
- PlatformConnectionSource,
- Persistence,
-} from "@t3tools/client-runtime/platform";
+import { ClientCapabilities, PlatformConnectionSource } from "@t3tools/client-runtime/platform";
import {
ConnectionBlockedError,
ConnectionTransientError,
@@ -25,10 +21,8 @@ import { authClientMetadata } from "../lib/authClientMetadata";
import * as Runtime from "../lib/runtime";
import * as MobileStorage from "../persistence/mobile-storage";
import { appAtomRegistry } from "../state/atom-registry";
-import { clearThreadOutboxEnvironment } from "../state/thread-outbox-removal";
-import { clearComposerDraftsEnvironment } from "../state/use-composer-drafts";
-import { clearThreadComposerErrorsForEnvironment } from "../state/thread-composer-error";
import { mobileApplicationActiveWakeup } from "./app-state-wakeups";
+import * as EnvironmentOwnedDataCleanup from "./environment-owned-data-cleanup";
import * as ConnectionStorage from "./storage";
function networkStatus(state: Network.NetworkState): "unknown" | "offline" | "online" {
@@ -255,22 +249,6 @@ const layerPlatformConnectionSource = Layer.succeed(
const layerProvidedConnectionStorage = ConnectionStorage.layer.pipe(Layer.provide(Runtime.layer));
const layerProvidedCapabilities = layerCapabilities.pipe(Layer.provide(Runtime.layer));
-const layerEnvironmentOwnedDataCleanup = Layer.succeed(
- Persistence.EnvironmentOwnedDataCleanup,
- Persistence.EnvironmentOwnedDataCleanup.of({
- clear: Effect.fn("Persistence.EnvironmentOwnedDataCleanup.clear")((environmentId) =>
- Effect.all(
- [
- Effect.promise(() => clearThreadOutboxEnvironment(environmentId)),
- Effect.promise(() => clearComposerDraftsEnvironment(environmentId)),
- Effect.sync(() => clearThreadComposerErrorsForEnvironment(environmentId)),
- ],
- { concurrency: "unbounded", discard: true },
- ),
- ),
- }),
-);
-
type ConnectionPlatformLayerSource =
| typeof layerProvidedConnectionStorage
| typeof Runtime.layer
@@ -278,7 +256,7 @@ type ConnectionPlatformLayerSource =
| typeof layerWakeups
| typeof layerProvidedCapabilities
| typeof layerPlatformConnectionSource
- | typeof layerEnvironmentOwnedDataCleanup;
+ | typeof EnvironmentOwnedDataCleanup.layer;
export const layer: Layer.Layer<
Layer.Success,
@@ -291,5 +269,5 @@ export const layer: Layer.Layer<
layerWakeups,
layerProvidedCapabilities,
layerPlatformConnectionSource,
- layerEnvironmentOwnedDataCleanup,
+ EnvironmentOwnedDataCleanup.layer,
);
diff --git a/apps/mobile/src/features/connection/LinkedEnvironmentsSection.test.tsx b/apps/mobile/src/features/connection/LinkedEnvironmentsSection.test.tsx
new file mode 100644
index 0000000000000..964d499fd30c4
--- /dev/null
+++ b/apps/mobile/src/features/connection/LinkedEnvironmentsSection.test.tsx
@@ -0,0 +1,169 @@
+import { RegistryContext } from "@effect/atom-react";
+import {
+ NavigationContext,
+ type NavigationProp,
+ type ParamListBase,
+} from "@react-navigation/native";
+import { EnvironmentId } from "@t3tools/contracts";
+import { AtomRegistry } from "effect/reactivity";
+import { act, type ReactNode } from "react";
+import { createRoot } from "react-dom/client";
+import { expect, it, vi } from "vite-plus/test";
+
+// Each listing probes every linked machine, so the test counts the fetches it starts and cuts.
+const fetches = vi.hoisted(() => ({
+ started: 0,
+ interrupted: 0,
+ gate: Promise.resolve(),
+ open: () => {},
+}));
+
+vi.mock("@react-navigation/native", async () => {
+ const { createRequire } = await import("node:module");
+ const { realpathSync } = await import("node:fs");
+ const require = createRequire(import.meta.url);
+ const nativeRequire = createRequire(
+ realpathSync(require.resolve("@react-navigation/native/package.json")),
+ );
+ // Use the shipped focus hook without importing the React Native view layer.
+ const { NavigationContext, useFocusEffect }: typeof import("@react-navigation/native") =
+ nativeRequire("@react-navigation/core");
+ return { NavigationContext, useFocusEffect };
+});
+const appState = vi.hoisted(() => ({ listeners: new Set<(state: string) => void>() }));
+
+vi.mock("react-native", () => ({
+ AppState: {
+ addEventListener: (_event: "change", listener: (state: string) => void) => {
+ appState.listeners.add(listener);
+ return { remove: () => appState.listeners.delete(listener) };
+ },
+ },
+ View: ({ children }: { children?: ReactNode }) => children,
+}));
+vi.mock("../../components/ui/AppText", () => ({
+ AppText: ({ children }: { children?: ReactNode }) => children,
+}));
+vi.mock("../settings/components/SettingsSection", () => ({
+ SettingsSection: ({ children }: { children?: ReactNode }) => children,
+}));
+vi.mock("../../state/entities", () => ({
+ useEnvironmentServerConfig: () => ({
+ environment: { capabilities: { peerLinks: true } },
+ settings: { linkedEnvironmentsEnabled: true },
+ }),
+}));
+vi.mock("../../state/session", () => ({ useEnvironmentScope: () => true }));
+vi.mock("../../state/peerLinks", async () => {
+ const { Atom } = await import("effect/reactivity");
+ const EffectModule = await import("effect/Effect");
+ // Waits for the gate, as a list waits on its slowest linked machine.
+ const list = Atom.make(
+ EffectModule.gen(function* () {
+ fetches.started += 1;
+ yield* EffectModule.promise(() => fetches.gate);
+ return { links: [] };
+ }).pipe(
+ EffectModule.onInterrupt(() =>
+ EffectModule.sync(() => {
+ fetches.interrupted += 1;
+ }),
+ ),
+ ),
+ );
+ return { peerLinkEnvironment: { list: () => list } };
+});
+
+import { LinkedEnvironmentsSection } from "./LinkedEnvironmentsSection";
+
+function createNavigation() {
+ const listeners = { focus: new Set<() => void>(), blur: new Set<() => void>() };
+ let focused = true;
+ return {
+ value: {
+ isFocused: () => focused,
+ addListener: (event: keyof typeof listeners, listener: () => void) => {
+ listeners[event].add(listener);
+ return () => listeners[event].delete(listener);
+ },
+ } as unknown as NavigationProp,
+ focus(next: boolean) {
+ focused = next;
+ act(() => {
+ for (const listener of listeners[next ? "focus" : "blur"]) listener();
+ });
+ },
+ };
+}
+
+function setup() {
+ (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+ fetches.started = 0;
+ fetches.interrupted = 0;
+ fetches.gate = new Promise((resolve) => {
+ fetches.open = resolve;
+ });
+ const registry = AtomRegistry.make();
+ const root = createRoot(document.createElement("div"));
+ const navigation = createNavigation();
+ act(() =>
+ root.render(
+
+
+
+
+ ,
+ ),
+ );
+ return {
+ focus: navigation.focus,
+ moveApp: (state: "active" | "background") =>
+ act(() => {
+ for (const listener of appState.listeners) listener(state);
+ }),
+ settle: () =>
+ act(async () => {
+ fetches.open();
+ await fetches.gate;
+ }),
+ [Symbol.dispose]() {
+ act(() => root.unmount());
+ registry.dispose();
+ },
+ };
+}
+
+it("asks again on focus only once the list it is waiting for has answered", async () => {
+ using screen = setup();
+ // The first focus comes while the first fetch runs, which must not be cut and restarted.
+ expect(fetches).toMatchObject({ started: 1, interrupted: 0 });
+ screen.focus(false);
+ screen.focus(true);
+ expect(fetches).toMatchObject({ started: 1, interrupted: 0 });
+
+ await screen.settle();
+ screen.focus(false);
+ screen.focus(true);
+ expect(fetches).toMatchObject({ started: 2, interrupted: 0 });
+});
+
+it("asks again when the app comes back to the front on this screen", async () => {
+ using screen = setup();
+ await screen.settle();
+ expect(fetches).toMatchObject({ started: 1, interrupted: 0 });
+ fetches.gate = new Promise((resolve) => {
+ fetches.open = resolve;
+ });
+
+ screen.moveApp("background");
+ screen.moveApp("active");
+ expect(fetches).toMatchObject({ started: 2, interrupted: 0 });
+
+ // Coming back while that answer is still out must not cut it and start again.
+ screen.moveApp("background");
+ screen.moveApp("active");
+ expect(fetches).toMatchObject({ started: 2, interrupted: 0 });
+});
diff --git a/apps/mobile/src/features/connection/LinkedEnvironmentsSection.tsx b/apps/mobile/src/features/connection/LinkedEnvironmentsSection.tsx
index 9153c9fa6a1c8..f447e2760277e 100644
--- a/apps/mobile/src/features/connection/LinkedEnvironmentsSection.tsx
+++ b/apps/mobile/src/features/connection/LinkedEnvironmentsSection.tsx
@@ -1,9 +1,10 @@
+import { RegistryContext } from "@effect/atom-react";
import { offersLinkedEnvironments } from "@t3tools/client-runtime/link-request";
import { peerLinkHealth } from "@t3tools/client-runtime/state/peerLinks";
import { useFocusEffect } from "@react-navigation/native";
import { AuthAccessReadScope, type EnvironmentId } from "@t3tools/contracts";
import * as DateTime from "effect/DateTime";
-import { useCallback, useState } from "react";
+import { useCallback, useContext, useState } from "react";
import { AppState, View } from "react-native";
import { AppText as Text } from "../../components/ui/AppText";
@@ -20,8 +21,25 @@ export function LinkedEnvironmentsSection(props: {
const config = useEnvironmentServerConfig(props.environmentId);
const canRead = useEnvironmentScope(props.environmentId, AuthAccessReadScope);
const supported = canRead && offersLinkedEnvironments(config);
- const links = useEnvironmentQuery(
- supported ? peerLinkEnvironment.list({ environmentId: props.environmentId, input: {} }) : null,
+ const listAtom = supported
+ ? peerLinkEnvironment.list({ environmentId: props.environmentId, input: {} })
+ : null;
+ const links = useEnvironmentQuery(listAtom);
+ const registry = useContext(RegistryContext);
+ // Links change outside this client, and the shared list only revalidates when built, so
+ // showing the screen and bringing the app back ask again.
+ useFocusEffect(
+ useCallback(() => {
+ if (listAtom === null) return;
+ const askAgain = () => {
+ if (!registry.get(listAtom).waiting) registry.refresh(listAtom);
+ };
+ askAgain();
+ const subscription = AppState.addEventListener("change", (state) => {
+ if (state === "active") askAgain();
+ });
+ return () => subscription.remove();
+ }, [listAtom, registry]),
);
const [nowMs, setNowMs] = useState(Date.now);
const hasLinks = supported && (links.data?.links.length ?? 0) > 0;
diff --git a/apps/mobile/src/features/connection/useConnectionController.ts b/apps/mobile/src/features/connection/useConnectionController.ts
index 626892d447569..64deaaf8d1e72 100644
--- a/apps/mobile/src/features/connection/useConnectionController.ts
+++ b/apps/mobile/src/features/connection/useConnectionController.ts
@@ -38,7 +38,6 @@ export function useConnectionController() {
const updateBearer = useAtomCommand(updateBearerConnection, { reportFailure: false });
const registerEnvironment = useAtomCommand(environmentCatalog.register, "environment register");
const removeEnvironmentMutation = useAtomCommand(environmentCatalog.remove, "environment remove");
- const retryEnvironmentMutation = useAtomCommand(environmentCatalog.retryNow, "environment retry");
const setEnvironmentEnabledMutation = useAtomCommand(
environmentCatalog.setEnabled,
"environment toggle",
@@ -84,8 +83,6 @@ export function useConnectionController() {
);
const removeEnvironment = (environmentId: EnvironmentId) =>
removeEnvironmentMutation(environmentId);
- const retryEnvironment = (environmentId: EnvironmentId) =>
- retryEnvironmentMutation(environmentId);
const setEnvironmentEnabled = (environmentId: EnvironmentId, enabled: boolean) =>
setEnvironmentEnabledMutation({ environmentId, enabled });
const updateEnvironment = (
@@ -111,7 +108,6 @@ export function useConnectionController() {
connectPairingUrl,
connectRelayEnvironment,
removeEnvironment,
- retryEnvironment,
setEnvironmentEnabled,
updateEnvironment,
refreshRelayEnvironments,
diff --git a/apps/mobile/src/features/connection/useRetryEnvironment.test.tsx b/apps/mobile/src/features/connection/useRetryEnvironment.test.tsx
new file mode 100644
index 0000000000000..da94dedf2e78a
--- /dev/null
+++ b/apps/mobile/src/features/connection/useRetryEnvironment.test.tsx
@@ -0,0 +1,108 @@
+import { RegistryContext } from "@effect/atom-react";
+import { EnvironmentId } from "@t3tools/contracts";
+import {
+ EnvironmentRegistry,
+ PrimaryConnectionTarget,
+ type ConnectionCatalogEntry,
+} from "@t3tools/client-runtime/connection";
+import * as Effect from "effect/Effect";
+import * as Option from "effect/Option";
+import * as SubscriptionRef from "effect/SubscriptionRef";
+import { AtomRegistry } from "effect/reactivity";
+import { act, useLayoutEffect } from "react";
+import { createRoot } from "react-dom/client";
+import { describe, expect, it } from "@effect/vitest";
+import { vi } from "vite-plus/test";
+
+const fixture = vi.hoisted(() => ({
+ environment: undefined as
+ | Pick<
+ EnvironmentRegistry.EnvironmentRegistry["Service"],
+ "entries" | "retryNow" | "setEnabled"
+ >
+ | undefined,
+}));
+
+vi.mock("../../connection/runtime", async () => {
+ const { Atom } = await import("effect/reactivity");
+ const Layer = await import("effect/Layer");
+ const { EnvironmentRegistry } = await import("@t3tools/client-runtime/connection");
+ return {
+ connectionAtomRuntime: Atom.runtime(
+ Layer.suspend(() =>
+ Layer.succeed(
+ EnvironmentRegistry.EnvironmentRegistry,
+ fixture.environment as unknown as EnvironmentRegistry.EnvironmentRegistry["Service"],
+ ),
+ ),
+ ),
+ };
+});
+
+import { useRetryEnvironment } from "./useRetryEnvironment";
+
+const environmentId = EnvironmentId.make("retry-environment");
+
+describe("useRetryEnvironment", () => {
+ it.effect.each([
+ { enabled: false, retries: 0 },
+ { enabled: true, retries: 1 },
+ ])("Retry now with the environment enabled: $enabled", ({ enabled, retries }) =>
+ Effect.gen(function* () {
+ (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+ const target = new PrimaryConnectionTarget({
+ environmentId,
+ label: "Retry",
+ httpBaseUrl: "https://retry.test",
+ wsBaseUrl: "wss://retry.test",
+ });
+ const entries = yield* SubscriptionRef.make<
+ ReadonlyMap
+ >(new Map([[environmentId, { target, profile: Option.none(), enabled }]]));
+ let retryCount = 0;
+ fixture.environment = {
+ entries,
+ retryNow: () =>
+ Effect.sync(() => {
+ retryCount += 1;
+ }),
+ setEnabled: (id, next) =>
+ SubscriptionRef.update(entries, (current) =>
+ new Map(current).set(id, { ...current.get(id)!, enabled: next }),
+ ),
+ };
+
+ const registry = AtomRegistry.make();
+ const root = createRoot(document.createElement("div"));
+ using _mounted = {
+ [Symbol.dispose]() {
+ act(() => root.unmount());
+ registry.dispose();
+ },
+ };
+ let retryEnvironment!: ReturnType;
+ function Probe() {
+ const value = useRetryEnvironment();
+ useLayoutEffect(() => {
+ retryEnvironment = value;
+ });
+ return null;
+ }
+ yield* Effect.promise(async () => {
+ await act(async () =>
+ root.render(
+
+
+ ,
+ ),
+ );
+ await act(async () => {
+ await retryEnvironment(environmentId);
+ });
+ });
+
+ const entry = (yield* SubscriptionRef.get(entries)).get(environmentId);
+ expect({ enabled: entry?.enabled, retries: retryCount }).toEqual({ enabled: true, retries });
+ }),
+ );
+});
diff --git a/apps/mobile/src/features/connection/useRetryEnvironment.ts b/apps/mobile/src/features/connection/useRetryEnvironment.ts
new file mode 100644
index 0000000000000..b5d8edc749230
--- /dev/null
+++ b/apps/mobile/src/features/connection/useRetryEnvironment.ts
@@ -0,0 +1,17 @@
+import { useAtomValue } from "@effect/atom-react";
+import type { EnvironmentId } from "@t3tools/contracts";
+
+import { environmentCatalog } from "../../connection/catalog";
+import { useAtomCommand } from "../../state/use-atom-command";
+
+export function useRetryEnvironment() {
+ const catalog = useAtomValue(environmentCatalog.catalogValueAtom);
+ const retryNow = useAtomCommand(environmentCatalog.retryNow, "environment retry");
+ const setEnabled = useAtomCommand(environmentCatalog.setEnabled, "environment toggle");
+
+ return (environmentId: EnvironmentId) =>
+ // A retry does nothing while the environment is switched off.
+ catalog.entries.get(environmentId)?.enabled === false
+ ? setEnabled({ environmentId, enabled: true })
+ : retryNow(environmentId);
+}
diff --git a/apps/mobile/src/features/files/WorkspaceFilePreviewError.tsx b/apps/mobile/src/features/files/WorkspaceFilePreviewError.tsx
index 63c3e7be0c65e..eccac90d9abea 100644
--- a/apps/mobile/src/features/files/WorkspaceFilePreviewError.tsx
+++ b/apps/mobile/src/features/files/WorkspaceFilePreviewError.tsx
@@ -2,11 +2,10 @@ import type { EnvironmentId } from "@t3tools/contracts";
import { View } from "react-native";
import { EmptyState } from "../../components/ui/EmptyState";
-import { environmentCatalog } from "../../connection/catalog";
import type { AssetUrlFailureReason } from "../../state/asset-url-state";
-import { useAtomCommand } from "../../state/use-atom-command";
import { useEnvironmentPresentation } from "../../state/presentation";
import { EnvironmentConnectionNotice } from "../connection/EnvironmentConnectionNotice";
+import { useRetryEnvironment } from "../connection/useRetryEnvironment";
export function WorkspaceFilePreviewError(props: {
readonly environmentId: EnvironmentId | null;
@@ -15,7 +14,7 @@ export function WorkspaceFilePreviewError(props: {
}) {
const { environmentId, onRetry } = props;
const environment = useEnvironmentPresentation(environmentId);
- const retryEnvironment = useAtomCommand(environmentCatalog.retryNow, "environment retry");
+ const retryEnvironment = useRetryEnvironment();
const retryConnection = () => {
if (environmentId !== null) void retryEnvironment(environmentId);
onRetry();
diff --git a/apps/mobile/src/features/files/ZipArchiveView.tsx b/apps/mobile/src/features/files/ZipArchiveView.tsx
index 9f5dbbec0725f..6187a051e1c4d 100644
--- a/apps/mobile/src/features/files/ZipArchiveView.tsx
+++ b/apps/mobile/src/features/files/ZipArchiveView.tsx
@@ -667,8 +667,6 @@ function ZipEntryView(props: {
() => {
if (controller.signal.aborted) return;
setBusy(null);
- if (kind === "attach")
- Dialog.alert("Added to chat", `${entry.name} is attached to your message.`);
},
(cause: unknown) => {
if (controller.signal.aborted) return;
diff --git a/apps/mobile/src/features/files/filePath.test.ts b/apps/mobile/src/features/files/filePath.test.ts
index c58316af3698b..75f46e23f10cd 100644
--- a/apps/mobile/src/features/files/filePath.test.ts
+++ b/apps/mobile/src/features/files/filePath.test.ts
@@ -62,11 +62,18 @@ describe("needsWorkspaceFileContents", () => {
});
describe("workspace preview classifiers", () => {
- it("treat # and ? as literal filename characters", () => {
+ it("recognize preview extensions and treat # and ? as literal filename characters", () => {
for (const path of ["notes/clip#1.wav", "notes/clip?1.wav", "notes#old/clip.wav"]) {
expect(isAudioPreviewFile(path)).toBe(true);
}
- for (const path of ["docs/draft#1.md", "docs/draft?1.md", "docs#old/draft.md"]) {
+ for (const path of [
+ "docs/draft#1.md",
+ "docs/draft?1.md",
+ "docs#old/draft.md",
+ "CHANGELOG.markdown",
+ "notes.MDOWN",
+ "todo.mkd",
+ ]) {
expect(isMarkdownPreviewFile(path)).toBe(true);
}
});
diff --git a/apps/mobile/src/features/files/filePath.ts b/apps/mobile/src/features/files/filePath.ts
index 330ff5784da6d..8e659280fdd27 100644
--- a/apps/mobile/src/features/files/filePath.ts
+++ b/apps/mobile/src/features/files/filePath.ts
@@ -108,7 +108,7 @@ export function isSvgImagePreviewFile(path: string): boolean {
}
export function isMarkdownPreviewFile(path: string): boolean {
- return /\.(?:md|mdx)$/i.test(path);
+ return /\.(?:md|mdx|markdown|mdown|mkd)$/i.test(path);
}
export function needsWorkspaceFileContents(input: {
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/home/useThreadListActions.test.ts b/apps/mobile/src/features/home/useThreadListActions.test.ts
index 0bea39e419e21..135cf4e1d85a7 100644
--- a/apps/mobile/src/features/home/useThreadListActions.test.ts
+++ b/apps/mobile/src/features/home/useThreadListActions.test.ts
@@ -21,6 +21,7 @@ const state = vi.hoisted(() => ({
failedAction: null as string | null,
titleOutcome: null as ThreadTitleRegenerationOutcome | null,
archivedRefreshes: [] as string[],
+ onArchivedRefresh: undefined as (() => void) | undefined,
scopes: new Map>(),
shells: [] as EnvironmentThreadShell[],
requests: [] as {
@@ -59,6 +60,7 @@ vi.mock("../../components/ui/Dialog", () => ({
vi.mock("../archive/useArchivedThreadSnapshots", () => ({
refreshArchivedThreadsForEnvironment: (environmentId: string) => {
state.archivedRefreshes.push(environmentId);
+ state.onArchivedRefresh?.();
},
}));
vi.mock("../../state/session", () => ({
@@ -71,8 +73,9 @@ vi.mock("../../state/presentation", () => ({
vi.mock("../../state/server", () => ({
environmentServerConfigsAtom: "server-configs",
}));
-vi.mock("../../state/atom-registry", () => ({
- appAtomRegistry: {
+vi.mock("../../state/atom-registry", async () => {
+ const registry = (await import("effect/reactivity")).AtomRegistry.make();
+ const stub = {
set: (_atom: string, value: boolean) => {
state.dropBusy = value;
},
@@ -103,8 +106,21 @@ vi.mock("../../state/atom-registry", () => ({
},
]),
),
- },
-}));
+ };
+ // Real atoms such as composerDraftsAtom go to a real registry; strings are stubbed state.
+ return {
+ appAtomRegistry: {
+ get: (atom: unknown) =>
+ typeof atom === "string"
+ ? stub.get(atom)
+ : registry.get(atom as Parameters[0]),
+ set: (atom: unknown, value: unknown) =>
+ typeof atom === "string"
+ ? stub.set(atom, value as boolean)
+ : registry.set(atom as Parameters[0], value),
+ },
+ };
+});
vi.mock("../../state/use-atom-command", () => ({
useAtomCommand: (command: unknown) => command,
}));
@@ -164,6 +180,8 @@ vi.mock("../../state/threads", () => ({
),
}));
+import { appAtomRegistry } from "../../state/atom-registry";
+import { composerDraftsAtom } from "../../state/use-composer-drafts";
import { dismissThreadUndoNotice, readThreadUndoNotice } from "./thread-undo-notice";
import { useThreadListActions } from "./useThreadListActions";
@@ -197,6 +215,7 @@ beforeEach(() => {
state.failedAction = null;
state.titleOutcome = null;
state.archivedRefreshes = [];
+ state.onArchivedRefresh = undefined;
state.pendingOrder = null;
state.dropBusy = false;
state.holdingRows = false;
@@ -250,7 +269,9 @@ describe("thread list operation permissions", () => {
expect(state.requests).toEqual([]);
});
- it("rechecks permission after a retained delete confirmation", async () => {
+ it("rechecks permission after a retained delete confirmation, then clears the draft", async () => {
+ const draft = { text: "unsent", attachments: [] };
+ appAtomRegistry.set(composerDraftsAtom, { "primary:thread": draft, "primary:other": draft });
useThreadListActions().confirmDeleteThread(makeThread());
const confirm = state.dialogs[0]?.onConfirm;
expect(confirm).toBeTypeOf("function");
@@ -259,6 +280,15 @@ describe("thread list operation permissions", () => {
await confirm!();
expect(state.requests).toEqual([]);
+ expect(Object.keys(appAtomRegistry.get(composerDraftsAtom))).toContain("primary:thread");
+
+ state.scopes.get(primaryEnvironmentId)!.add(AuthOrchestrationOperateScope);
+ const deleted = new Promise((resolve) => (state.onArchivedRefresh = resolve));
+ confirm!();
+ await deleted;
+
+ expect(state.requests).toEqual([expect.objectContaining({ action: "delete" })]);
+ expect(Object.keys(appAtomRegistry.get(composerDraftsAtom))).toEqual(["primary:other"]);
});
});
@@ -594,6 +624,19 @@ describe("thread action undo", () => {
await undo();
expect(state.requests.map(({ action }) => action)).toEqual(["unpin"]);
});
+
+ it("keeps the earlier Undo until archiving succeeds", async () => {
+ const actions = useThreadListActions();
+ const thread = makeThread();
+ await actions.settleThread(thread);
+ state.failedAction = "archive";
+ expect(await actions.archiveThread(thread)).toBe(false);
+ expect(readThreadUndoNotice()?.action).toBe("Settled");
+
+ state.failedAction = null;
+ expect(await actions.archiveThread(thread)).toBe(true);
+ expect(readThreadUndoNotice()).toBeNull();
+ });
});
describe("thread archive guard", () => {
diff --git a/apps/mobile/src/features/home/useThreadListActions.ts b/apps/mobile/src/features/home/useThreadListActions.ts
index 3cd180db6273f..b100b6aa5e6da 100644
--- a/apps/mobile/src/features/home/useThreadListActions.ts
+++ b/apps/mobile/src/features/home/useThreadListActions.ts
@@ -17,6 +17,7 @@ import { appAtomRegistry } from "../../state/atom-registry";
import { environmentServerConfigsAtom } from "../../state/server";
import { connectedEnvironmentIdsAtom } from "../../state/presentation";
import { readEnvironmentScope } from "../../state/session";
+import { clearComposerDraft } from "../../state/use-composer-drafts";
import {
environmentThreadShells,
steadyNavigationThreadShellsAtom,
@@ -115,6 +116,7 @@ function useThreadActionExecutor(
action: ThreadListAction,
thread: EnvironmentThreadShell,
onStarted?: () => void,
+ restoreUnsettledAt?: string | null,
) => {
if (!checkThreadOperationPermission(thread, actionFailureTitle(action))) return false;
const key = scopedThreadKey(thread.environmentId, thread.id);
@@ -145,9 +147,6 @@ function useThreadActionExecutor(
return false;
}
if (action === "unsettle") ThreadUndo.invalidate("settle", key);
- if (action === "archive" || action === "delete") {
- for (const kind of ["settle", "snooze", "pin"]) ThreadUndo.invalidate(kind, key);
- }
onStarted?.();
const result = await withThreadDismissal(
key,
@@ -157,7 +156,11 @@ function useThreadActionExecutor(
// suppressed until real activity clears the pin server-side.
await unsettleMutation({
environmentId: thread.environmentId,
- input: { threadId: thread.id, reason: "user" },
+ input: {
+ threadId: thread.id,
+ reason: "user",
+ ...(restoreUnsettledAt === undefined ? {} : { restoreUnsettledAt }),
+ },
})
: await (
action === "settle"
@@ -177,9 +180,13 @@ function useThreadActionExecutor(
Dialog.alert(actionFailureTitle(action), actionFailureMessage(action, result.cause));
return false;
}
+ if (action === "archive" || action === "delete") {
+ for (const kind of ["settle", "snooze", "pin"]) ThreadUndo.invalidate(kind, key);
+ }
if (action === "archive" || action === "unarchive" || action === "delete") {
refreshArchivedThreadsForEnvironment(thread.environmentId);
}
+ if (action === "delete") clearComposerDraft(key);
onCompleted?.(action, thread);
return true;
})();
@@ -263,11 +270,19 @@ export function useThreadListActions(): {
async (step) => {
switch (step.action) {
case "unsettle":
- return unsettleThread(thread);
+ return unsettleThread(thread, step.restoreUnsettledAt);
case "unsnooze":
return unsnoozeThread(thread);
case "pin":
return pinThread(thread, step.orderKey);
+ case "reorderActive": {
+ const result = await reorderActiveMutation({
+ environmentId: thread.environmentId,
+ input: { threadId: thread.id, orderKey: step.orderKey },
+ });
+ if (result._tag === "Failure") throw Cause.squash(result.cause);
+ return true;
+ }
case "snooze": {
const failureTitle =
action === "Unpinned" ? "Could not undo unpin" : "Could not undo settle";
@@ -411,8 +426,10 @@ export function useThreadListActions(): {
snoozeInFlightThreadKeys.current.delete(key);
return succeeded;
};
- const unsettleThread = async (thread: EnvironmentThreadShell) =>
- (await executeAction("unsettle", thread)) === true;
+ const unsettleThread = async (
+ thread: EnvironmentThreadShell,
+ restoreUnsettledAt?: string | null,
+ ) => (await executeAction("unsettle", thread, undefined, restoreUnsettledAt)) === true;
const pinThread = async (thread: EnvironmentThreadShell, restoreOrderKey?: string) => {
if (!checkThreadOperationPermission(thread, "Could not pin thread")) return false;
if (!environmentConfigLoaded(thread.environmentId)) {
diff --git a/apps/mobile/src/features/layout/createWorkspaceStackNavigator.ios.tsx b/apps/mobile/src/features/layout/createWorkspaceStackNavigator.ios.tsx
index bac954d99f118..fb144bdd16c7e 100644
--- a/apps/mobile/src/features/layout/createWorkspaceStackNavigator.ios.tsx
+++ b/apps/mobile/src/features/layout/createWorkspaceStackNavigator.ios.tsx
@@ -107,7 +107,10 @@ function ColumnScreen(props: {
readonly selectedThreadKey?: string | null;
readonly selectedPullRequestKey?: string | null;
readonly onDismiss: (routeKey: string, native: boolean) => void;
- readonly onAppearance: (type: "willAppear" | "didAppear" | "willDisappear", key: string) => void;
+ readonly onAppearance: (
+ type: "willAppear" | "didAppear" | "willDisappear" | "didDisappear",
+ key: string,
+ ) => void;
readonly onCompose?: () => void;
readonly navigation: ViewProps["navigation"];
readonly footer?: ReactNode;
@@ -152,9 +155,10 @@ function ColumnScreen(props: {
props.onAppearance("willDisappear", key);
props.navigation.emit({ type: "transitionStart", target: key, data: { closing: true } });
}}
- onDidDisappear={() =>
- props.navigation.emit({ type: "transitionEnd", target: key, data: { closing: true } })
- }
+ onDidDisappear={() => {
+ props.onAppearance("didDisappear", key);
+ props.navigation.emit({ type: "transitionEnd", target: key, data: { closing: true } });
+ }}
>
@@ -307,7 +311,7 @@ function WorkspaceColumns(
}
};
const followCollapsedSplit = (
- type: "willAppear" | "didAppear" | "willDisappear",
+ type: "willAppear" | "didAppear" | "willDisappear" | "didDisappear",
key: string,
) => {
if (!collapsed.current || layout.usesSplitView) return;
@@ -331,6 +335,7 @@ function WorkspaceColumns(
const primary = props.descriptors[props.primary.key];
if (!primary) return null;
+ const primaryColumnWidth = (layout.listPaneWidth ?? 320) + (layout.listPaneGap ?? 0) / 2;
return (
0 &&
!primaryVisible &&
!layout.usesSplitView &&
diff --git a/apps/mobile/src/features/pull-requests/PullRequestDiscussionScreen.tsx b/apps/mobile/src/features/pull-requests/PullRequestDiscussionScreen.tsx
index e92debeea0f1d..9d59324c1e4a6 100644
--- a/apps/mobile/src/features/pull-requests/PullRequestDiscussionScreen.tsx
+++ b/apps/mobile/src/features/pull-requests/PullRequestDiscussionScreen.tsx
@@ -21,7 +21,7 @@ import { AppText as Text, AppTextInput as TextInput } from "../../components/ui/
import { AppBar } from "../../components/ui/AppBar";
import { Button } from "../../components/ui/Button";
import { GlassSurface } from "../../components/ui/GlassSurface";
-import { relativeTime } from "../../lib/time";
+import { compareTimestamps, relativeTime } from "../../lib/time";
import { composerPullRequests } from "../../state/pull-requests";
import { useAtomCommand } from "../../state/use-atom-command";
import { useEnvironmentQuery } from "../../state/query";
@@ -147,7 +147,7 @@ function Discussion({ params }: { params: PullRequestParams & { readonly discuss
...new Map(
[...extra, ...(thread?.comments ?? [])].map((comment) => [comment.id, comment]),
).values(),
- ].sort((left, right) => left.createdAt.localeCompare(right.createdAt));
+ ].sort((left, right) => compareTimestamps(left.createdAt, right.createdAt));
const scrollRef = useRef(null);
const pendingTop = useRef(null);
const positionedComment = useRef(null);
diff --git a/apps/mobile/src/features/pull-requests/PullRequestListFilters.tsx b/apps/mobile/src/features/pull-requests/PullRequestListFilters.tsx
index fbcb62406b7a7..5bec031fb735f 100644
--- a/apps/mobile/src/features/pull-requests/PullRequestListFilters.tsx
+++ b/apps/mobile/src/features/pull-requests/PullRequestListFilters.tsx
@@ -41,12 +41,18 @@ function choices(field: string, options: Readonly>, selec
}));
}
-type ProjectOrder = readonly { readonly memberProjectRefs: readonly ScopedProjectRef[] }[];
+type ProjectOrder = readonly {
+ readonly memberProjectRefs: readonly ScopedProjectRef[];
+ readonly pinned: boolean;
+ readonly archived: boolean;
+}[];
const sameProjectOrder = (previous: ProjectOrder, next: ProjectOrder) =>
previous.length === next.length &&
previous.every((group, index) => {
const members = next[index]!.memberProjectRefs;
return (
+ group.pinned === next[index]!.pinned &&
+ group.archived === next[index]!.archived &&
group.memberProjectRefs.length === members.length &&
group.memberProjectRefs.every(
(ref, member) =>
@@ -69,7 +75,11 @@ const sidebarProjectOrderFamily = Atom.family((mode: SidebarProjectGroupingMode)
threads: get(environmentThreadShells.threadShellsAtom),
pendingTasks: [],
projectSortOrder: "updated_at",
- }).map((scope) => ({ memberProjectRefs: scope.projectRefs })),
+ }).map((scope) => ({
+ memberProjectRefs: scope.projectRefs,
+ pinned: scope.pinned,
+ archived: scope.archived,
+ })),
).pipe(Atom.withEquality(sameProjectOrder)),
);
diff --git a/apps/mobile/src/features/pull-requests/PullRequestMergeControls.tsx b/apps/mobile/src/features/pull-requests/PullRequestMergeControls.tsx
index 2d0414b503653..3889dd87ed2f4 100644
--- a/apps/mobile/src/features/pull-requests/PullRequestMergeControls.tsx
+++ b/apps/mobile/src/features/pull-requests/PullRequestMergeControls.tsx
@@ -3,12 +3,14 @@ import { useAtomRefresh, useAtomSet, useAtomValue } from "@effect/atom-react";
import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
import type { PullRequestDetail, PullRequestMergeMethod } from "@t3tools/contracts";
+import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
import { AsyncResult } from "effect/reactivity";
import { useRef, useState } from "react";
import { View } from "react-native";
import { AppText as Text } from "../../components/ui/AppText";
import { Button } from "../../components/ui/Button";
import { SplitButton } from "../../components/ui/SplitButton";
+import { useEnvironmentServerConfig } from "../../state/entities";
import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences";
import { composerPullRequests } from "../../state/pull-requests";
import { useAtomCommand } from "../../state/use-atom-command";
@@ -19,6 +21,7 @@ import {
MERGE_METHODS,
PR_ACTION_ICONS,
pullRequestActionLabel,
+ resolveMergeMethod,
} from "./pullRequestActions";
import { pullRequestStackMerge, singlePullRequestMergeAllowed } from "./pullRequestStack";
import { pullRequestTarget, type PullRequestParams } from "./usePullRequestDiff";
@@ -39,6 +42,7 @@ export function PullRequestMergeControls(props: {
const permissions = usePullRequestPermissions(props.params, pr);
const stateAction = usePullRequestAction(props.params, pr);
const preferences = useAtomValue(mobilePreferencesAtom);
+ const serverSettings = useEnvironmentServerConfig(target.environmentId)?.settings;
const savePreferences = useAtomSet(updateMobilePreferencesAtom);
const runAction = useAtomCommand(composerPullRequests.runAction, { reportFailure: false });
const refreshDetail = useAtomRefresh(composerPullRequests.detail(target));
@@ -47,15 +51,15 @@ export function PullRequestMergeControls(props: {
const [busy, setBusy] = useState(false);
const pending = useRef(false);
const methods = allowedMergeMethods(pr);
- const preferred =
- selectedMethod ??
- (AsyncResult.isSuccess(preferences) ? preferences.value.pullRequestMergeMethod : undefined) ??
- "squash";
- const method = methods.includes(preferred)
- ? preferred
- : methods.includes("squash")
- ? "squash"
- : methods[0];
+ const method = resolveMergeMethod(
+ pr,
+ selectedMethod,
+ serverSettings
+ ? resolveProjectSettings(serverSettings, target.input.projectId).settings
+ .pullRequestMergeMethod
+ : null,
+ AsyncResult.isSuccess(preferences) ? preferences.value.pullRequestMergeMethod : undefined,
+ );
const scope = stack.stack ? pullRequestStackMerge(stack.stack, pr.number, terminology) : null;
const canMergeSingle = singlePullRequestMergeAllowed({
supportsStackActions: stack.supportsStackActions,
diff --git a/apps/mobile/src/features/pull-requests/PullRequestReactions.tsx b/apps/mobile/src/features/pull-requests/PullRequestReactions.tsx
index 394fc630a0046..722a435d2f118 100644
--- a/apps/mobile/src/features/pull-requests/PullRequestReactions.tsx
+++ b/apps/mobile/src/features/pull-requests/PullRequestReactions.tsx
@@ -145,7 +145,7 @@ export function PullRequestCommentFooter(props: {
>;
readonly permissions: Pick<
ReturnType,
- "canEditComment" | "canReact"
+ "canEditComment" | "canReactComment"
>;
readonly onChanged: () => void;
readonly onEdit?: () => void;
@@ -155,7 +155,7 @@ export function PullRequestCommentFooter(props: {
const reactions = comment.reactions ?? [];
const editableKind = comment.kind === "review" ? null : comment.kind;
const canEdit = editableKind !== null && props.permissions.canEditComment(comment);
- const { canReact } = props.permissions;
+ const canReact = props.permissions.canReactComment(comment);
if (reactions.length === 0 && !canReact && !canEdit) return null;
return (
diff --git a/apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx b/apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx
index f3c47e2582858..1bcab04eb3eea 100644
--- a/apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx
+++ b/apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx
@@ -3,6 +3,7 @@ import {
pullRequestAnchorMatchesUrl,
pullRequestDiffPathMatches,
pullRequestLinkCommit,
+ resolvePullRequestAnchorRange,
resolvePullRequestReviewAnchor,
} from "@t3tools/shared/pullRequestAnchor";
import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";
@@ -142,15 +143,13 @@ function usePullRequestActivityRows(params: PullRequestParams, filter: ActivityF
const filtered = result.data ? filterPullRequestActivity(result.data, filter) : null;
const rows = (() => {
if (!filtered) return [];
- const rows = pullRequestTimelineRows(filtered.activity, params, navigation, {
- permissions,
- onChanged: result.refresh,
- });
- if (filter.newestFirst) {
- const notice = rows.at(-1)?.key === "truncated" ? rows.pop() : undefined;
- rows.reverse();
- if (notice) rows.push(notice);
- }
+ const rows = pullRequestTimelineRows(
+ filtered.activity,
+ params,
+ navigation,
+ { permissions, onChanged: result.refresh },
+ filter.newestFirst,
+ );
if (!rows.length)
rows.push({
key: "empty",
@@ -1074,7 +1073,15 @@ function PullRequestFileRouteContent({ route }: PullRequestFileRouteProps) {
: !jumpPath || requestedFile
? data.files[0]
: undefined);
- const range = pickedPath === null && linkAnchor?.kind === "diff" ? linkAnchor.range : null;
+ const linkRange = pickedPath === null && linkAnchor?.kind === "diff" ? linkAnchor.range : null;
+ const range =
+ linkRange &&
+ resolvePullRequestAnchorRange(linkRange, (line) =>
+ data.rows.some(
+ (row) =>
+ row.fileId === targetFile?.id && row.change === "delete" && row.oldLineNumber === line,
+ ),
+ );
const focus =
route.params.focus ??
(range
diff --git a/apps/mobile/src/features/pull-requests/PullRequestStatusRows.tsx b/apps/mobile/src/features/pull-requests/PullRequestStatusRows.tsx
index 03ba26f2247cf..805d61c928378 100644
--- a/apps/mobile/src/features/pull-requests/PullRequestStatusRows.tsx
+++ b/apps/mobile/src/features/pull-requests/PullRequestStatusRows.tsx
@@ -27,6 +27,7 @@ import {
} from "./pullRequestActions";
import {
checkStatus,
+ isFailingCheck,
pullRequestBranchSummary,
pullRequestChecksSummary,
pullRequestReviewSummary,
@@ -132,8 +133,7 @@ export function PullRequestChecksRow(props: RowProps) {
exiting={PR_ROW_EXIT}
className="pl-8"
>
- {props.pr.state === "open" &&
- props.pr.checks.some((check) => check.status === "failure") ? (
+ {props.pr.state === "open" && props.pr.checks.some(isFailingCheck) ? (
) : null}
{action.available("approve-workflows") ? (
diff --git a/apps/mobile/src/features/pull-requests/PullRequestTimeline.tsx b/apps/mobile/src/features/pull-requests/PullRequestTimeline.tsx
index 4b7ba3a968187..586d9947510f3 100644
--- a/apps/mobile/src/features/pull-requests/PullRequestTimeline.tsx
+++ b/apps/mobile/src/features/pull-requests/PullRequestTimeline.tsx
@@ -17,7 +17,7 @@ import { Pressable, StyleSheet, View } from "react-native";
import { parseMarkdownDocument } from "../../lib/markdownDocument";
import { AppText as Text } from "../../components/ui/AppText";
import { SymbolView, type AppSymbolName } from "../../components/ui/AppSymbol";
-import { relativeTime } from "../../lib/time";
+import { byTimestamp, relativeTime } from "../../lib/time";
import { PullRequestAvatar } from "./PullRequestPresentation";
import { PullRequestMarkdown } from "./PullRequestMarkdown";
import { PullRequestCommentFooter } from "./PullRequestReactions";
@@ -218,6 +218,7 @@ export function pullRequestTimelineRows(
params: PullRequestParams,
navigation: Pick, "navigate" | "dispatch">,
actions: CommentActions,
+ newestFirst: boolean,
) {
const linkTarget = parsePullRequestAnchor(params.navigationUrl);
const threads = pullRequestConversationThreads(activity);
@@ -320,7 +321,7 @@ export function pullRequestTimelineRows(
),
})),
- ].sort((a, b) => a.date.localeCompare(b.date));
+ ].sort(byTimestamp(newestFirst));
if (activity.commentsTruncated || activity.reviewThreadsTruncated)
events.push({
key: "truncated",
diff --git a/apps/mobile/src/features/pull-requests/pullRequestActions.test.ts b/apps/mobile/src/features/pull-requests/pullRequestActions.test.ts
index 2234a31081802..6862b5b31b2fb 100644
--- a/apps/mobile/src/features/pull-requests/pullRequestActions.test.ts
+++ b/apps/mobile/src/features/pull-requests/pullRequestActions.test.ts
@@ -5,6 +5,7 @@ import {
canPerformPullRequestAction,
mergeUnavailableReason,
pullRequestActionLabel,
+ resolveMergeMethod,
} from "./pullRequestActions";
const GITHUB = sourceControlClients.get("github").changeRequest;
@@ -65,6 +66,22 @@ describe("mobile pull request actions", () => {
expect(mergeUnavailableReason(pr, true, GITHUB)).toContain("conflicts");
});
+ it("picks the chosen, project default, then last used merge method the repository allows", () => {
+ const pr = detail();
+ expect(resolveMergeMethod(pr, null, "merge", "squash")).toBe("merge");
+ expect(resolveMergeMethod(pr, "squash", "merge", "merge")).toBe("squash");
+ expect(resolveMergeMethod(pr, null, "rebase", "merge")).toBe("merge");
+ expect(resolveMergeMethod(pr, null, null, undefined)).toBe("squash");
+ expect(
+ resolveMergeMethod(
+ detail({ mergeCapabilities: { merge: true, squash: false, rebase: false } }),
+ null,
+ null,
+ "rebase",
+ ),
+ ).toBe("merge");
+ });
+
it("names the change request with its host's term", () => {
expect(pullRequestActionLabel("close", GITHUB)).toBe("Close pull request");
expect(pullRequestActionLabel("close", GITLAB)).toBe("Close merge request");
diff --git a/apps/mobile/src/features/pull-requests/pullRequestActions.ts b/apps/mobile/src/features/pull-requests/pullRequestActions.ts
index 132501b60a240..967689b57d84e 100644
--- a/apps/mobile/src/features/pull-requests/pullRequestActions.ts
+++ b/apps/mobile/src/features/pull-requests/pullRequestActions.ts
@@ -87,6 +87,20 @@ export function allowedMergeMethods(pr: ActionDetail) {
return pr.capabilities.mergeMethods.filter((method) => pr.mergeCapabilities[method]);
}
+export function resolveMergeMethod(
+ pr: ActionDetail,
+ selected: PullRequestMergeMethod | null,
+ projectDefault: PullRequestMergeMethod | null,
+ lastUsed: PullRequestMergeMethod | undefined,
+) {
+ const methods = allowedMergeMethods(pr);
+ return (
+ [selected, projectDefault, lastUsed, "squash" as const].find(
+ (method) => method != null && methods.includes(method),
+ ) ?? methods[0]
+ );
+}
+
export function allowedUpdateMethods(pr: ActionDetail) {
return (pr.capabilities.updateMethods ?? []).filter((method) =>
pr.viewerPermissions.updateMethods?.includes(method),
diff --git a/apps/mobile/src/features/pull-requests/pullRequestFilesViewed.test.ts b/apps/mobile/src/features/pull-requests/pullRequestFilesViewed.test.ts
index ee438e6187215..aca2a28ae8a21 100644
--- a/apps/mobile/src/features/pull-requests/pullRequestFilesViewed.test.ts
+++ b/apps/mobile/src/features/pull-requests/pullRequestFilesViewed.test.ts
@@ -1,24 +1,16 @@
-import type { PullRequestFilesViewedResult } from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
import { viewedOverlay } from "./pullRequestFilesViewed";
-// The overlay compares reads by identity, so each call is a distinct read.
-const read = (): PullRequestFilesViewedResult => ({ files: [], truncated: false });
-
describe("viewedOverlay", () => {
it("keeps a press while its write is in flight", () => {
- const before = read();
expect(
- viewedOverlay({ "a.ts": { viewed: true, version: 1, awaitingReadAfter: undefined } }, before),
+ viewedOverlay({ "a.ts": { viewed: true, version: 1, awaitingReadAfter: undefined } }, 3),
).toEqual({ "a.ts": true });
});
- it("keeps a landed press until a read newer than the one current at the write", () => {
- const before = read();
- const presses = {
- "a.ts": { viewed: true, version: 1, awaitingReadAfter: { read: before } },
- };
- expect(viewedOverlay(presses, before)).toEqual({ "a.ts": true });
- expect(viewedOverlay(presses, read())).toEqual({});
+ it("yields a landed press to the next completed read, even one with unchanged data", () => {
+ const presses = { "a.ts": { viewed: true, version: 1, awaitingReadAfter: 3 } };
+ expect(viewedOverlay(presses, 3)).toEqual({ "a.ts": true });
+ expect(viewedOverlay(presses, 4)).toEqual({});
});
});
diff --git a/apps/mobile/src/features/pull-requests/pullRequestFilesViewed.ts b/apps/mobile/src/features/pull-requests/pullRequestFilesViewed.ts
index b76d3193c9c8e..6cbfe3795b5e4 100644
--- a/apps/mobile/src/features/pull-requests/pullRequestFilesViewed.ts
+++ b/apps/mobile/src/features/pull-requests/pullRequestFilesViewed.ts
@@ -1,12 +1,8 @@
-import type { PullRequestFilesViewedResult } from "@t3tools/contracts";
-
-export type FilesViewedRead = PullRequestFilesViewedResult | null;
-
export interface ViewedPress {
readonly viewed: boolean;
readonly version: number;
- /** Set once the write lands: the press yields to the server once a read newer than this lands. */
- readonly awaitingReadAfter: { readonly read: FilesViewedRead } | undefined;
+ /** Completed reads when the write landed: the press yields once a later read completes. */
+ readonly awaitingReadAfter: number | undefined;
}
export interface ViewedState {
@@ -18,11 +14,11 @@ export interface ViewedState {
/** The pressed states the server's read has not caught up with yet. */
export function viewedOverlay(
presses: Readonly>,
- read: FilesViewedRead,
+ reads: number,
): Record {
const overlay: Record = {};
for (const [path, press] of Object.entries(presses))
- if (press.awaitingReadAfter === undefined || press.awaitingReadAfter.read === read)
+ if (press.awaitingReadAfter === undefined || press.awaitingReadAfter === reads)
overlay[path] = press.viewed;
return overlay;
}
diff --git a/apps/mobile/src/features/pull-requests/pullRequestList.ts b/apps/mobile/src/features/pull-requests/pullRequestList.ts
index 674d3b0e24fe3..5a4572dbde803 100644
--- a/apps/mobile/src/features/pull-requests/pullRequestList.ts
+++ b/apps/mobile/src/features/pull-requests/pullRequestList.ts
@@ -11,6 +11,7 @@ import {
type PullRequestListStatsInput,
} from "@t3tools/contracts";
import type { PullRequestListControls } from "../../persistence/mobile-preferences";
+import { compareTimestamps } from "../../lib/time";
export const PR_LIST_PAGE_SIZE = 30;
export type { PullRequestListControls } from "../../persistence/mobile-preferences";
@@ -242,7 +243,7 @@ export function mergePullRequestListEntries(
const held = entries.get(key);
if (!held || (entry.observedAt ?? 0) >= (held.observedAt ?? 0)) entries.set(key, entry);
}
- return [...entries.values()].sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
+ return [...entries.values()].sort((a, b) => compareTimestamps(b.updatedAt, a.updatedAt));
}
export interface PullRequestListPages {
@@ -455,10 +456,10 @@ export function filterPullRequestList<
}
return [...unique.values()].sort((a, b) =>
controls.sort === "created"
- ? b.createdAt.localeCompare(a.createdAt)
+ ? compareTimestamps(b.createdAt, a.createdAt)
: controls.sort === "oldest"
- ? a.updatedAt.localeCompare(b.updatedAt)
- : b.updatedAt.localeCompare(a.updatedAt),
+ ? compareTimestamps(a.updatedAt, b.updatedAt)
+ : compareTimestamps(b.updatedAt, a.updatedAt),
);
}
diff --git a/apps/mobile/src/features/pull-requests/pullRequestStatus.test.ts b/apps/mobile/src/features/pull-requests/pullRequestStatus.test.ts
index aef40179ded64..e5cb4551db56b 100644
--- a/apps/mobile/src/features/pull-requests/pullRequestStatus.test.ts
+++ b/apps/mobile/src/features/pull-requests/pullRequestStatus.test.ts
@@ -97,5 +97,8 @@ describe("mobile overview check status", () => {
expect(
pullRequestChecksSummary({ checks: [check("success"), check("pending"), check("failure")] }),
).toMatchObject({ title: "1 check failing", count: "1 of 3" });
+ expect(
+ pullRequestChecksSummary({ checks: [check("success"), check("cancelled")] }),
+ ).toMatchObject({ title: "1 check failing", tint: "accent-danger-foreground" });
});
});
diff --git a/apps/mobile/src/features/pull-requests/pullRequestStatus.ts b/apps/mobile/src/features/pull-requests/pullRequestStatus.ts
index 5426266dc6893..d664aef1fc015 100644
--- a/apps/mobile/src/features/pull-requests/pullRequestStatus.ts
+++ b/apps/mobile/src/features/pull-requests/pullRequestStatus.ts
@@ -88,8 +88,12 @@ export function checkStatus(check: PullRequestCheck) {
}
}
+export function isFailingCheck(check: PullRequestCheck) {
+ return check.status === "failure" || check.status === "cancelled";
+}
+
export function pullRequestChecksSummary(pr: Pick) {
- const failed = pr.checks.filter((check) => check.status === "failure").length;
+ const failed = pr.checks.filter(isFailingCheck).length;
const required = pr.checks.filter((check) => check.status === "action-required").length;
const pending = pr.checks.filter((check) => check.status === "pending").length;
const passed = pr.checks.filter((check) => check.status === "success").length;
diff --git a/apps/mobile/src/features/pull-requests/usePullRequestFilesViewed.ts b/apps/mobile/src/features/pull-requests/usePullRequestFilesViewed.ts
index 7467c73fbe403..c973c81dac39e 100644
--- a/apps/mobile/src/features/pull-requests/usePullRequestFilesViewed.ts
+++ b/apps/mobile/src/features/pull-requests/usePullRequestFilesViewed.ts
@@ -2,9 +2,12 @@ import { usePullRequestConnected } from "./usePullRequestConnected";
import { RegistryContext, useAtomRefresh, useAtomValue } from "@effect/atom-react";
import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
import type { PullRequestDetail } from "@t3tools/contracts";
-import { AsyncResult } from "effect/reactivity";
import { use, useState } from "react";
-import { composerPullRequests } from "../../state/pull-requests";
+import {
+ composerPullRequests,
+ filesViewedReadsFamily,
+ filesViewedReadsKey,
+} from "../../state/pull-requests";
import { useEnvironmentQuery } from "../../state/query";
import { useAtomCommand } from "../../state/use-atom-command";
import { pullRequestTarget, type PullRequestParams } from "./usePullRequestDiff";
@@ -23,11 +26,13 @@ export function usePullRequestFilesViewed(params: PullRequestParams, pr: PullReq
const allowed = connected && permission;
const query = useEnvironmentQuery(supported ? composerPullRequests.filesViewed(target) : null);
const refresh = useAtomRefresh(composerPullRequests.filesViewed(target));
+ const readsAtom = filesViewedReadsFamily(filesViewedReadsKey(target));
+ const reads = useAtomValue(readsAtom);
const write = useAtomCommand(composerPullRequests.setFilesViewed, { reportFailure: false });
const [state, setState] = useState({ key: scopeKey, presses: {}, error: null });
const presses = state.key === scopeKey ? state.presses : {};
const error = state.key === scopeKey ? state.error : null;
- const overlay = viewedOverlay(presses, query.data);
+ const overlay = viewedOverlay(presses, reads);
const update = (change: (current: ViewedState) => ViewedState) =>
setState((current) =>
change(current.key === scopeKey ? current : { key: scopeKey, presses: {}, error: null }),
@@ -48,11 +53,8 @@ export function usePullRequestFilesViewed(params: PullRequestParams, pr: PullReq
...target,
input: { ...target.input, files: [{ path, viewed }] },
});
- // The read that is current once the write lands still predates it; a newer one carries it.
- const readAtWrite = AsyncResult.getOrElse(
- registry.get(composerPullRequests.filesViewed(target)),
- () => null,
- );
+ // A read completed by the time the write lands may predate it; the next one carries it.
+ const readsAtWrite = registry.get(readsAtom);
setState((current) => {
if (current.key !== scopeKey || current.presses[path]?.version !== version) return current;
if (response._tag === "Success")
@@ -60,7 +62,7 @@ export function usePullRequestFilesViewed(params: PullRequestParams, pr: PullReq
...current,
presses: {
...current.presses,
- [path]: { viewed, version, awaitingReadAfter: { read: readAtWrite } },
+ [path]: { viewed, version, awaitingReadAfter: readsAtWrite },
},
};
const rest = { ...current.presses };
diff --git a/apps/mobile/src/features/pull-requests/usePullRequestPermissions.ts b/apps/mobile/src/features/pull-requests/usePullRequestPermissions.ts
index 28a2bbb04cc97..38ba2b74deb24 100644
--- a/apps/mobile/src/features/pull-requests/usePullRequestPermissions.ts
+++ b/apps/mobile/src/features/pull-requests/usePullRequestPermissions.ts
@@ -4,6 +4,7 @@ import {
canEditPullRequestComment,
canEditPullRequestMaintainerEdits,
} from "@t3tools/client-runtime/pull-request-editing";
+import { canReactPullRequestComment } from "@t3tools/client-runtime/pull-request-reactions";
import type { PullRequestComment, PullRequestDetail } from "@t3tools/contracts";
import { usePullRequestConnected } from "./usePullRequestConnected";
import { composerPullRequests } from "../../state/pull-requests";
@@ -54,6 +55,8 @@ export function usePullRequestPermissions(params: PullRequestParams, pr: PullReq
connected && canUpdate && pr !== null && canEditPullRequestMaintainerEdits(pr),
canEditComment: (comment: Pick) =>
connected && canUpdateComment && pr !== null && canEditPullRequestComment(pr, comment),
+ canReactComment: (comment: Pick) =>
+ connected && canSetReaction && pr !== null && canReactPullRequestComment(pr, comment),
canReact: connected && canSetReaction && pr?.capabilities.reactions === true,
canComment:
connected && canComment && pr?.capabilities.comment === true && pr.viewerPermissions.comment,
diff --git a/apps/mobile/src/features/review/ReviewCommentCard.tsx b/apps/mobile/src/features/review/ReviewCommentCard.tsx
index a65bd83e9a66d..3e2cdc9ddfb6c 100644
--- a/apps/mobile/src/features/review/ReviewCommentCard.tsx
+++ b/apps/mobile/src/features/review/ReviewCommentCard.tsx
@@ -12,8 +12,10 @@ import { resolveNativeReviewDiffView } from "../diffs/nativeReviewDiffSurface";
import {
buildNativeReviewDiffData,
buildNativeReviewSnippetRows,
+ buildReviewCommentPatch,
createNativeReviewDiffTheme,
NATIVE_REVIEW_DIFF_CONTENT_WIDTH,
+ reviewCommentDiffText,
} from "./nativeReviewDiffAdapter";
import { buildReviewParsedDiff } from "./reviewModel";
import { REVIEW_MONO_FONT_FAMILY } from "./reviewDiffRendering";
@@ -86,7 +88,7 @@ export const ReviewCommentCard = memo(function ReviewCommentCard(props: {
theme: appearanceScheme,
});
const snippetTokens = useMarkdownCodeHighlight({
- code: props.comment.diff.trim(),
+ code: reviewCommentDiffText(props.comment.diff),
language: props.comment.fenceLanguage ?? language,
enabled: compactNativeRows.length === 0,
theme: appearanceScheme,
@@ -234,32 +236,10 @@ export const ReviewCommentCard = memo(function ReviewCommentCard(props: {
) /* oxlint-enable react/no-array-index-key */,
)
- : props.comment.diff.trim()}
+ : reviewCommentDiffText(props.comment.diff)}
) : null}
);
});
-
-function buildReviewCommentPatch(comment: ReviewInlineComment): string {
- if ((comment.fenceLanguage ?? "diff") !== "diff") {
- return "";
- }
- const diff = comment.diff.trim();
- if (!diff) {
- return "";
- }
-
- if (diff.startsWith("diff --git ")) {
- return diff;
- }
-
- const normalizedPath = comment.filePath.replaceAll("\\", "/");
- return [
- `diff --git a/${normalizedPath} b/${normalizedPath}`,
- `--- a/${normalizedPath}`,
- `+++ b/${normalizedPath}`,
- diff,
- ].join("\n");
-}
diff --git a/apps/mobile/src/features/review/ReviewSheet.tsx b/apps/mobile/src/features/review/ReviewSheet.tsx
index 21bf033b761be..7cf0716277b80 100644
--- a/apps/mobile/src/features/review/ReviewSheet.tsx
+++ b/apps/mobile/src/features/review/ReviewSheet.tsx
@@ -26,11 +26,10 @@ import {
import { PaneListItem } from "../../components/ui/PaneListItem";
import { ScreenContent } from "../../components/ui/ScreenContent";
import { SheetPane } from "../../components/ui/SheetPane";
-import { environmentCatalog } from "../../connection/catalog";
import { useEnvironmentPresentation } from "../../state/presentation";
-import { useAtomCommand } from "../../state/use-atom-command";
import { useThreadDraftForThread } from "../../state/use-thread-composer-state";
import { EnvironmentConnectionNotice } from "../connection/EnvironmentConnectionNotice";
+import { useRetryEnvironment } from "../connection/useRetryEnvironment";
import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
import {
Inspector,
@@ -351,7 +350,7 @@ export function ReviewSheet(props: ReviewSheetProps) {
const { themeAppearance: selectedTheme } = useAppearancePreferences();
const { environmentId, threadId } = props.route.params;
const environment = useEnvironmentPresentation(environmentId);
- const retryEnvironment = useAtomCommand(environmentCatalog.retryNow, "environment retry");
+ const retryEnvironment = useRetryEnvironment();
const isEnvironmentReady = environment.presentation?.connection.phase === "connected";
const { draftMessage, draftContext } = useThreadDraftForThread({ environmentId, threadId });
const reviewCache = useReviewCacheForThread({ environmentId, threadId });
diff --git a/apps/mobile/src/features/review/nativeReviewDiffAdapter.test.ts b/apps/mobile/src/features/review/nativeReviewDiffAdapter.test.ts
index 7e620836baccd..06c577df1bda0 100644
--- a/apps/mobile/src/features/review/nativeReviewDiffAdapter.test.ts
+++ b/apps/mobile/src/features/review/nativeReviewDiffAdapter.test.ts
@@ -8,7 +8,9 @@ import { combinePullRequestDiffPages } from "../pull-requests/pullRequestDiffPag
import { createPullRequestDiffHighlightFiles } from "../pull-requests/pullRequestDiffHighlightFiles";
import {
buildNativeReviewDiffData,
+ buildReviewCommentPatch,
getCachedNativeReviewDiffData,
+ reviewCommentDiffText,
} from "./nativeReviewDiffAdapter";
import type { ReviewInlineComment } from "./reviewCommentSelection";
import { buildReviewParsedDiff, type ReviewParsedDiff } from "./reviewModel";
@@ -46,6 +48,27 @@ function filesPatch(paths: ReadonlyArray) {
.join("\n");
}
+describe("buildReviewCommentPatch", () => {
+ it("keeps a selection's trailing blank line and whitespace", () => {
+ const rows = (diff: string) =>
+ buildNativeReviewDiffData(
+ buildReviewParsedDiff(
+ buildReviewCommentPatch({ ...makeComment("Insert here."), diff }),
+ "review-comment-trailing-blank",
+ ),
+ ).rows.filter((row) => row.kind === "line");
+
+ expect(rows("@@ -3,1 +2,2 @@\n+two\t\n ")).toMatchObject([
+ { content: "two\t", change: "add" },
+ { content: "", change: "context" },
+ ]);
+ expect(rows("@@ -4,1 +4,1 @@\n ")).toMatchObject([{ content: "", change: "context" }]);
+ expect(reviewCommentDiffText("\n@@ -3,1 +2,2 @@\n+two\t\n \n")).toBe(
+ "@@ -3,1 +2,2 @@\n+two\t\n ",
+ );
+ });
+});
+
describe("buildNativeReviewDiffData languages", () => {
it.each([
["js", "javascript"],
diff --git a/apps/mobile/src/features/review/nativeReviewDiffAdapter.ts b/apps/mobile/src/features/review/nativeReviewDiffAdapter.ts
index d55aa97e305c9..e943fd5c57928 100644
--- a/apps/mobile/src/features/review/nativeReviewDiffAdapter.ts
+++ b/apps/mobile/src/features/review/nativeReviewDiffAdapter.ts
@@ -44,6 +44,32 @@ export function buildNativeReviewSnippetRows(
}));
}
+export function reviewCommentDiffText(diff: string): string {
+ return diff.trimStart().replace(/\n+$/, "");
+}
+
+export function buildReviewCommentPatch(comment: ReviewInlineComment): string {
+ if ((comment.fenceLanguage ?? "diff") !== "diff") {
+ return "";
+ }
+ if (!comment.diff.trim()) {
+ return "";
+ }
+ const diff = reviewCommentDiffText(comment.diff);
+
+ if (diff.startsWith("diff --git ")) {
+ return diff;
+ }
+
+ const normalizedPath = comment.filePath.replaceAll("\\", "/");
+ return [
+ `diff --git a/${normalizedPath} b/${normalizedPath}`,
+ `--- a/${normalizedPath}`,
+ `+++ b/${normalizedPath}`,
+ diff,
+ ].join("\n");
+}
+
function opaqueNativeHexColor(color: string, background: string): string {
const hex = NATIVE_HEX_COLOR.exec(color);
if (hex && !hex[4]) return color;
diff --git a/apps/mobile/src/features/review/useReviewDiffData.ts b/apps/mobile/src/features/review/useReviewDiffData.ts
index d9ec656cbc773..8368c1ec63aa3 100644
--- a/apps/mobile/src/features/review/useReviewDiffData.ts
+++ b/apps/mobile/src/features/review/useReviewDiffData.ts
@@ -55,7 +55,7 @@ function getCachedReviewFile(
...(loaded ?? {
path: stat.path,
previousPath: stat.previousPath,
- changeType: "change" as const,
+ changeType: stat.changeType ?? ("change" as const),
languageHint: null,
additionLines: [],
deletionLines: [],
@@ -142,13 +142,7 @@ export function useReviewDiffData(input: {
});
const registry = useContext(RegistryContext);
const { environmentId, cwd } = input;
- const scope = JSON.stringify([
- environmentId,
- cwd,
- source?.kind,
- source?.baseRef,
- source?.diffHash,
- ]);
+ const scope = JSON.stringify([environmentId, cwd, lazySource?.kind, source?.baseRef]);
const [requested, setRequested] = useState({ scope, indices: [0, 1, 2] });
const indices = useMemo(
() => new Set(requested.scope === scope ? requested.indices : [0, 1, 2]),
diff --git a/apps/mobile/src/features/settings/SettingsNotificationsRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsNotificationsRouteScreen.tsx
index 44a21cd463713..39f6319ca2a67 100644
--- a/apps/mobile/src/features/settings/SettingsNotificationsRouteScreen.tsx
+++ b/apps/mobile/src/features/settings/SettingsNotificationsRouteScreen.tsx
@@ -202,9 +202,7 @@ function ConfiguredSettingsNotificationsRouteScreen() {
}
if (result.value.type === "granted") {
setNotificationStatus("enabled");
- if (agentAwarenessNotificationsReady()) {
- Dialog.alert("Notifications enabled", "Agent notifications are enabled for this device.");
- } else {
+ if (!agentAwarenessNotificationsReady()) {
Dialog.alert(
"Couldn't finish enabling notifications",
"Notification access was granted, but this device could not be registered with T3 Connect. Notifications will start once registration succeeds.",
diff --git a/apps/mobile/src/features/settings/SettingsProjectOverviewRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsProjectOverviewRouteScreen.tsx
index 89408243ef81a..05ef2af346daa 100644
--- a/apps/mobile/src/features/settings/SettingsProjectOverviewRouteScreen.tsx
+++ b/apps/mobile/src/features/settings/SettingsProjectOverviewRouteScreen.tsx
@@ -138,7 +138,11 @@ function ProjectOverviewContent(props: {
}) {
const { isRemoving, setIsRemoving, startRemoval, finishRemoval } = props;
const representative = props.members[0]!;
- const displayName = deriveProjectGroupLabel({ representative, members: props.members });
+ const displayName = deriveProjectGroupLabel({
+ groupKey: props.group.key,
+ representative,
+ members: props.members,
+ });
const [draftName, setDraftName] = useState(null);
const [isSaving, setIsSaving] = useState(false);
const threads = useThreadShells();
diff --git a/apps/mobile/src/features/settings/SettingsRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsRouteScreen.tsx
index 1da8134b0e211..a14fbf51bdb02 100644
--- a/apps/mobile/src/features/settings/SettingsRouteScreen.tsx
+++ b/apps/mobile/src/features/settings/SettingsRouteScreen.tsx
@@ -252,8 +252,9 @@ function useSettingsIndexSections(): SettingsListSection[] {
selectedTargets.some((target) => target.environmentId === project.environmentId),
) ?? [];
const projectLabel =
- scopedProjectMembers.length > 0
+ selectedProject && scopedProjectMembers.length > 0
? deriveProjectGroupLabel({
+ groupKey: selectedProject.key,
representative: scopedProjectMembers[0]!,
members: scopedProjectMembers,
})
diff --git a/apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.test.tsx b/apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.test.tsx
new file mode 100644
index 0000000000000..b92c1ec725b47
--- /dev/null
+++ b/apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.test.tsx
@@ -0,0 +1,264 @@
+import { RegistryContext } from "@effect/atom-react";
+import {
+ EnvironmentId,
+ ProjectId,
+ ProviderInstanceId,
+ ScheduledTaskId,
+ type ScheduledTask,
+} from "@t3tools/contracts";
+import { Atom } from "effect/reactivity";
+import { act, type ReactNode } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
+
+const { Children, mocks } = vi.hoisted(() => ({
+ Children: ({ children }: { children?: ReactNode }) => children,
+ mocks: { upsert: vi.fn(), alert: vi.fn(), tasks: [] as ScheduledTask[] },
+}));
+vi.mock("react-native", () => ({
+ Platform: { OS: "ios" },
+ View: Children,
+ TextInput: () => null,
+ Pressable: ({ children, onPress }: { children?: ReactNode; onPress: () => void }) => (
+
+ ),
+}));
+vi.mock("@react-navigation/native", () => ({
+ useNavigation: () => ({ isFocused: () => false }),
+ usePreventRemove: () => {},
+}));
+vi.mock("react-native-safe-area-context", () => ({ useSafeAreaInsets: () => ({ bottom: 0 }) }));
+vi.mock("@expo/ui/community/datetime-picker", () => ({ DateTimePicker: () => null }));
+vi.mock("../../components/ui/Dialog", () => ({ alert: mocks.alert }));
+vi.mock("../../components/ui/AppText", () => ({ AppText: Children }));
+vi.mock("../../components/ui/AppSymbol", () => ({ SymbolView: () => null }));
+vi.mock("../../components/EnvironmentMachineSymbol", () => ({
+ EnvironmentMachineSymbol: () => null,
+ ENVIRONMENT_MACHINE_SYMBOLS: {},
+}));
+vi.mock("../../components/ui/Menu", () => ({
+ Menu: ({
+ actions,
+ onPressAction,
+ }: {
+ actions: readonly { id: string; title: string }[];
+ onPressAction: (event: { nativeEvent: { event: string } }) => void;
+ }) =>
+ actions.map(({ id, title }) => (
+
+ )),
+}));
+vi.mock("../../components/ui/ScreenScrollView", () => ({ ScreenScrollView: Children }));
+vi.mock("./components/SettingsScreen", () => ({ SettingsScreen: Children }));
+vi.mock("./components/SettingsSection", () => ({ SettingsSection: Children }));
+vi.mock("./components/SettingsEnvironmentFilterHeader", () => ({
+ useSettingsEnvironmentMenu: () => null,
+}));
+vi.mock("./components/ScheduledTaskPromptField", () => ({ ScheduledTaskPromptField: () => null }));
+vi.mock("../layout/workspace/useSelectWorkspaceDetail", () => ({
+ useSelectWorkspaceDetail: () => vi.fn(),
+}));
+vi.mock("../../state/threads", () => ({ threadFamilies: {} }));
+vi.mock("../../lib/copyTextWithHaptic", () => ({ tryCopyTextWithHaptic: vi.fn() }));
+vi.mock("../voice-input/useVoiceInputController", () => ({
+ useVoiceInputController: () => ({ blocksSubmission: false }),
+}));
+vi.mock("../../components/ui/Button", () => ({
+ Button: ({ label, onPress }: { label: string; onPress: () => void }) => (
+
+ ),
+}));
+vi.mock("../../components/ui/SegmentedControl", () => ({
+ SegmentedControl: ({
+ options,
+ onSelect,
+ }: {
+ options: readonly { value: string; label: string }[];
+ onSelect: (value: string) => void;
+ }) =>
+ options.map(({ value, label }) => (
+
+ )),
+}));
+vi.mock("../../components/ui/ThemedSwitch", () => ({
+ ThemedSwitch: ({
+ value,
+ onValueChange,
+ }: {
+ value: boolean;
+ onValueChange: (value: boolean) => void;
+ }) => ,
+}));
+vi.mock("../../state/entities", () => ({
+ useProjects: () => [
+ { environmentId: "environment", id: "project", title: "Project" },
+ { environmentId: "target", id: "target-project", title: "Target project" },
+ ],
+ useServerConfigs: () => new Map(),
+ useEnvironmentServerConfig: () => null,
+ useThreadShell: () => null,
+}));
+vi.mock("./settings-environment-filter", () => ({
+ useSettingsEnvironmentFilter: () => ({
+ selectedTargets: [{ environmentId: "environment", label: "Environment" }],
+ availableTargets: [
+ { environmentId: "environment", label: "Environment" },
+ { environmentId: "target", label: "Target" },
+ ],
+ selectedProjectKey: null,
+ projectGroups: [],
+ }),
+}));
+vi.mock("../../lib/modelOptions", () => ({
+ buildModelOptions: () => [],
+ resolveDefaultableModelSelection: () => null,
+ resolveNewTaskModelSelection: () => null,
+}));
+vi.mock("../../state/session", () => ({
+ readEnvironmentScope: () => true,
+ usePreparedConnection: () => ({ _tag: "None" }),
+}));
+vi.mock("../../state/server", () => ({
+ serverEnvironment: {
+ scheduledTasksLive: () => ({}),
+ upsertScheduledTask: { permissionAtom: () => Atom.make(true) },
+ },
+}));
+vi.mock("../../state/query", () => ({
+ useEnvironmentQuery: () => ({ data: { tasks: mocks.tasks, threads: [] } }),
+}));
+vi.mock("../../state/use-atom-command", () => ({ useAtomCommand: () => mocks.upsert }));
+
+import { appAtomRegistry } from "../../state/atom-registry";
+import { editDraft } from "./scheduledTaskDraft";
+import {
+ scheduledTaskEditorSessionAtom,
+ startScheduledTaskEditor,
+} from "./scheduled-task-editor-state";
+import { SettingsScheduledTaskEditRouteScreen } from "./SettingsScheduledTasksRouteScreen";
+
+let root: Root;
+let container: HTMLDivElement;
+beforeEach(() => {
+ (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+ container = document.createElement("div");
+ root = createRoot(container);
+ mocks.alert.mockReset();
+ mocks.upsert.mockReset();
+ mocks.upsert.mockResolvedValue({ _tag: "Success" });
+ const task: ScheduledTask = {
+ id: ScheduledTaskId.make("task"),
+ title: "Task",
+ prompt: "Prompt",
+ enabled: true,
+ schedule: { type: "fixed_time", timeOfDay: "05:00" },
+ projectId: ProjectId.make("project"),
+ threadId: null,
+ workspaceStrategy: { type: "root" },
+ modelSelection: {
+ instanceId: ProviderInstanceId.make("codex"),
+ model: "model",
+ },
+ runtimeMode: "full-access",
+ interactionMode: "default",
+ createdBy: "user",
+ creationSource: "mobile",
+ createdAt: "2026-10-22T00:00:00.000Z",
+ updatedAt: "2026-10-22T00:00:00.000Z",
+ nextRunAt: null,
+ lastRunAt: null,
+ lastRunStatus: "never",
+ lastRunError: null,
+ runCount: 0,
+ };
+ mocks.tasks = [task];
+ const draft = editDraft(task);
+ startScheduledTaskEditor({
+ environmentId: EnvironmentId.make("environment"),
+ environmentLabel: "Environment",
+ draft: { ...draft, schedule: { ...draft.schedule, intervalMinutes: "60" } },
+ });
+ act(() =>
+ root.render(
+
+
+ ,
+ ),
+ );
+});
+afterEach(() => {
+ act(() => root.unmount());
+ appAtomRegistry.set(scheduledTaskEditorSessionAtom, null);
+});
+function button(label: string) {
+ const element = Array.from(container.querySelectorAll("button")).find(
+ (button) => button.textContent === label,
+ );
+ if (!element) throw new Error(`Missing button: ${label}`);
+ return element;
+}
+describe("scheduled task batched edits", () => {
+ it("submits the selected interval when saved before React commits", async () => {
+ await act(async () => {
+ button("Interval").click();
+ button("Save changes").click();
+ });
+ expect(mocks.alert).not.toHaveBeenCalled();
+ expect(mocks.upsert).toHaveBeenCalledExactlyOnceWith({
+ environmentId: "environment",
+ input: expect.objectContaining({
+ id: "task",
+ requireExisting: true,
+ schedule: { type: "interval", everyMs: 3_600_000 },
+ }),
+ });
+ });
+ it("retains the interval when enabled changes before React commits", async () => {
+ act(() => {
+ button("Interval").click();
+ button("Toggle enabled").click();
+ });
+ expect(appAtomRegistry.get(scheduledTaskEditorSessionAtom)?.current?.draft.schedule.mode).toBe(
+ "interval",
+ );
+ await act(async () => button("Save changes").click());
+ expect(mocks.alert).not.toHaveBeenCalled();
+ expect(mocks.upsert).toHaveBeenCalledExactlyOnceWith({
+ environmentId: "environment",
+ input: expect.objectContaining({
+ id: "task",
+ requireExisting: true,
+ enabled: false,
+ schedule: { type: "interval", everyMs: 3_600_000 },
+ }),
+ });
+ });
+ it("keeps every webhook filter added before React commits", () => {
+ act(() => button("On webhook").click());
+ act(() => {
+ button("Add filter").click();
+ button("Add filter").click();
+ });
+ expect(
+ appAtomRegistry.get(scheduledTaskEditorSessionAtom)?.current?.draft.schedule.filters,
+ ).toHaveLength(2);
+ });
+ it("keeps the target project when an old picker fires after changing environments", () => {
+ const editor = appAtomRegistry.get(scheduledTaskEditorSessionAtom)?.current;
+ if (!editor) throw new Error("Missing editor");
+ act(() => startScheduledTaskEditor({ ...editor, draft: { ...editor.draft, task: null } }));
+ act(() => {
+ button("Select Target").click();
+ button("Interval").click();
+ button("Select Project").click();
+ });
+ expect(appAtomRegistry.get(scheduledTaskEditorSessionAtom)?.current).toMatchObject({
+ environmentId: "target",
+ draft: { projectId: "target-project", schedule: { mode: "interval" } },
+ });
+ });
+});
diff --git a/apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.tsx
index 3f552c1f0c46c..d71fbc8fd9d24 100644
--- a/apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.tsx
+++ b/apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.tsx
@@ -83,7 +83,11 @@ import {
type ScheduledTaskDraft as Draft,
} from "./scheduledTaskDraft";
import { settingsTargetsForProject } from "./settings-environment-filter.logic";
-import { useScheduledTaskDestinationLabel, useScheduledTaskEditor } from "./scheduled-task-editor";
+import {
+ useScheduledTaskDestinationLabel,
+ useScheduledTaskEditor,
+ useScheduledTaskThread,
+} from "./scheduled-task-editor";
import {
discardScheduledTaskEditor,
markScheduledTaskEditorSaved,
@@ -267,11 +271,13 @@ function SelectRow(props: {
function WebhookFilterRows(props: {
readonly filters: ReadonlyArray;
readonly disabled: boolean;
- readonly onChange: (filters: ReadonlyArray) => void;
+ readonly onChange: (
+ update: (filters: ReadonlyArray) => ReadonlyArray,
+ ) => void;
}) {
- const update = (index: number, patch: Partial) =>
- props.onChange(
- props.filters.map((filter, at) => (at === index ? { ...filter, ...patch } : filter)),
+ const update = (id: WebhookFilterDraft["id"], patch: Partial) =>
+ props.onChange((filters) =>
+ filters.map((filter) => (filter.id === id ? { ...filter, ...patch } : filter)),
);
return (
<>
@@ -284,7 +290,9 @@ function WebhookFilterRows(props: {
accessibilityLabel={`Remove filter ${index + 1}`}
disabled={props.disabled}
hitSlop={8}
- onPress={() => props.onChange(removeWebhookFilterDraft(props.filters, filter.id))}
+ onPress={() =>
+ props.onChange((filters) => removeWebhookFilterDraft(filters, filter.id))
+ }
className="active:opacity-70"
>
@@ -295,7 +303,7 @@ function WebhookFilterRows(props: {
value={filter.path}
placeholder="body.action"
disabled={props.disabled}
- onChange={(path) => update(index, { path })}
+ onChange={(path) => update(filter.id, { path })}
/>
{
const known = WEBHOOK_FILTER_OPS.find((option) => option.op === id);
- if (known) update(index, { op: known.op });
+ if (known) update(filter.id, { op: known.op });
}}
/>
{filter.op === "exists" ? null : (
@@ -316,7 +324,7 @@ function WebhookFilterRows(props: {
value={filter.value}
placeholder={filter.op === "in" ? "opened, reopened" : "opened"}
disabled={props.disabled}
- onChange={(value) => update(index, { value })}
+ onChange={(value) => update(filter.id, { value })}
/>
)}
@@ -325,7 +333,13 @@ function WebhookFilterRows(props: {
props.onChange([...props.filters, emptyWebhookFilterDraft()])}
+ onPress={() =>
+ props.onChange((filters) =>
+ filters.length < MAX_WEBHOOK_FILTERS
+ ? [...filters, emptyWebhookFilterDraft()]
+ : filters,
+ )
+ }
className="min-h-14 flex-row items-center gap-3 border-t border-border-subtle px-4 py-3 active:opacity-70"
>
@@ -590,8 +604,19 @@ function SettingsScheduledTaskEditorScreen({ title }: { readonly title: string }
voiceInput={voiceInput}
/>
}
- setDraft={(draft) => {
- if (!saving) setEditor({ ...editor, draft });
+ setDraft={(update) => {
+ if (!saving)
+ setEditor((current) =>
+ current ? { ...current, draft: update(current.draft) } : current,
+ );
+ }}
+ setEnvironmentDraft={(update) => {
+ if (!saving)
+ setEditor((current) =>
+ current && current.environmentId === editor.environmentId
+ ? { ...current, draft: update(current.draft) }
+ : current,
+ );
}}
onSaved={() => {
saved.current = true;
@@ -599,18 +624,21 @@ function SettingsScheduledTaskEditorScreen({ title }: { readonly title: string }
if (navigation.isFocused()) navigation.goBack();
}}
onChangeEnvironment={(target) => {
- if (target.environmentId === editor.environmentId) return;
- setEditor({
- environmentId: target.environmentId,
- environmentLabel: target.label,
- draft: {
- ...draftForEnvironment(target.environmentId),
- title: editor.draft.title,
- prompt: editor.draft.prompt,
- schedule: editor.draft.schedule,
- enabled: editor.draft.enabled,
- },
- });
+ setEditor((current) =>
+ !current || target.environmentId === current.environmentId
+ ? current
+ : {
+ environmentId: target.environmentId,
+ environmentLabel: target.label,
+ draft: {
+ ...draftForEnvironment(target.environmentId),
+ title: current.draft.title,
+ prompt: current.draft.prompt,
+ schedule: current.draft.schedule,
+ enabled: current.draft.enabled,
+ },
+ },
+ );
}}
/>
) : (
@@ -635,6 +663,7 @@ function TaskForm({
dictationPending,
promptField,
setDraft,
+ setEnvironmentDraft,
onSaved,
onChangeEnvironment,
}: {
@@ -646,10 +675,12 @@ function TaskForm({
readonly setSaving: (saving: boolean) => void;
readonly dictationPending: boolean;
readonly promptField: ReactNode;
- readonly setDraft: (draft: Draft) => void;
+ readonly setDraft: (update: (current: Draft) => Draft) => void;
+ readonly setEnvironmentDraft: (update: (current: Draft) => Draft) => void;
readonly onSaved: () => void;
readonly onChangeEnvironment: (target: SettingsTarget) => void;
}) {
+ const { readEditor } = useScheduledTaskEditor();
const navigation = useNavigation>();
const tasks = useEnvironmentQuery(
serverEnvironment.scheduledTasksLive({ environmentId, input: {} }),
@@ -666,6 +697,10 @@ function TaskForm({
.sort((left, right) => Number(right.pinnedAt != null) - Number(left.pinnedAt != null));
const config = useEnvironmentServerConfig(environmentId);
const destinationLabel = useScheduledTaskDestinationLabel(environmentId, draft.threadId);
+ const boundThread = useScheduledTaskThread(environmentId, draft.threadId);
+ // Bound runs use the thread's current model, so the locked row shows that one.
+ const shownSelection =
+ draft.threadId === null ? draft.modelSelection : (boundThread?.modelSelection ?? null);
const modelOptions = buildModelOptions(config, null, undefined, draft.projectId);
// Existing webhook tasks keep the option so they can still switch to a timer.
const webhookDenial = managedCapabilityDenial(config?.managedPolicy, "webhookTasks");
@@ -699,6 +734,9 @@ function TaskForm({
draft.task?.schedule.type === "once";
const offersThreadModes = config?.environment.capabilities.scheduledTaskThreadModes === true;
const save = async () => {
+ const current = readEditor();
+ if (!current || current.environmentId !== environmentId) return;
+ const draft = current.draft;
if (
!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope) ||
submissionPending.current ||
@@ -853,7 +891,7 @@ function TaskForm({
disabled={saving}
value={draft.title}
placeholder="Check for issues"
- onChange={(title) => setDraft({ ...draft, title })}
+ onChange={(title) => setDraft((current) => ({ ...current, title }))}
/>
{promptField}
@@ -873,21 +911,23 @@ function TaskForm({
onSelect={(id) => {
const project = projects.find((item) => item.id === id);
if (!project) return;
- const keepsExplicitModel =
- draft.modelSelectionIsExplicit &&
- (draft.modelSelection === null ||
- !config?.settings ||
- resolveProjectProviderInstanceEnabled(
- config.settings,
- project.id,
- draft.modelSelection.instanceId,
- ));
- setDraft({
- ...changeDraftProject(draft, project.id),
- modelSelection: keepsExplicitModel
- ? draft.modelSelection
- : scheduledTaskDefaultModel(config, project),
- modelSelectionIsExplicit: keepsExplicitModel,
+ setEnvironmentDraft((current) => {
+ const keepsExplicitModel =
+ current.modelSelectionIsExplicit &&
+ (current.modelSelection === null ||
+ !config?.settings ||
+ resolveProjectProviderInstanceEnabled(
+ config.settings,
+ project.id,
+ current.modelSelection.instanceId,
+ ));
+ return {
+ ...changeDraftProject(current, project.id),
+ modelSelection: keepsExplicitModel
+ ? current.modelSelection
+ : scheduledTaskDefaultModel(config, project),
+ modelSelectionIsExplicit: keepsExplicitModel,
+ };
});
}}
/>
@@ -897,14 +937,17 @@ function TaskForm({
value={
modelOptions.find(
(option) =>
- option.selection.instanceId === draft.modelSelection?.instanceId &&
- option.selection.model === draft.modelSelection?.model,
+ option.selection.instanceId === shownSelection?.instanceId &&
+ option.selection.model === shownSelection?.model,
)?.label ??
- draft.modelSelection?.model ??
+ shownSelection?.model ??
(modelOptions.length ? "Choose model" : "No models available")
}
onPress={() => navigation.navigate("SettingsScheduledTaskModel")}
- disabled={saving || dictationPending || environmentUnavailable}
+ // The saved selection only seeds new threads; bound runs ignore it.
+ disabled={
+ saving || dictationPending || environmentUnavailable || draft.threadId !== null
+ }
/>
@@ -935,9 +978,9 @@ function TaskForm({
)}
onSelect={(id) => {
if (id === "new_thread")
- setDraft({ ...unbindDraftFromThread(draft), threadMode: id });
+ setDraft((current) => ({ ...unbindDraftFromThread(current), threadMode: id }));
else if (id === "continue" || id === "fresh_session")
- setDraft({ ...draft, threadMode: id });
+ setDraft((current) => ({ ...current, threadMode: id }));
}}
/>
) : null}
@@ -985,7 +1028,7 @@ function TaskForm({
]}
onSelect={(id) => {
if (id === "worktree" || id === "root" || id === "existing_worktree")
- setDraft({ ...draft, workspace: id });
+ setDraft((current) => ({ ...current, workspace: id }));
}}
/>
{draft.workspace === "worktree" ? (
@@ -1008,10 +1051,10 @@ function TaskForm({
value={draft.checkoutPath}
borderTop
onChange={(checkoutPath) =>
- setDraft({
- ...draft,
- checkoutPath: resolvePastedPath(draft.checkoutPath, checkoutPath),
- })
+ setEnvironmentDraft((current) => ({
+ ...current,
+ checkoutPath: resolvePastedPath(current.checkoutPath, checkoutPath),
+ }))
}
/>
) : null}
@@ -1036,21 +1079,21 @@ function TaskForm({
onSelect={(mode) => {
setTimePickerOpen(false);
setRunAtPicker(null);
- setDraft({
- ...draft,
+ setDraft((current) => ({
+ ...current,
prompt:
- mode === "webhook" && !draft.prompt.trim()
+ mode === "webhook" && !current.prompt.trim()
? DEFAULT_WEBHOOK_PROMPT
- : draft.prompt,
+ : current.prompt,
schedule: {
- ...draft.schedule,
+ ...current.schedule,
mode,
runAt:
- mode === "once" && !draft.schedule.runAt
+ mode === "once" && !current.schedule.runAt
? new Date(Math.ceil(Date.now() / 3_600_000) * 3_600_000).toISOString()
- : draft.schedule.runAt,
+ : current.schedule.runAt,
},
- });
+ }));
}}
/>
@@ -1089,7 +1132,10 @@ function TaskForm({
onDismiss={() => setTimePickerOpen(false)}
onValueChange={(_, selected) => {
const timeOfDay = `${String(selected.getHours()).padStart(2, "0")}:${String(selected.getMinutes()).padStart(2, "0")}`;
- setDraft({ ...draft, schedule: { ...draft.schedule, timeOfDay } });
+ setDraft((current) => ({
+ ...current,
+ schedule: { ...current.schedule, timeOfDay },
+ }));
}}
/>
) : null}
@@ -1118,19 +1164,21 @@ function TaskForm({
})),
]}
onSelect={(id) => {
- const weekdays =
- id === "every_day"
- ? DAYS.map((day) => day.index)
- : id === "weekdays"
- ? [1, 2, 3, 4, 5]
- : (() => {
- const day = DAYS.find((item) => String(item.index) === id);
- if (!day) return draft.schedule.weekdays;
- return draft.schedule.weekdays.includes(day.index)
- ? draft.schedule.weekdays.filter((index) => index !== day.index)
- : [...draft.schedule.weekdays, day.index];
- })();
- setDraft({ ...draft, schedule: { ...draft.schedule, weekdays } });
+ setDraft((current) => {
+ const weekdays =
+ id === "every_day"
+ ? DAYS.map((day) => day.index)
+ : id === "weekdays"
+ ? [1, 2, 3, 4, 5]
+ : (() => {
+ const day = DAYS.find((item) => String(item.index) === id);
+ if (!day) return current.schedule.weekdays;
+ return current.schedule.weekdays.includes(day.index)
+ ? current.schedule.weekdays.filter((index) => index !== day.index)
+ : [...current.schedule.weekdays, day.index];
+ })();
+ return { ...current, schedule: { ...current.schedule, weekdays } };
+ });
}}
/>
>
@@ -1175,10 +1223,10 @@ function TaskForm({
onValueChange={(_, selected) => {
// Android shows a dialog that closes on pick; iOS stays inline.
if (Platform.OS === "android") setRunAtPicker(null);
- setDraft({
- ...draft,
- schedule: { ...draft.schedule, runAt: selected.toISOString() },
- });
+ setDraft((current) => ({
+ ...current,
+ schedule: { ...current.schedule, runAt: selected.toISOString() },
+ }));
}}
/>
) : null}
@@ -1206,14 +1254,20 @@ function TaskForm({
disabled={saving}
borderTop
onChange={(maxDeliveryAgeMinutes) =>
- setDraft({ ...draft, schedule: { ...draft.schedule, maxDeliveryAgeMinutes } })
+ setDraft((current) => ({
+ ...current,
+ schedule: { ...current.schedule, maxDeliveryAgeMinutes },
+ }))
}
/>
- setDraft({ ...draft, schedule: { ...draft.schedule, filters } })
+ onChange={(update) =>
+ setDraft((current) => ({
+ ...current,
+ schedule: { ...current.schedule, filters: update(current.schedule.filters) },
+ }))
}
/>
- setDraft({ ...draft, schedule: { ...draft.schedule, replayKey } })
+ setDraft((current) => ({
+ ...current,
+ schedule: { ...current.schedule, replayKey },
+ }))
}
/>
@@ -1236,7 +1293,10 @@ function TaskForm({
disabled={saving}
borderTop
onChange={(coalesceKey) =>
- setDraft({ ...draft, schedule: { ...draft.schedule, coalesceKey } })
+ setDraft((current) => ({
+ ...current,
+ schedule: { ...current.schedule, coalesceKey },
+ }))
}
/>
- setDraft({ ...draft, schedule: { ...draft.schedule, coalesceWindowSeconds } })
+ setDraft((current) => ({
+ ...current,
+ schedule: { ...current.schedule, coalesceWindowSeconds },
+ }))
}
/>
@@ -1264,7 +1327,10 @@ function TaskForm({
disabled={saving}
borderTop
onChange={(intervalMinutes) =>
- setDraft({ ...draft, schedule: { ...draft.schedule, intervalMinutes } })
+ setDraft((current) => ({
+ ...current,
+ schedule: { ...current.schedule, intervalMinutes },
+ }))
}
/>
{!(parseIntervalMinutes(draft.schedule.intervalMinutes) >= 1) ? (
@@ -1287,7 +1353,7 @@ function TaskForm({
setDraft({ ...draft, enabled })}
+ onValueChange={(enabled) => setDraft((current) => ({ ...current, enabled }))}
/>
diff --git a/apps/mobile/src/features/settings/appearance/useScaledTextRole.ts b/apps/mobile/src/features/settings/appearance/useScaledTextRole.ts
index ffeb6114c17a5..c71298a89822a 100644
--- a/apps/mobile/src/features/settings/appearance/useScaledTextRole.ts
+++ b/apps/mobile/src/features/settings/appearance/useScaledTextRole.ts
@@ -1,4 +1,6 @@
-import { resolveScaledTextRole } from "../../../lib/appearancePreferences";
+import { Platform, useWindowDimensions } from "react-native";
+
+import { resolveComposerTextRole, resolveScaledTextRole } from "../../../lib/appearancePreferences";
import { MOBILE_TYPOGRAPHY } from "../../../lib/typography";
import { useAppearancePreferences } from "./AppearancePreferencesProvider";
@@ -12,3 +14,9 @@ export function useScaledTextRole(role: keyof typeof MOBILE_TYPOGRAPHY): ScaledT
const { appearance } = useAppearancePreferences();
return resolveScaledTextRole(role, appearance.baseFontSize);
}
+
+export function useComposerTextRole(): ScaledTextRole {
+ const body = useScaledTextRole("body");
+ const { fontScale } = useWindowDimensions();
+ return resolveComposerTextRole(body, fontScale, Platform.OS);
+}
diff --git a/apps/mobile/src/features/settings/scheduled-task-editor.tsx b/apps/mobile/src/features/settings/scheduled-task-editor.tsx
index e99600ae533b8..d79ef40896e87 100644
--- a/apps/mobile/src/features/settings/scheduled-task-editor.tsx
+++ b/apps/mobile/src/features/settings/scheduled-task-editor.tsx
@@ -21,22 +21,29 @@ import {
export const NEW_THREAD_DESTINATION_LABEL = "New thread each run";
-export function useScheduledTaskDestinationLabel(
+export function useScheduledTaskThread(
environmentId: EnvironmentId | null,
threadId: ThreadId | null,
-): string {
+) {
const ref =
environmentId === null || threadId === null ? null : scopeThreadRef(environmentId, threadId);
const shell = useThreadShell(ref);
- // The shell can omit older settled threads; their family read still carries the title.
+ // The shell can omit older settled threads; their family read still carries the row.
const family = useEnvironmentQuery(
ref !== null && shell === null
? threadFamilies.familyAtom(ref.environmentId, ref.threadId)
: null,
);
- const thread = shell ?? family.data?.threads.find((row) => row.id === threadId);
- if (ref === null) return NEW_THREAD_DESTINATION_LABEL;
- return thread?.title.trim() || `Thread ${ref.threadId}`;
+ return shell ?? family.data?.threads.find((row) => row.id === threadId) ?? null;
+}
+
+export function useScheduledTaskDestinationLabel(
+ environmentId: EnvironmentId | null,
+ threadId: ThreadId | null,
+): string {
+ const thread = useScheduledTaskThread(environmentId, threadId);
+ if (environmentId === null || threadId === null) return NEW_THREAD_DESTINATION_LABEL;
+ return thread?.title.trim() || `Thread ${threadId}`;
}
/** The form draft lives in an atom, so it survives while its native picker routes are on top. */
diff --git a/apps/mobile/src/features/settings/scheduledTaskPresentation.test.ts b/apps/mobile/src/features/settings/scheduledTaskPresentation.test.ts
new file mode 100644
index 0000000000000..02ca0a2d11c78
--- /dev/null
+++ b/apps/mobile/src/features/settings/scheduledTaskPresentation.test.ts
@@ -0,0 +1,13 @@
+import { describe, expect, it } from "vite-plus/test";
+
+import { formatNextScheduledTaskRun } from "./scheduledTaskPresentation";
+
+describe("formatNextScheduledTaskRun", () => {
+ it("names the rounded unit for a run later today", () => {
+ const now = new Date(2026, 10, 3, 10, 0, 0).getTime();
+ const at = (minutes: number) => new Date(now + minutes * 60_000).toISOString();
+ expect(formatNextScheduledTaskRun(at(59), now)).toBe("Next run in 59 minutes");
+ expect(formatNextScheduledTaskRun(at(59.5), now)).toBe("Next run in 1 hour");
+ expect(formatNextScheduledTaskRun(at(150), now)).toBe("Next run in 3 hours");
+ });
+});
diff --git a/apps/mobile/src/features/settings/scheduledTaskPresentation.ts b/apps/mobile/src/features/settings/scheduledTaskPresentation.ts
index 0fbc2626f1fbb..7ebdcfc2d3b3c 100644
--- a/apps/mobile/src/features/settings/scheduledTaskPresentation.ts
+++ b/apps/mobile/src/features/settings/scheduledTaskPresentation.ts
@@ -38,8 +38,9 @@ export function formatNextScheduledTaskRun(nextRunAt: string, now: number): stri
const days = localCalendarDay(next) - localCalendarDay(current);
if (days === 0) {
if (remaining < MINUTE) return "Next run in less than a minute";
- const unit = remaining < HOUR ? "minute" : "hour";
- const count = Math.round(remaining / (remaining < HOUR ? MINUTE : HOUR));
+ const minutes = Math.round(remaining / MINUTE);
+ const unit = minutes < 60 ? "minute" : "hour";
+ const count = minutes < 60 ? minutes : Math.round(remaining / HOUR);
return `Next run in ${count} ${unit}${count === 1 ? "" : "s"}`;
}
diff --git a/apps/mobile/src/features/sharing/incoming-share-model.test.ts b/apps/mobile/src/features/sharing/incoming-share-model.test.ts
index 3e798975d743c..1dea547de53b4 100644
--- a/apps/mobile/src/features/sharing/incoming-share-model.test.ts
+++ b/apps/mobile/src/features/sharing/incoming-share-model.test.ts
@@ -54,7 +54,7 @@ describe("incoming native shares", () => {
text: "Please explain this error\n\nhttps://example.com/issue/1",
attachments: [
{
- id: "share-1:image:3",
+ id: "share-1-image-3",
type: "image",
name: "Screenshot.png",
mimeType: "image/png",
@@ -131,7 +131,7 @@ describe("incoming native shares", () => {
expect(result.attachments).toEqual([
{
- id: "share-report:file:0",
+ id: "share-report-file-0",
type: "file",
name: "report.pdf",
mimeType: "application/pdf",
@@ -165,7 +165,7 @@ describe("incoming native shares", () => {
expect(result.warnings).toEqual([]);
expect(result.attachments).toEqual([
{
- id: "share-video:file:0",
+ id: "share-video-file-0",
type: "file",
name: video.originalName,
mimeType: video.mimeType,
@@ -239,7 +239,7 @@ describe("incoming native shares", () => {
expect(result.attachments).toEqual([
{
- id: "share-android-report:file:0",
+ id: "share-android-report-file-0",
type: "file",
name: "report",
mimeType: "application/pdf",
diff --git a/apps/mobile/src/features/sharing/incoming-share-model.ts b/apps/mobile/src/features/sharing/incoming-share-model.ts
index aa097713923b6..aa97294e15466 100644
--- a/apps/mobile/src/features/sharing/incoming-share-model.ts
+++ b/apps/mobile/src/features/sharing/incoming-share-model.ts
@@ -332,7 +332,7 @@ export async function buildIncomingShareDraft(input: {
}
}
attachments.push({
- id: `${input.id}:file:${index}`,
+ id: `${input.id}-file-${index}`,
type: "file",
name,
mimeType,
@@ -397,7 +397,7 @@ export async function buildIncomingShareDraft(input: {
}
const dataUrl = `data:${mimeType};base64,${base64}`;
attachments.push({
- id: `${input.id}:image:${index}`,
+ id: `${input.id}-image-${index}`,
type: "image",
name: resolved?.originalName ?? fallbackName(uri, index, mimeType),
mimeType,
diff --git a/apps/mobile/src/features/shortcuts/appShortcutsRuntime.test.ts b/apps/mobile/src/features/shortcuts/appShortcutsRuntime.test.ts
index c985506480b76..961c0f42fa538 100644
--- a/apps/mobile/src/features/shortcuts/appShortcutsRuntime.test.ts
+++ b/apps/mobile/src/features/shortcuts/appShortcutsRuntime.test.ts
@@ -2,6 +2,7 @@ import { describe, expect, it, vi } from "vite-plus/test";
vi.mock("expo-quick-actions", () => ({}));
vi.mock("react-native", () => ({ Platform: { OS: "android" } }));
+vi.mock("../../connection/catalog", () => ({}));
vi.mock("../../persistence/imperative", () => ({}));
vi.mock("../../state/atom-registry", () => ({}));
vi.mock("../../state/threads", () => ({ environmentThreadShells: {} }));
@@ -54,6 +55,23 @@ describe("createRecentThreadShortcuts", () => {
expect(save).toHaveBeenLastCalledWith([thread("a")]);
});
+ it("drops threads of environments that are no longer saved", async () => {
+ const gone = { environmentId: "gone", threadId: "b", title: "b" };
+ const kept = { environmentId: "kept", threadId: "c", title: "c" };
+ const { save, publish, recents } = setup(() => Promise.resolve([thread("a"), gone, kept]));
+ recents.retainEnvironments(new Set(["env", "kept"]));
+ await recents.loaded;
+ expect(publish).toHaveBeenLastCalledWith([thread("a"), kept]);
+
+ recents.retainEnvironments(new Set(["kept"]));
+ await recents.saved();
+ expect(publish).toHaveBeenLastCalledWith([kept]);
+ expect(save).toHaveBeenLastCalledWith([kept]);
+
+ recents.recordActiveThread(thread("a"));
+ expect(publish).toHaveBeenLastCalledWith([kept]);
+ });
+
it("records title changes of the open thread and ignores repeats", async () => {
const { publish, recents } = setup(() => Promise.resolve([]));
await recents.loaded;
diff --git a/apps/mobile/src/features/shortcuts/appShortcutsRuntime.ts b/apps/mobile/src/features/shortcuts/appShortcutsRuntime.ts
index b182c33b07866..a8c3d7b964776 100644
--- a/apps/mobile/src/features/shortcuts/appShortcutsRuntime.ts
+++ b/apps/mobile/src/features/shortcuts/appShortcutsRuntime.ts
@@ -4,6 +4,7 @@ import type { NavigationState } from "@react-navigation/native";
import type { ScopedThreadRef } from "@t3tools/contracts";
import { Atom } from "effect/reactivity";
+import { environmentCatalog } from "../../connection/catalog";
import {
loadRecentThreadShortcuts,
saveRecentThreadShortcuts,
@@ -34,6 +35,7 @@ export function createRecentThreadShortcuts(dependencies: RecentThreadShortcutsD
let recents: ReadonlyArray | null = null;
let persistable = false;
let active: RecentThreadShortcut | null = null;
+ let savedEnvironmentIds: ReadonlySet | null = null;
// Serialize saves so older lists cannot overwrite newer ones.
let saveQueue: Promise = Promise.resolve();
@@ -53,8 +55,11 @@ export function createRecentThreadShortcuts(dependencies: RecentThreadShortcutsD
});
};
+ const isSaved = (thread: RecentThreadShortcut) =>
+ savedEnvironmentIds?.has(thread.environmentId) ?? true;
+
const withActive = (list: ReadonlyArray) => {
- if (active === null) return list;
+ if (active === null || !isSaved(active)) return list;
const next = withRecentThreadShortcut(list, active);
if (next !== list) persistable = true;
return next;
@@ -63,7 +68,7 @@ export function createRecentThreadShortcuts(dependencies: RecentThreadShortcutsD
const loaded = dependencies.load().then(
(threads) => {
persistable = true;
- commit(withActive(threads));
+ commit(withActive(threads.filter(isSaved)));
},
(error: unknown) => {
console.warn("[app-shortcuts] failed to load recent threads", error);
@@ -81,6 +86,12 @@ export function createRecentThreadShortcuts(dependencies: RecentThreadShortcutsD
const updated = withActive(recents);
if (updated !== recents) commit(updated);
},
+ retainEnvironments(next: ReadonlySet): void {
+ savedEnvironmentIds = next;
+ if (recents === null) return;
+ const kept = recents.filter(isSaved);
+ if (kept.length !== recents.length) commit(kept);
+ },
};
}
@@ -142,8 +153,16 @@ export function installAppShortcuts(navigate: (href: string) => void): () => voi
(active) => recents.recordActiveThread(active),
{ immediate: true },
);
+ const unsubscribeCatalog = appAtomRegistry.subscribe(
+ environmentCatalog.catalogValueAtom,
+ (catalog) => {
+ if (catalog.isReady) recents.retainEnvironments(new Set(catalog.entries.keys()));
+ },
+ { immediate: true },
+ );
return () => {
subscription.remove();
unsubscribe();
+ unsubscribeCatalog();
};
}
diff --git a/apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx b/apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx
index 90fac17f8004a..173e0cb62c624 100644
--- a/apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx
+++ b/apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx
@@ -40,7 +40,6 @@ import { LoadingScreen } from "../../components/LoadingScreen";
import { ScreenContent } from "../../components/ui/ScreenContent";
import { Button } from "../../components/ui/Button";
import { IconButton } from "../../components/ui/IconButton";
-import { environmentCatalog } from "../../connection/catalog";
import { useEnvironmentPresentation } from "../../state/presentation";
import { terminalEnvironment } from "../../state/terminal";
import { environmentSession, readEnvironmentScope } from "../../state/session";
@@ -64,6 +63,7 @@ import {
import { useThreadSelection } from "../../state/use-thread-selection";
import { useSelectedThreadProjection } from "../../state/use-thread-detail";
import { EnvironmentConnectionNotice } from "../connection/EnvironmentConnectionNotice";
+import { useRetryEnvironment } from "../connection/useRetryEnvironment";
import { TerminalSurface, type TerminalSurfaceHandle } from "./NativeTerminalSurface";
import { getMobileTerminalTheme } from "./terminalTheme";
import { useTerminalExitNavigation } from "./useTerminalExitNavigation";
@@ -381,7 +381,7 @@ function ThreadTerminal(props: {
const navigation = useNavigation();
const writeTerminal = useAtomCommand(terminalEnvironment.write, "terminal write");
const clearTerminal = useAtomCommand(terminalEnvironment.clear, "terminal clear");
- const retryEnvironment = useAtomCommand(environmentCatalog.retryNow, "environment retry");
+ const retryEnvironment = useRetryEnvironment();
const selectedThreadDetail = useSelectedThreadProjection();
const selectedThreadDetailWorktreePath =
selectedThreadDetail?.projection.thread.worktreePath ?? null;
diff --git a/apps/mobile/src/features/threads/HtmlRenderWebView.tsx b/apps/mobile/src/features/threads/HtmlRenderWebView.tsx
index bf22cd01a1966..b13704196468b 100644
--- a/apps/mobile/src/features/threads/HtmlRenderWebView.tsx
+++ b/apps/mobile/src/features/threads/HtmlRenderWebView.tsx
@@ -22,10 +22,11 @@ import { useAppearancePreferences } from "../settings/appearance/AppearancePrefe
import { webViewDecelerationRate } from "../../lib/webViewDecelerationRate";
const ROW_BOTTOM_MARGIN = 8;
+const ACTION_ROW_HEIGHT = 32;
const FULL_SCREEN_GUTTER = 16;
export function htmlRenderRowHeight(frameHeight: number) {
- return frameHeight + ROW_BOTTOM_MARGIN;
+ return ACTION_ROW_HEIGHT + frameHeight + ROW_BOTTOM_MARGIN;
}
function useHtmlRenderTheme() {
@@ -213,6 +214,34 @@ export function ThreadHtmlRender(props: {
return (
+
+ {uri !== null && !failed ? (
+
+ navigation.navigate("ThreadAttachment", {
+ environmentId: String(props.environmentId),
+ threadId: String(props.threadId),
+ attachmentId,
+ name: fileName,
+ mimeType: "text/html",
+ sizeBytes: "0",
+ htmlRender: "1",
+ })
+ }
+ >
+
+
+ ) : null}
+
{uri !== null && !failed ? (
)}
- {uri !== null && !failed ? (
-
- navigation.navigate("ThreadAttachment", {
- environmentId: String(props.environmentId),
- threadId: String(props.threadId),
- attachmentId,
- name: fileName,
- mimeType: "text/html",
- sizeBytes: "0",
- htmlRender: "1",
- })
- }
- >
-
-
- ) : null}
);
diff --git a/apps/mobile/src/features/threads/McpAppWebView.tsx b/apps/mobile/src/features/threads/McpAppWebView.tsx
index cf03775b7c7fc..203343eb5a680 100644
--- a/apps/mobile/src/features/threads/McpAppWebView.tsx
+++ b/apps/mobile/src/features/threads/McpAppWebView.tsx
@@ -264,6 +264,8 @@ export function ThreadMcpApp(props: {
);
}, [host, detailAtom]);
const userActive = useRef(false);
+ // Teardown completions check this so a replaced document's late callback is ignored.
+ const currentHost = useRef(null);
// Each WebView document gets its own host: the view is keyed by document,
// restart generation and URL, and a changed app re-attaches this callback.
@@ -399,6 +401,8 @@ export function ThreadMcpApp(props: {
}
if (mode === "fullscreen" && current.displayMode !== "fullscreen") {
await documentHost.teardown();
+ // A crash restart or reload during the wait already replaced this document.
+ if (currentHost.current !== documentHost) return "inline";
// Approval arrival or navigation during the wait requires reloading inline.
const navigation = latest.current.navigation;
if (latest.current.awaitingUser || !navigation.isFocused()) {
@@ -417,7 +421,7 @@ export function ThreadMcpApp(props: {
}
if (mode === "inline" && current.displayMode === "fullscreen") {
await documentHost.teardown();
- current.onExitFullscreen?.();
+ if (currentHost.current === documentHost) current.onExitFullscreen?.();
return "inline";
}
return current.displayMode ?? "inline";
@@ -460,11 +464,11 @@ export function ThreadMcpApp(props: {
},
onRequestTeardown: () => {
const current = latest.current.props;
- if (current.displayMode === "fullscreen") {
- void documentHost.teardown().then(() => current.onExitFullscreen?.());
- } else {
- void documentHost.teardown().then(() => setClosed(true));
- }
+ void documentHost.teardown().then(() => {
+ if (currentHost.current !== documentHost) return;
+ if (current.displayMode === "fullscreen") current.onExitFullscreen?.();
+ else setClosed(true);
+ });
},
onSizeChanged: (size) => {
if (latest.current.props.displayMode === "fullscreen") return;
@@ -473,7 +477,9 @@ export function ThreadMcpApp(props: {
},
});
setHost(documentHost);
+ currentHost.current = documentHost;
return () => {
+ if (currentHost.current === documentHost) currentHost.current = null;
// An unmount cannot wait: the request goes out before the view does.
void documentHost.teardown();
setHost((current) => (current === documentHost ? null : current));
diff --git a/apps/mobile/src/features/threads/NewTaskRouteScreen.tsx b/apps/mobile/src/features/threads/NewTaskRouteScreen.tsx
index ac9e2ce813636..8027e1572a073 100644
--- a/apps/mobile/src/features/threads/NewTaskRouteScreen.tsx
+++ b/apps/mobile/src/features/threads/NewTaskRouteScreen.tsx
@@ -523,7 +523,7 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps
}
@@ -548,7 +548,7 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps
diff --git a/apps/mobile/src/features/threads/QuestionAttachments.tsx b/apps/mobile/src/features/threads/QuestionAttachments.tsx
index b8fa753188608..3cc26c42fd7fc 100644
--- a/apps/mobile/src/features/threads/QuestionAttachments.tsx
+++ b/apps/mobile/src/features/threads/QuestionAttachments.tsx
@@ -105,10 +105,7 @@ export function QuestionAttachments(props: {
props.question.id,
);
changeQuestionAttachmentPreparation(key, 1);
- void convertPastedImagesToAttachments({
- uris,
- existingCount: appAtomRegistry.get(composerDraftsAtom)[key]?.attachments.length ?? 0,
- })
+ void convertPastedImagesToAttachments({ uris })
.then(async (result) => {
if (
scope.active &&
diff --git a/apps/mobile/src/features/threads/SubagentRow.tsx b/apps/mobile/src/features/threads/SubagentRow.tsx
index 7c71ac2680de1..96f6f659aa5a1 100644
--- a/apps/mobile/src/features/threads/SubagentRow.tsx
+++ b/apps/mobile/src/features/threads/SubagentRow.tsx
@@ -4,7 +4,10 @@ import {
resolveProviderInstanceDisplayName,
shouldShowInstanceBadge,
} from "@t3tools/client-runtime/state/provider-instance-display";
-import { resolveSubagentMetadata } from "@t3tools/client-runtime/state/subagent-display";
+import {
+ resolveSubagentMetadata,
+ subagentCardDetail,
+} from "@t3tools/client-runtime/state/subagent-display";
import { formatSubagentEffort } from "@t3tools/client-runtime/state/thread-execution";
import type { EnvironmentId, OrchestrationV2Subagent } from "@t3tools/contracts";
import type { ReactNode } from "react";
@@ -15,7 +18,6 @@ import { SymbolView } from "../../components/ui/AppSymbol";
import { ProviderIcon, ProviderInstanceIcon } from "../../components/ProviderIcon";
import { cn } from "../../lib/cn";
import { useEnvironmentServerConfig, useProject, useThreadShell } from "../../state/entities";
-import { subagentCardDetail } from "./subagent-card-presentation";
import { SUBAGENT_TONE_TEXT_CLASS, SubagentStatusDot } from "./SubagentStatusDot";
import { resolveSubagentRowPresentation } from "./threadAgentsPresentation";
diff --git a/apps/mobile/src/features/threads/ThreadComposer.tsx b/apps/mobile/src/features/threads/ThreadComposer.tsx
index 6035338ee6644..ffa9e90bb1fd3 100644
--- a/apps/mobile/src/features/threads/ThreadComposer.tsx
+++ b/apps/mobile/src/features/threads/ThreadComposer.tsx
@@ -16,6 +16,7 @@ import { useAtomValue } from "@effect/atom-react";
import { clampFileAttachmentUploadBytes } from "@t3tools/client-runtime/state/attachments";
import { pastedTextDisposition, replaceTextSelection } from "@t3tools/client-runtime/text-paste";
import {
+ AuthOrchestrationOperateScope,
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
PROVIDER_SEND_TURN_MAX_INPUT_CHARS,
type ChatAttachment,
@@ -30,6 +31,7 @@ import {
hasProviderUsageLimits,
isUsageLimitsCommand,
} from "@t3tools/shared/usageLimits";
+import { parseSideChatCommand } from "@t3tools/shared/composerTrigger";
import { StackActions, useFocusEffect, useNavigation } from "@react-navigation/native";
import type { ReactNode } from "react";
import { useEffect, useEffectEvent, useRef, useState, type RefObject } from "react";
@@ -68,6 +70,7 @@ import type { ComposerDocumentAttachment } from "../../lib/composerContext";
import { useProject, useVisibleThreadShells } from "../../state/entities";
import { useMentionableEnvironments } from "../../state/environments";
import { useLinkedEnvironments } from "../../state/peerLinks";
+import { useEnvironmentScopeDenied } from "../../state/session";
import { scopeProjectRef } from "@t3tools/client-runtime/environment";
import { AppText as Text } from "../../components/ui/AppText";
@@ -80,7 +83,12 @@ import { VideoPreviewModal, type VideoPreviewSource } from "../../components/ui/
import { GlassSurface } from "../../components/ui/GlassSurface";
import { ComposerEditor, type ComposerEditorHandle } from "../../components/ComposerEditor";
import { fileRoutePathSegments } from "../files/filePath";
-import { ComposerActionButton, ComposerToolbarRow } from "../../components/ComposerToolbar";
+import {
+ ComposerActionButton,
+ ComposerInlineControl,
+ ComposerToolbarRow,
+} from "../../components/ComposerToolbar";
+import { formatTokens } from "@t3tools/shared/usageFormat";
import { ComposerModelControl } from "../../components/ComposerModelControl";
import {
composerStripAttachments,
@@ -91,7 +99,7 @@ import {
isModelSelectionUnavailable,
serverConfigForCwd,
} from "../../lib/modelOptions";
-import { useScaledTextRole, type ScaledTextRole } from "../settings/appearance/useScaledTextRole";
+import { useComposerTextRole, type ScaledTextRole } from "../settings/appearance/useScaledTextRole";
import type { RemoteClientConnectionState } from "../../lib/connection";
import { MOBILE_TYPOGRAPHY } from "../../lib/typography";
import { Menu } from "../../components/ui/Menu";
@@ -219,12 +227,20 @@ export interface ThreadComposerProps {
readonly selectedThread: EnvironmentThreadShell;
readonly reportedModelSelection?: ModelSelection | null;
readonly hasCompactableConversation: boolean;
+ /** Set while the next send compacts the thread first. */
+ readonly compactBeforeSend?: {
+ readonly tokens: number;
+ readonly keepFullHistory: boolean;
+ readonly toggleKeepFullHistory: () => void;
+ } | null;
/** Arms a fresh session for the next message; absent where `/clear` is unavailable. */
readonly onFreshSession?: () => void;
readonly offersSideChat?: boolean;
readonly serverConfig: T3ServerConfig | null;
readonly queueCount: number;
readonly activeThreadBusy: boolean;
+ /** Sending declines a pending approval and redirects the agent, so `/side` is plain text. */
+ readonly redirectsApproval: boolean;
readonly canStopThread: boolean;
readonly environmentId: EnvironmentId;
readonly projectCwd: string | null;
@@ -421,7 +437,7 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps
const composerPanel = materialTheme["--color-composer-panel"];
const navigation = useNavigation();
const foregroundColor = useUniwindTheme()["--color-foreground"];
- const bodyText = useScaledTextRole("body");
+ const bodyText = useComposerTextRole();
const fallbackInputRef = useRef(null);
const inputRef = props.editorRef ?? fallbackInputRef;
const [isFocused, setIsFocused] = useState(false);
@@ -473,6 +489,10 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps
setResumingQueue(false);
};
+ const operateDenied = useEnvironmentScopeDenied(
+ props.environmentId,
+ AuthOrchestrationOperateScope,
+ );
const uploadStates = useAtomValue(composerAttachmentUploadsAtom);
const attachmentsUploading =
props.connectionState === "connected" &&
@@ -484,7 +504,10 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps
});
const sendPresentation = resolveComposerSendPresentation({
editingQueuedMessage: queuedEdit !== null,
- running: props.activeThreadBusy,
+ // A side-chat command starts a side chat; it never queues or steers the running turn.
+ running:
+ props.activeThreadBusy &&
+ (props.redirectsApproval || parseSideChatCommand(draftMessage) === null),
canSteer: props.canSteerActiveTurn,
followUpBehavior: props.followUpBehavior,
deliveryDeferred:
@@ -831,6 +854,32 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps
);
+ const compactBeforeSend =
+ props.compactBeforeSend && !showResumeAction && queuedEdit === null
+ ? props.compactBeforeSend
+ : null;
+ const compactTokens = compactBeforeSend ? formatTokens(compactBeforeSend.tokens) : null;
+ const compactControl =
+ compactBeforeSend && compactTokens !== null ? (
+
+ ) : null;
+
return (
props.onHeightChange?.(event.nativeEvent.layout.height)}
@@ -1111,6 +1160,7 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps
compactEditor.isExpanded ? { flex: 1, justifyContent: "flex-end" } : undefined
}
>
+ {compactControl}
{modelControl}
- {props.connectionState === "connected" && !props.canOperateThread ? (
+ {props.connectionState === "connected" && operateDenied ? (
This connection cannot control this task. You can still edit your draft.
diff --git a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx
index cb9e5eb715dc9..73b985fc20144 100644
--- a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx
+++ b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx
@@ -37,7 +37,11 @@ import { useKeyboardScrollToEnd } from "@legendapp/list/keyboard";
import { resolveProviderSkillsForCwd } from "@t3tools/client-runtime/providerSkills";
import type { LegendListRef } from "@legendapp/list/react-native";
import { NativeLayoutObserver } from "../../native/NativeLayoutObserver";
-import { deriveBottomControlInsets, type NativeLayoutMetrics } from "../../lib/reserved-regions";
+import {
+ deriveBottomControlInsets,
+ deriveContentSideInsets,
+ type NativeLayoutMetrics,
+} from "../../lib/reserved-regions";
import type {
EnvironmentId,
MessageId,
@@ -138,6 +142,7 @@ import {
type LayoutVariant,
} from "../../lib/layout";
import { editPendingThreadMessage } from "../../state/edit-pending-thread-message";
+import { environmentCatalog } from "../../connection/catalog";
import { deviceEnvironment } from "../../state/device";
import { useEnvironmentQuery } from "../../state/query";
import { threadDevicePreviews } from "../devices/threadDevicePreviews";
@@ -176,8 +181,6 @@ import { PendingApprovalCard } from "./PendingApprovalCard";
import { ComposerErrorNotice } from "./ComposerErrorNotice";
import { ManagedRuntimeModeNotice } from "./ManagedRuntimeModeNotice";
import { FreshSessionNotice } from "./FreshSessionNotice";
-import { Notice } from "../../components/ui/Notice";
-import { formatTokens } from "@t3tools/shared/usageFormat";
import { ComposerFeedback } from "./ComposerFeedback";
import { ComposerUsageLimits } from "./ComposerUsageLimits";
import { PendingUserInputCard } from "./PendingUserInputCard";
@@ -197,6 +200,7 @@ import {
COMPOSER_COLLAPSED_CHROME,
THREAD_COMPOSER_BOTTOM_GUTTER,
ThreadComposer,
+ type ThreadComposerProps,
} from "./ThreadComposer";
import { ComposerPopoverHost } from "./ComposerPopoverHost";
import { ThreadFeed, type ThreadFeedHistoryControls } from "./ThreadFeed";
@@ -247,11 +251,7 @@ export interface ThreadDetailScreenProps {
readonly extensionStatuses?: NonNullable;
readonly isCompacting: boolean;
/** Set while the next send compacts the thread first. */
- readonly compactBeforeSend?: {
- readonly tokens: number;
- readonly keepFullHistory: boolean;
- readonly toggleKeepFullHistory: () => void;
- } | null;
+ readonly compactBeforeSend?: ThreadComposerProps["compactBeforeSend"];
readonly creationState:
| {
readonly kind: "preparing";
@@ -372,6 +372,7 @@ const wakeAwareVisitShell = Atom.family((key: string) => {
const threadVisitTracker = createThreadVisitTracker({
threadShellAtom: (ref) => wakeAwareVisitShell(threadKey(ref)),
+ sessionGenerationAtom: environmentCatalog.sessionGenerationAtom,
visit: threadEnvironment.visit,
});
@@ -1523,7 +1524,7 @@ function ThreadDetailBody(
}
contentMaxWidth={contentMaxWidth}
historyControls={props.historyControls}
- contentSideInsets={nativeMetrics?.safeArea}
+ contentSideInsets={deriveContentSideInsets(nativeMetrics)}
layoutVariant={layoutVariant}
usesAutomaticContentInsets={props.usesAutomaticContentInsets}
onHeaderMaterialVisibilityChange={props.onHeaderMaterialVisibilityChange}
@@ -1700,25 +1701,6 @@ function ThreadDetailBody(
{freshSessionAvailable ? (
) : null}
- {props.compactBeforeSend ? (
-
-
-
- ) : null}
{props.canOperateThread ? (
0 &&
+ props.activePendingUserInput === null
+ }
canStopThread={props.canStopThread}
environmentId={props.environmentId}
projectCwd={props.threadCwd ?? props.projectWorkspaceRoot}
diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsx
index bbc0ce1066808..f1a9c93f77db3 100644
--- a/apps/mobile/src/features/threads/ThreadFeed.tsx
+++ b/apps/mobile/src/features/threads/ThreadFeed.tsx
@@ -96,6 +96,7 @@ import { CHAT_LIST_ANCHOR_OFFSET, resolveChatListAnchoredEndSpace } from "@t3too
import { imageMimeType } from "@t3tools/shared/image";
import { videoMimeType } from "@t3tools/shared/video";
import { SymbolView, type AppSymbolName } from "../../components/ui/AppSymbol";
+import { textDirection } from "@t3tools/shared/textDirection";
import { useFocusEffect, useNavigation } from "@react-navigation/native";
import { useNativeWorkspaceColumnsSupported } from "../../native/NativeWorkspaceColumns";
import { useDeviceType } from "../../native/native-layout-metrics";
@@ -1124,8 +1125,12 @@ function ArtifactTemplateCard(props: {
readonly template: CodexArtifactTemplate;
readonly onUse?: ((template: CodexArtifactTemplate) => void) | undefined;
}) {
+ const direction = textDirection(props.template.displayName);
return (
-
+
+
+
+
);
}
diff --git a/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx b/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx
index 4040f9d08b09b..76dd9ba271b94 100644
--- a/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx
+++ b/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx
@@ -390,7 +390,6 @@ function ThreadNavigationSidebarPane(props: ThreadNavigationSidebarProps) {
) === props.selectedThreadKey)
}
project={projectByKey.get(pendingScopeKey) ?? null}
- projectTitle={projectTitleByProjectKey.get(pendingScopeKey)}
environmentLabel={
Object.keys(savedConnectionsById).length > 1
? (savedConnectionsById[item.pendingTask.environmentId]?.environmentLabel ?? null)
diff --git a/apps/mobile/src/features/threads/ThreadQueueControl.tsx b/apps/mobile/src/features/threads/ThreadQueueControl.tsx
index d3b3ba6006291..c251283ef8839 100644
--- a/apps/mobile/src/features/threads/ThreadQueueControl.tsx
+++ b/apps/mobile/src/features/threads/ThreadQueueControl.tsx
@@ -25,6 +25,7 @@ import { useSafeAreaInsets } from "react-native-safe-area-context";
import { Button } from "../../components/ui/Button";
import * as Dialog from "../../components/ui/Dialog";
+import { FilePreviewModal, type FilePreviewSource } from "../../components/ui/FilePreviewModal";
import { SheetHeader } from "../../components/ui/SheetHeader";
import { AppText as Text } from "../../components/ui/AppText";
import { SymbolView } from "../../components/ui/AppSymbol";
@@ -143,6 +144,7 @@ export function ThreadQueueSheet({ route }: StaticScreenProps) {
});
const [resuming, setResuming] = useState(false);
const [busyRunId, setBusyRunId] = useState(null);
+ const [previewFile, setPreviewFile] = useState(null);
const busyRef = useRef(false);
const queuedRuns = workflow?.queuedRuns ?? [];
@@ -321,6 +323,7 @@ export function ThreadQueueSheet({ route }: StaticScreenProps) {
{message ? (
@@ -384,6 +387,7 @@ export function ThreadQueueSheet({ route }: StaticScreenProps) {
navigation.goBack()} />
{content}
+ setPreviewFile(null)} />
);
}
@@ -436,8 +440,10 @@ function QueueRowSwipeable(props: {
function QueueAttachmentThumbnails(props: {
readonly environmentId: EnvironmentId;
readonly attachments: ReadonlyArray;
+ readonly onPressPreview: (source: FilePreviewSource) => void;
}) {
const images = props.attachments.filter((attachment) => attachment.mimeType.startsWith("image/"));
+ const gallery = images.map((attachment) => queueImagePreview(props.environmentId, attachment));
const shown = images.slice(0, THUMBNAIL_LIMIT);
const overflow = props.attachments.length - shown.length;
if (props.attachments.length === 0) return null;
@@ -448,6 +454,12 @@ function QueueAttachmentThumbnails(props: {
key={attachment.id}
environmentId={props.environmentId}
attachment={attachment}
+ onPress={() =>
+ props.onPressPreview({
+ ...queueImagePreview(props.environmentId, attachment),
+ gallery,
+ })
+ }
/>
))}
{overflow > 0 ? (
@@ -461,28 +473,60 @@ function QueueAttachmentThumbnails(props: {
);
}
+function queueAttachmentResource(attachment: ChatAttachment) {
+ return {
+ _tag: "attachment",
+ attachmentId: attachment.id,
+ fileName: attachment.name,
+ mimeType: attachment.mimeType,
+ disposition: "inline",
+ } as const;
+}
+
+function queueImagePreview(environmentId: EnvironmentId, attachment: ChatAttachment) {
+ const resource = queueAttachmentResource(attachment);
+ return {
+ kind: "image",
+ environmentId,
+ resource,
+ name: attachment.name,
+ mimeType: attachment.mimeType,
+ actionsSource: {
+ name: attachment.name,
+ mimeType: attachment.mimeType,
+ environmentId,
+ resource,
+ },
+ } as const;
+}
+
function QueueAttachmentThumbnail(props: {
readonly environmentId: EnvironmentId;
readonly attachment: ChatAttachment;
+ readonly onPress: () => void;
}) {
- const resource = {
- _tag: "attachment",
- attachmentId: props.attachment.id,
- fileName: props.attachment.name,
- mimeType: props.attachment.mimeType,
- disposition: "inline",
- } as const;
+ const resource = queueAttachmentResource(props.attachment);
const url = useAssetUrl(props.environmentId, resource);
- if (url === null) {
- return ;
- }
return (
-
+ // Its own press target, so tapping an image previews it instead of editing the message.
+
+ {url === null ? (
+
+ ) : (
+
+ )}
+
);
}
diff --git a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx
index 0bed5a25f0271..51e1e7182ae5a 100644
--- a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx
+++ b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx
@@ -859,7 +859,7 @@ function ThreadRouteContent(
selectedThread?.worktreePath != null ||
(selectedThreadCreation?.message.creation?.workspaceMode === "worktree" &&
selectedThreadCreation.outcome == null),
- turnStarted: setupTurnStartedAt !== null,
+ runs: selectedThreadDetail?.runs ?? [],
followUpSent:
composer.selectedThreadFeed.filter(
(entry) => entry.type === "message" && entry.message.role === "user",
diff --git a/apps/mobile/src/features/threads/resume-thread.ts b/apps/mobile/src/features/threads/resume-thread.ts
index e112423868254..94bed891d7ae4 100644
--- a/apps/mobile/src/features/threads/resume-thread.ts
+++ b/apps/mobile/src/features/threads/resume-thread.ts
@@ -69,7 +69,7 @@ export async function resumeThread(input: {
message: {
messageId: input.messageId,
role: "user",
- text: "Continue where you left off.",
+ text: "",
attachments: [],
},
runtimeMode,
diff --git a/apps/mobile/src/features/threads/subagent-card-presentation.test.ts b/apps/mobile/src/features/threads/subagent-card-presentation.test.ts
index 2b32f84fcb9cc..14a8e6ce99dfe 100644
--- a/apps/mobile/src/features/threads/subagent-card-presentation.test.ts
+++ b/apps/mobile/src/features/threads/subagent-card-presentation.test.ts
@@ -1,17 +1,8 @@
import * as DateTime from "effect/DateTime";
import { describe, expect, it } from "vite-plus/test";
-import { subagentCardDetail, subagentCardElapsed } from "./subagent-card-presentation";
+import { subagentCardElapsed } from "./subagent-card-presentation";
describe("subagent card", () => {
- it.each([
- [" Verified", "screenshot Verified"],
- ["[docs](https://en.wikipedia.org/wiki/T3_(protocol))", "docs"],
- ["[report](outputs/report%20(final).md)", "report"],
- ["[report](outputs/report\\(final.md)", "report"],
- ])("strips image and link markup from %s", (detail, expected) => {
- expect(subagentCardDetail(detail)).toBe(expected);
- });
-
const start = DateTime.makeUnsafe("2026-09-21T12:00:00Z");
const end = DateTime.makeUnsafe("2026-09-21T12:01:00Z");
const later = DateTime.makeUnsafe("2026-09-21T12:02:00Z");
diff --git a/apps/mobile/src/features/threads/subagent-card-presentation.ts b/apps/mobile/src/features/threads/subagent-card-presentation.ts
index 42e75c5cf214e..239f48cf441cc 100644
--- a/apps/mobile/src/features/threads/subagent-card-presentation.ts
+++ b/apps/mobile/src/features/threads/subagent-card-presentation.ts
@@ -3,18 +3,6 @@ import type { OrchestrationV2Subagent } from "@t3tools/contracts";
import { formatDuration } from "@t3tools/shared/orchestrationTiming";
import * as DateTime from "effect/DateTime";
-export function subagentCardDetail(detail: string | null): string | null {
- if (!detail || /^Child task ended with status\b/i.test(detail)) return null;
- return (
- detail
- .replace(/!?\[([^\]]+)\]\((?:\\.|[^\\()]|\((?:\\.|[^\\()])*\))*\)/g, "$1")
- .replace(/`/g, "")
- .replace(/^[ \t]*[-*][ \t]+/gm, "")
- .replace(/\s+/g, " ")
- .trim() || null
- );
-}
-
export function subagentCardElapsed(
agents: ReadonlyArray>,
nowMs: number,
diff --git a/apps/mobile/src/features/threads/thread-list-v2-items.tsx b/apps/mobile/src/features/threads/thread-list-v2-items.tsx
index b6bf0c98e349c..01bd49b028468 100644
--- a/apps/mobile/src/features/threads/thread-list-v2-items.tsx
+++ b/apps/mobile/src/features/threads/thread-list-v2-items.tsx
@@ -79,10 +79,12 @@ import {
resolveThreadListV2SnoozeMenuSelection,
resolveThreadListV2SnoozePresets,
threadHasUnseenCompletion,
+ resolveThreadListV2RowStatus,
resolveThreadListV2Status,
resolveThreadListV2ProviderDrivers,
resolveThreadListV2SwipeActions,
layoutThreadListV2RowMenuActions,
+ threadListV2RowAccessibilityLabel,
type ThreadListV2Status,
} from "./threadListV2";
import { QueuedMessageIcon } from "./queued-message-icon";
@@ -378,7 +380,6 @@ export const ThreadListV2PendingRow = memo(function ThreadListV2PendingRow(props
readonly pendingTask: PendingNewTask;
readonly selected?: boolean;
readonly project: EnvironmentProject | null;
- readonly projectTitle?: string;
readonly environmentLabel: string | null;
readonly environmentMachine?: EnvironmentMachineKind;
readonly pane?: "screen" | "sidebar";
@@ -425,7 +426,6 @@ export const ThreadListV2PendingRow = memo(function ThreadListV2PendingRow(props
}),
[deleteLabel, handleDelete, pendingTask.title],
);
- const projectTitle = props.projectTitle ?? props.project?.title ?? pendingTask.projectTitle ?? "";
const projectCwd = props.project?.workspaceRoot || null;
// Drafts only; the reads are shared per-project atoms, and queued rows skip them.
const projectDefaults = useNewTaskProjectDefaults(isDraft ? props.project : null);
@@ -467,7 +467,7 @@ export const ThreadListV2PendingRow = memo(function ThreadListV2PendingRow(props
faviconPath={props.project.faviconPath}
projectIcon={props.project.projectIcon}
size={projectIconSize}
- projectTitle={projectTitle}
+ projectTitle={props.project.title}
workspaceRoot={props.project.workspaceRoot}
/>
@@ -772,7 +772,8 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
const selected = props.selected === true;
const rowAppearance = getThreadListV2RowAppearance(theme, sidebarPane, selected);
- const status = resolveThreadListV2Status(thread);
+ const rawStatus = resolveThreadListV2Status(thread);
+ const status = resolveThreadListV2RowStatus(thread);
const isUnread = status === "ready" && threadHasUnseenCompletion(thread);
const workingLabel = STATUS_LABEL_BY_STATUS[status];
const showsWoke = status === "ready" && props.wokeAt !== null;
@@ -782,8 +783,20 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
: workingLabel) ?? (isUnread ? DONE_STATUS_LABEL : undefined);
const recede = shouldRecedeThreadRow({ status, selected });
const isRegeneratingTitle = thread.titleRegeneration != null;
- const rowAccessibilityLabel = `${thread.title}${providerNameLabel ? `, ${providerNameLabel}` : ""}${props.hasQueuedMessages ? ", messages queued to send" : ""}${isRegeneratingTitle ? ", regenerating title" : ""}`;
const timeLabel = props.timeLabel;
+ const rowAccessibilityLabel = threadListV2RowAccessibilityLabel({
+ title: thread.title,
+ variant,
+ woke: showsWoke,
+ // Working and waiting rows show only an icon and a duration, so name them for speech.
+ statusLabel:
+ statusLabel && (statusLabel.label ?? (status === "waiting" ? "Waiting" : "Working")),
+ timeLabel,
+ snoozeWakeLabel: snoozedRow ? props.snoozeWakeLabelText : undefined,
+ providerNameLabel,
+ hasQueuedMessages: props.hasQueuedMessages === true,
+ regeneratingTitle: isRegeneratingTitle,
+ });
const visitThread = useAtomCommand(threadEnvironment.visit, { reportFailure: false });
const handleAcknowledgeWoke = useCallback(() => {
@@ -1298,7 +1311,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
) : null}
- {(status === "failed" || status === "limited") && thread.runtime?.lastError ? (
+ {(rawStatus === "failed" || rawStatus === "limited") && thread.runtime?.lastError ? (
{(close) => (
-