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/CodexAuthCallback.test.ts b/apps/desktop/src/app/CodexAuthCallback.test.ts
index 6d8a905885aca..8d69dee35850d 100644
--- a/apps/desktop/src/app/CodexAuthCallback.test.ts
+++ b/apps/desktop/src/app/CodexAuthCallback.test.ts
@@ -5,13 +5,25 @@ import { codexAuthDeliveryUrl, readCodexAuthDelivery } from "@t3tools/shared/cod
import { EnvironmentId, ProviderInstanceId } from "@t3tools/contracts";
import { receiveCodexAuthCallback, cancelCodexAuthCallback } from "./CodexAuthCallback.ts";
+// Holds every probe socket until all ports are read, so one call never returns the same port twice.
+async function freePorts(count: number) {
+ const servers = Array.from({ length: count }, () => NodeHttp.createServer());
+ await Promise.all(
+ servers.map((server) => new Promise((resolve) => server.listen(0, "127.0.0.1", resolve))),
+ );
+ const ports = servers.map((server) => {
+ const address = server.address();
+ if (!address || typeof address === "string") throw new Error("address");
+ return address.port;
+ });
+ await Promise.all(
+ servers.map((server) => new Promise((resolve) => server.close(() => resolve()))),
+ );
+ return ports;
+}
async function freePort() {
- const server = NodeHttp.createServer();
- await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
- const address = server.address();
- if (!address || typeof address === "string") throw new Error("address");
- await new Promise((resolve) => server.close(() => resolve()));
- return address.port;
+ const [port] = await freePorts(1);
+ return port!;
}
function request(port: number, state = "a".repeat(43)) {
const url = new URL("https://auth.openai.com/api/accounts/authorize");
@@ -37,18 +49,27 @@ function callback(authorizationUrl: string) {
}
describe("desktop Codex callback helper", () => {
- it("binds before opening sign-in, ignores a foreign response, and returns only the code callback", async () => {
+ it("binds before opening sign-in, ignores a foreign response, and returns only the code callback", async ({
+ onTestFinished,
+ }) => {
const authorizationUrl = request(await freePort());
const expected = callback(authorizationUrl);
- const received = await receiveCodexAuthCallback(authorizationUrl, async () => {
+ const opening = Promise.withResolvers();
+ onTestFinished(() => opening.resolve(true));
+ const checkResponse = async () => {
const invalid = new URL(expected);
invalid.searchParams.set("state", "foreign");
expect((await fetch(invalid)).status).toBe(400);
const response = await fetch(expected);
expect(response.headers.get("cache-control")).toBe("no-store");
expect(await response.text()).not.toContain("test-code");
- return true;
+ };
+ let responseChecked!: Promise;
+ const received = await receiveCodexAuthCallback(authorizationUrl, () => {
+ responseChecked = checkResponse();
+ return responseChecked.then(() => opening.promise);
});
+ await responseChecked;
expect(received).toBe(expected);
});
it("returns hosted web to the exact instance and environment without putting the code in its query", async () => {
@@ -61,38 +82,57 @@ describe("desktop Codex callback helper", () => {
instanceId: ProviderInstanceId.make("work"),
flowId: "flow-one",
};
+ const openBrowser = async () => {
+ const response = await fetch(expected, { redirect: "manual" });
+ expect(response.status).toBe(303);
+ const delivery = response.headers.get("location")!;
+ expect(new URL(delivery).searchParams.has("code")).toBe(false);
+ expect(readCodexAuthDelivery(delivery)?.callbackUrl).toBe(expected);
+ expect(readCodexAuthDelivery(delivery)?.returnUrl).toBe(input.returnUrl);
+ return true;
+ };
+ let opening!: Promise;
await receiveCodexAuthCallback(
authorizationUrl,
- async () => {
- const response = await fetch(expected, { redirect: "manual" });
- expect(response.status).toBe(303);
- const delivery = response.headers.get("location")!;
- expect(new URL(delivery).searchParams.has("code")).toBe(false);
- expect(readCodexAuthDelivery(delivery)?.callbackUrl).toBe(expected);
- expect(readCodexAuthDelivery(delivery)?.returnUrl).toBe(input.returnUrl);
- return true;
- },
+ () => (opening = openBrowser()),
(url) => codexAuthDeliveryUrl(input, url),
);
+ await opening;
});
- it("cancels and releases its listener so exact-port reauthorization can run again", async () => {
- const authorizationUrl = request(await freePort());
- await expect(
- receiveCodexAuthCallback(authorizationUrl, async () => {
- cancelCodexAuthCallback(authorizationUrl);
- return true;
- }),
- ).rejects.toThrow("cancelled");
- expect(
- await receiveCodexAuthCallback(authorizationUrl, async () => {
- await fetch(callback(authorizationUrl));
- return true;
- }),
- ).toBe(callback(authorizationUrl));
+ it("cancels and releases its listener so exact-port reauthorization can run again", async ({
+ onTestFinished,
+ signal,
+ }) => {
+ for (const external of [false, true]) {
+ const authorizationUrl = request(await freePort());
+ const abort = new AbortController();
+ const opening = Promise.withResolvers();
+ onTestFinished(() => opening.resolve(true));
+ await expect(
+ receiveCodexAuthCallback(
+ authorizationUrl,
+ async () => {
+ if (external) abort.abort();
+ else cancelCodexAuthCallback(authorizationUrl);
+ return opening.promise;
+ },
+ undefined,
+ abort.signal,
+ ),
+ ).rejects.toThrow("cancelled");
+ if (signal.aborted) return;
+ expect(
+ await receiveCodexAuthCallback(authorizationUrl, async () => {
+ await fetch(callback(authorizationUrl));
+ return true;
+ }),
+ ).toBe(callback(authorizationUrl));
+ }
});
it("allows two accounts to complete independently", async () => {
- const a = request(await freePort(), "a".repeat(43));
- const b = request(await freePort(), "c".repeat(43));
+ const [portA, portB] = await freePorts(2);
+ const a = request(portA!, "a".repeat(43));
+ const b = request(portB!, "c".repeat(43));
const openedA = Promise.withResolvers();
const openedB = Promise.withResolvers();
const receiveA = receiveCodexAuthCallback(a, async () => {
diff --git a/apps/desktop/src/app/DesktopApp.ts b/apps/desktop/src/app/DesktopApp.ts
index 0e7f949bc042c..f69bf965d0058 100644
--- a/apps/desktop/src/app/DesktopApp.ts
+++ b/apps/desktop/src/app/DesktopApp.ts
@@ -308,11 +308,9 @@ const bootstrap = Effect.fn("desktop.bootstrap")(function* (backendStarted: bool
}
const primaryBackend = yield* (yield* DesktopBackendPool.DesktopBackendPool).primary;
- // WSL-only fallback can change the primary endpoint before readiness.
const config = yield* primaryBackend.currentConfig;
if (
!environment.isDevelopment &&
- !settings.wslOnly &&
Option.isSome(config) &&
Option.isNone(config.value.preflightFailure)
) {
diff --git a/apps/desktop/src/app/DesktopClerk.ts b/apps/desktop/src/app/DesktopClerk.ts
index 206a143128a8e..207aa17739e59 100644
--- a/apps/desktop/src/app/DesktopClerk.ts
+++ b/apps/desktop/src/app/DesktopClerk.ts
@@ -178,11 +178,12 @@ export const make = Effect.gen(function* () {
Effect.gen(function* () {
yield* electronApp.whenReady;
yield* Effect.tryPromise({
- try: () =>
+ try: (signal) =>
receiveCodexAuthCallback(
request.authorizationUrl,
(url) => runPromise(shell.openExternal(url)),
(callbackUrl) => codexAuthDeliveryUrl(request, callbackUrl),
+ signal,
),
catch: () =>
new CodexAuthCallbackError({
diff --git a/apps/desktop/src/app/DesktopConnectionCatalogStore.test.ts b/apps/desktop/src/app/DesktopConnectionCatalogStore.test.ts
index b3f705a680969..9e5e1db0b980e 100644
--- a/apps/desktop/src/app/DesktopConnectionCatalogStore.test.ts
+++ b/apps/desktop/src/app/DesktopConnectionCatalogStore.test.ts
@@ -583,4 +583,67 @@ describe("DesktopConnectionCatalogStore", () => {
);
}).pipe(Effect.provide(NodeServices.layer)),
);
+
+ const emptyCatalog =
+ '{"schemaVersion":1,"targets":[],"profiles":[],"credentials":[],"remoteDpopTokens":[],"disabledEnvironmentIds":[]}';
+ const savedFilesHolding = Effect.fn(function* (stateDir: string, contents: string) {
+ const fileSystem = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const kept: string[] = [];
+ for (const name of yield* fileSystem.readDirectory(stateDir)) {
+ const file = path.join(stateDir, name);
+ if ((yield* fileSystem.stat(file)).type !== "File") continue;
+ if ((yield* fileSystem.readFileString(file)) === contents) kept.push(name);
+ }
+ return kept;
+ });
+
+ it.effect("keeps a catalog this build cannot decode when the next save replaces it", () =>
+ withStore(
+ Effect.gen(function* () {
+ const path = yield* Path.Path;
+ const environment = yield* DesktopEnvironment.DesktopEnvironment;
+ const fileSystem = yield* FileSystem.FileSystem;
+ const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
+ const catalogPath = path.join(environment.stateDir, "connection-catalog.json");
+ assert.isTrue(
+ yield* store.set(
+ '{"schemaVersion":1,"targets":[{"_tag":"FutureConnectionTarget","environmentId":"remote"}],"profiles":[],"credentials":[],"remoteDpopTokens":[],"disabledEnvironmentIds":[]}',
+ ),
+ );
+ const original = yield* fileSystem.readFileString(catalogPath);
+
+ // Reading fails rather than hand the web client a catalog it would replace with an empty one.
+ yield* store.get.pipe(Effect.flip);
+ assert.isTrue(yield* store.set(emptyCatalog));
+
+ assert.isNotEmpty(yield* savedFilesHolding(environment.stateDir, original));
+ }),
+ ),
+ );
+
+ it.effect("keeps a catalog that no longer decrypts when the next save replaces it", () =>
+ Effect.gen(function* () {
+ const path = yield* Path.Path;
+ const fileSystem = yield* FileSystem.FileSystem;
+ const baseDir = yield* fileSystem.makeTempDirectoryScoped({
+ prefix: "t3-desktop-connection-catalog-test-",
+ });
+ const failDecrypt = yield* Ref.make(false);
+ const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore.pipe(
+ Effect.provide(layerFor(baseDir, true, failDecrypt)),
+ );
+ const stateDir = path.join(baseDir, "userdata");
+ assert.isTrue(yield* store.set('{"schemaVersion":1,"targets":[]}'));
+ const original = yield* fileSystem.readFileString(
+ path.join(stateDir, "connection-catalog.json"),
+ );
+
+ yield* Ref.set(failDecrypt, true);
+ yield* store.get.pipe(Effect.flip);
+ assert.isTrue(yield* store.set(emptyCatalog));
+
+ assert.isNotEmpty(yield* savedFilesHolding(stateDir, original));
+ }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
+ );
});
diff --git a/apps/desktop/src/app/DesktopConnectionCatalogStore.ts b/apps/desktop/src/app/DesktopConnectionCatalogStore.ts
index 1b6b97d439faa..5ca62a868b1c5 100644
--- a/apps/desktop/src/app/DesktopConnectionCatalogStore.ts
+++ b/apps/desktop/src/app/DesktopConnectionCatalogStore.ts
@@ -15,6 +15,7 @@ import { fromLenientJson } from "@t3tools/shared/schemaJson";
import * as Context from "effect/Context";
import * as SecureRandom from "effect/crypto/SecureRandom";
import * as Effect from "effect/Effect";
+import * as Clock from "effect/Clock";
import * as Base64 from "effect/encoding/Base64";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
@@ -62,6 +63,7 @@ const DesktopConnectionCatalogStoreWriteOperation = Schema.Literals([
"create-directory",
"write-temporary-file",
"replace-catalog-file",
+ "keep-unreadable-catalog",
]);
const DesktopConnectionCatalogStoreMigrationOperation = Schema.Literals([
@@ -409,6 +411,57 @@ export const make = Effect.gen(function* () {
),
);
+ const decryptDocument = (document: EncryptedConnectionCatalogDocument) =>
+ decodeSecretBytes(catalogPath, document.encryptedCatalog).pipe(
+ Effect.flatMap((encryptedCatalog) =>
+ safeStorage.decryptString(encryptedCatalog).pipe(
+ Effect.mapError(
+ (cause) =>
+ new DesktopConnectionCatalogStoreProtectionError({
+ operation: "decrypt-catalog",
+ catalogPath,
+ cause,
+ }),
+ ),
+ ),
+ ),
+ );
+
+ // A catalog this build cannot decrypt or decode may still hold another build's saved
+ // environments and credentials, so a save copies it aside instead of destroying it.
+ const keepUnreadableCatalog = Effect.gen(function* () {
+ const readable = yield* readDocument(fileSystem, catalogPath).pipe(
+ Effect.flatMap(
+ Option.match({
+ onNone: () => Effect.succeed(true),
+ onSome: (document) =>
+ decryptDocument(document).pipe(
+ Effect.flatMap(decodeRuntimeConnectionCatalogDocumentJson),
+ Effect.as(true),
+ ),
+ }),
+ ),
+ Effect.orElseSucceed(() => false),
+ );
+ if (readable) {
+ return;
+ }
+ const keptPath = `${catalogPath}.unreadable-${yield* Clock.currentTimeMillis}`;
+ yield* fileSystem.copyFile(catalogPath, keptPath).pipe(
+ Effect.mapError(
+ (cause) =>
+ new DesktopConnectionCatalogStoreWriteError({
+ operation: "keep-unreadable-catalog",
+ path: keptPath,
+ cause,
+ }),
+ ),
+ );
+ yield* Effect.logWarning("Kept an unreadable connection catalog before replacing it.", {
+ keptPath,
+ });
+ });
+
const writeCatalog = Effect.fn("desktop.connectionCatalogStore.writeCatalog")(function* (
catalog: string,
) {
@@ -570,7 +623,10 @@ export const make = Effect.gen(function* () {
if (!(yield* encryptionAvailable)) {
return false;
}
- yield* writeCatalog(catalog).pipe(mutex.withPermits(1));
+ yield* keepUnreadableCatalog.pipe(
+ Effect.andThen(writeCatalog(catalog)),
+ mutex.withPermits(1),
+ );
return true;
}),
});
diff --git a/apps/desktop/src/app/DesktopStartupRecovery.test.ts b/apps/desktop/src/app/DesktopStartupRecovery.test.ts
index 029bcaac2b487..5d407feff79d1 100644
--- a/apps/desktop/src/app/DesktopStartupRecovery.test.ts
+++ b/apps/desktop/src/app/DesktopStartupRecovery.test.ts
@@ -211,3 +211,75 @@ it.effect.each([
}),
).pipe(Effect.provide(DesktopState.layer)),
);
+
+it.effect("installs the build the update action downloaded, not the one it offered", () =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const installed = yield* Deferred.make();
+ const shown = yield* Deferred.make();
+ let navigate: ((event: { preventDefault: () => void }, url: string) => void) | undefined;
+ const recovery = {
+ isDestroyed: () => false,
+ loadURL: () => Promise.resolve(),
+ once: () => {},
+ webContents: {
+ setWindowOpenHandler: () => {},
+ on: (_event: string, listener: typeof navigate) => {
+ navigate = listener;
+ Deferred.doneUnsafe(shown, Effect.void);
+ },
+ },
+ } as unknown as Electron.BrowserWindow;
+ const offered = updateState({ status: "available", availableVersion: "0.1.4" });
+ const state = yield* DesktopState.DesktopState;
+ yield* listen.pipe(
+ Effect.provide(
+ Layer.mergeAll(
+ FileSystem.layerNoop({ readFileString: () => Effect.succeed("0.1.3") }),
+ Layer.succeed(DesktopEnvironment.DesktopEnvironment, {
+ appVersion: "0.1.3",
+ stateDir: "/task/state",
+ logDir: "/task/logs",
+ path: { join: (...parts: string[]) => parts.join("/") },
+ } as unknown as DesktopEnvironment.DesktopEnvironment["Service"]),
+ Layer.succeed(ElectronApp.ElectronApp, {
+ on: () => Effect.void,
+ } as unknown as ElectronApp.ElectronApp["Service"]),
+ Layer.succeed(
+ ElectronShell.ElectronShell,
+ {} as ElectronShell.ElectronShell["Service"],
+ ),
+ Layer.succeed(ElectronTheme.ElectronTheme, {
+ shouldUseDarkColors: Effect.succeed(false),
+ } as ElectronTheme.ElectronTheme["Service"]),
+ Layer.succeed(ElectronWindow.ElectronWindow, {
+ main: Effect.succeedNone,
+ create: () => Effect.succeed(recovery),
+ } as unknown as ElectronWindow.ElectronWindow["Service"]),
+ Layer.succeed(DesktopUpdates.DesktopUpdates, {
+ subscribe: Effect.succeed({ latest: offered, changes: Stream.empty }),
+ check: () => Effect.void,
+ getState: Effect.succeed(offered),
+ // A release published since the offer: the download fetches it instead.
+ download: Effect.succeed({
+ accepted: true,
+ completed: true,
+ state: updateState({ status: "downloaded", downloadedVersion: "0.1.5" }),
+ }),
+ installPrepared: (version: string) => Deferred.succeed(installed, version),
+ } as unknown as DesktopUpdates.DesktopUpdates["Service"]),
+ ),
+ ),
+ );
+ yield* SubscriptionRef.set(state.primaryBackendStartup, {
+ _tag: "Failing",
+ reason: "Server failed before readiness",
+ managedPolicy: false,
+ output: "Failure details",
+ });
+ yield* Deferred.await(shown);
+ navigate!({ preventDefault: () => {} }, "https://startup-recovery.invalid/update");
+ expect(yield* Deferred.await(installed)).toBe("0.1.5");
+ }),
+ ).pipe(Effect.provide(DesktopState.layer)),
+);
diff --git a/apps/desktop/src/app/DesktopStartupRecovery.ts b/apps/desktop/src/app/DesktopStartupRecovery.ts
index c8228183aad91..769a30cf7680b 100644
--- a/apps/desktop/src/app/DesktopStartupRecovery.ts
+++ b/apps/desktop/src/app/DesktopStartupRecovery.ts
@@ -212,13 +212,15 @@ export const listen: Effect.Effect<
switch (action) {
case "update": {
if (current._tag !== "Update") return;
- const state = yield* updates.getState;
- if (state.downloadedVersion === null) {
+ let { downloadedVersion } = yield* updates.getState;
+ if (downloadedVersion === null) {
+ // The download re-checks first, so it can fetch a newer build than the one offered.
const download = yield* updates.download;
if (!download.completed) return;
+ downloadedVersion = download.state.downloadedVersion;
}
- // Waits for a running background check; plain install would refuse.
- yield* updates.installPrepared(current.version);
+ if (downloadedVersion === null) return;
+ yield* updates.installPrepared(downloadedVersion);
return;
}
case "reinstall":
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 a62af9e86e5a8..0881a7ea2efa0 100644
--- a/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts
+++ b/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts
@@ -392,7 +392,7 @@ describe("DesktopBackendConfiguration", () => {
runtimeId: string;
sha256: string;
}> = [];
- const observedProbeRoots: string[] = [];
+ let probeCount = 0;
let legacyCleanupCount = 0;
const linuxAppRoot = "/home/test/.t3/wsl-runtime/1.2.3-x64";
const resolvedPath = "/home/test/.local/bin:/usr/bin:/bin";
@@ -413,8 +413,8 @@ describe("DesktopBackendConfiguration", () => {
});
return { ok: true, linuxAppRoot };
},
- probeRuntime: (_distro, root) => {
- observedProbeRoots.push(root);
+ probeRuntime: () => {
+ probeCount += 1;
return { ok: true, resolvedPath };
},
ensureNodePty: () => {
@@ -435,7 +435,7 @@ describe("DesktopBackendConfiguration", () => {
sha256: archiveHash,
},
]);
- assert.deepEqual(observedProbeRoots, [linuxAppRoot]);
+ assert.equal(probeCount, 1);
assert.equal(
config.entryPath,
path.join(baseDir, "server.asar/apps/server/dist/bin.mjs"),
@@ -572,10 +572,10 @@ describe("DesktopBackendConfiguration", () => {
);
});
- it.effect("resolveWsl retires a staged runtime whose executable does not start", () => {
+ it.effect("resolveWsl retires a staged runtime whose launch probe fails", () => {
const archiveHash = "c".repeat(64);
const stagedAppRoot = `/home/test/.t3/wsl-runtime/sha256-${archiveHash}`;
- const observedProbeRoots: string[] = [];
+ let probeCount = 0;
const observedNodePtyRoots: string[] = [];
const invalidatedRuntimeIds: string[] = [];
return withPackagedWslHarness(
@@ -587,9 +587,9 @@ describe("DesktopBackendConfiguration", () => {
Effect.sync(() => {
invalidatedRuntimeIds.push(runtimeId);
}),
- probeRuntime: (_distro, root) => {
- observedProbeRoots.push(root);
- return { ok: false, reason: `${root}/t3 --version failed (exit 127)` };
+ probeRuntime: () => {
+ probeCount += 1;
+ return { ok: false, reason: "WSL login-shell PATH could not be resolved" };
},
ensureNodePty: (_distro, root) => {
observedNodePtyRoots.push(root);
@@ -602,7 +602,7 @@ describe("DesktopBackendConfiguration", () => {
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
const config = yield* configuration.resolveWsl({ port: 5000, distro: "Ubuntu" });
- assert.deepEqual(observedProbeRoots, [stagedAppRoot]);
+ assert.equal(probeCount, 1);
assert.deepEqual(observedNodePtyRoots, [mountedAppRoot]);
assert.include(config.args, "/usr/bin/node");
assert.include(config.args, `${mountedAppRoot}/apps/server/dist/bin.mjs`);
@@ -627,7 +627,7 @@ describe("DesktopBackendConfiguration", () => {
Effect.sync(() => {
invalidatedRuntimeIds.push(runtimeId);
}),
- probeRuntime: () => ({ ok: false, reason: "t3 --version failed (exit 1)" }),
+ probeRuntime: () => ({ ok: false, reason: "WSL login-shell PATH could not be resolved" }),
ensureNodePty: () => ({
ok: false,
reason: "WSL backend preflight timed out while probing for Node.js.",
diff --git a/apps/desktop/src/backend/DesktopBackendConfiguration.ts b/apps/desktop/src/backend/DesktopBackendConfiguration.ts
index ec8e4afc49675..12866e1c644a2 100644
--- a/apps/desktop/src/backend/DesktopBackendConfiguration.ts
+++ b/apps/desktop/src/backend/DesktopBackendConfiguration.ts
@@ -424,7 +424,7 @@ const runWslPreflight = Effect.fn("desktop.backendConfiguration.wslPreflight")(f
const runtime = yield* wslEnv.prepareRuntime(runningDistro, input.runtimeArchive);
if (runtime.ok) {
// Staged runtimes bundle Node and node-pty; provider PATH discovery must not require them.
- const stagedProbe = yield* wslEnv.probeRuntime(runningDistro, runtime.linuxAppRoot);
+ const stagedProbe = yield* wslEnv.probeRuntime(runningDistro);
if (stagedProbe.ok) {
yield* wslServerTree.cleanupLegacy;
return {
@@ -437,7 +437,7 @@ const runWslPreflight = Effect.fn("desktop.backendConfiguration.wslPreflight")(f
} as const;
}
yield* Effect.logWarning(
- "The staged WSL runtime did not start; retrying from the mounted server tree.",
+ "The staged WSL runtime probe failed; retrying from the mounted server tree.",
{ reason: stagedProbe.reason },
);
stagedFailure = { runtimeId: input.runtimeArchive.runtimeId, reason: stagedProbe.reason };
diff --git a/apps/desktop/src/backend/DesktopBackendManager.test.ts b/apps/desktop/src/backend/DesktopBackendManager.test.ts
index 06a1f768f4bd4..ff5b7b8c08e4b 100644
--- a/apps/desktop/src/backend/DesktopBackendManager.test.ts
+++ b/apps/desktop/src/backend/DesktopBackendManager.test.ts
@@ -11,6 +11,7 @@ import {
DATABASE_MIGRATIONS_STARTED_MESSAGE,
} from "@t3tools/shared/databaseMigrationLog";
import { assert, describe, it } from "@effect/vitest";
+import * as Clock from "effect/Clock";
import * as Deferred from "effect/Deferred";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
@@ -239,6 +240,43 @@ describe("DesktopBackendManager", () => {
}),
);
+ it.effect("notices a WSL backend soon after it listens despite slow refused connects", () =>
+ Effect.gen(function* () {
+ const ready = yield* Deferred.make();
+ const exit = yield* Deferred.make();
+ const instance = yield* makeTestInstance({
+ config: { ...baseConfig, httpBaseUrl: new URL("http://172.20.84.98:3773") },
+ onReady: Deferred.succeed(ready, undefined).pipe(Effect.asVoid),
+ spawnerLayer: Layer.succeed(
+ ChildProcessSpawner.ChildProcessSpawner,
+ ChildProcessSpawner.make(() =>
+ Effect.acquireRelease(
+ Effect.succeed(makeProcess({ exitCode: Deferred.await(exit) })),
+ () => Deferred.succeed(exit, ChildProcessSpawner.ExitCode(0)),
+ ),
+ ),
+ ),
+ // Before the server listens at 300 ms, each refused connect takes a second to fail.
+ httpClientLayer: layerHttpClient((request) =>
+ Clock.currentTimeMillis.pipe(
+ Effect.flatMap((now) =>
+ now < 300
+ ? Effect.sleep(Duration.seconds(1)).pipe(
+ Effect.as(responseForRequest(request, 503)),
+ )
+ : Effect.succeed(responseForRequest(request, 200)),
+ ),
+ ),
+ ),
+ });
+ yield* instance.start;
+ yield* TestClock.adjust(Duration.millis(600));
+
+ assert.isTrue(yield* Deferred.isDone(ready));
+ yield* instance.stop();
+ }),
+ );
+
it.effect("spawns the backend with fd3 bootstrap and fd4 telemetry", () =>
Effect.gen(function* () {
let spawnedCommand: ChildProcess.Command | undefined;
diff --git a/apps/desktop/src/backend/DesktopBackendManager.ts b/apps/desktop/src/backend/DesktopBackendManager.ts
index 4acaa8a3c18b8..8b4f154b5d4de 100644
--- a/apps/desktop/src/backend/DesktopBackendManager.ts
+++ b/apps/desktop/src/backend/DesktopBackendManager.ts
@@ -344,8 +344,26 @@ const closeRun = (
);
};
+const LOOPBACK_HOSTNAMES = new Set(["127.0.0.1", "localhost", "[::1]"]);
+// Windows takes about a second to fail a refused connection to a non-loopback address such as a
+// WSL distro IP, so one sequential poller notices readiness up to a second late.
+const STAGGERED_READINESS_POLLERS = 4;
+const READINESS_POLLER_STAGGER = Duration.millis(250);
+
const waitForHttpReady = (
options: BackendProcessContext & { readonly timeout: Duration.Duration },
+): Effect.Effect => {
+ const poll = pollHttpReady(options);
+ if (LOOPBACK_HOSTNAMES.has(options.httpBaseUrl.hostname)) return poll;
+ return Effect.raceAll(
+ Array.from({ length: STAGGERED_READINESS_POLLERS }, (_, index) =>
+ Effect.sleep(Duration.times(READINESS_POLLER_STAGGER, index)).pipe(Effect.andThen(poll)),
+ ),
+ );
+};
+
+const pollHttpReady = (
+ options: BackendProcessContext & { readonly timeout: Duration.Duration },
): Effect.Effect => {
const readinessUrl = new URL(BACKEND_READINESS_PATH, options.httpBaseUrl);
return waitForHttpReadyShared({
diff --git a/apps/desktop/src/backend/DesktopBackendPool.test.ts b/apps/desktop/src/backend/DesktopBackendPool.test.ts
index 8e9f4320c08c7..005a1cde1224a 100644
--- a/apps/desktop/src/backend/DesktopBackendPool.test.ts
+++ b/apps/desktop/src/backend/DesktopBackendPool.test.ts
@@ -112,6 +112,10 @@ function layerPool(
labelRef: Ref.Ref,
options: {
readonly config?: DesktopBackendStartConfig;
+ readonly resolvePrimary?: Effect.Effect;
+ readonly onMainContentsCommand?: (
+ command: DesktopWindow.MainWindowContentsCommand,
+ ) => Effect.Effect;
readonly fileSystem?: Partial;
readonly spawner?: ChildProcessSpawner.ChildProcessSpawner["Service"];
readonly httpClient?: HttpClient.HttpClient;
@@ -180,9 +184,11 @@ function layerPool(
}),
DesktopBrowserHost.layer,
Layer.succeed(DesktopBackendConfiguration.DesktopBackendConfiguration, {
- resolvePrimary: options.config
- ? Effect.succeed(options.config)
- : Effect.die("unexpected primary config resolve"),
+ resolvePrimary:
+ options.resolvePrimary ??
+ (options.config
+ ? Effect.succeed(options.config)
+ : Effect.die("unexpected primary config resolve")),
resolvePrimaryLabel: Ref.get(labelRef),
resolveWsl: () => Effect.die("unexpected WSL config resolve"),
currentBootstrapToken: Effect.die("unexpected bootstrap token read"),
@@ -190,7 +196,12 @@ function layerPool(
DesktopAppSettings.layerTest(),
DesktopState.layer,
DesktopWslEnvironment.layerTest(),
- ElectronDialog.layer,
+ Layer.succeed(ElectronDialog.ElectronDialog, {
+ pickFolder: () => Effect.die("unexpected folder picker"),
+ pickFiles: () => Effect.die("unexpected file picker"),
+ showMessageBox: () => Effect.die("unexpected message box"),
+ showErrorBox: () => Effect.void,
+ } satisfies ElectronDialog.ElectronDialog["Service"]),
ElectronApp.layer,
Layer.succeed(DesktopWindow.DesktopWindow, {
createMain: Effect.die("unexpected window create"),
@@ -206,7 +217,8 @@ function layerPool(
dispatchMenuAction: () => Effect.die("unexpected menu action"),
dispatchSnapShotEvent: () => Effect.void,
zoomMain: () => Effect.die("unexpected zoom"),
- runMainContentsCommand: () => Effect.die("unexpected main contents command"),
+ runMainContentsCommand:
+ options.onMainContentsCommand ?? (() => Effect.die("unexpected main contents command")),
syncAppearance: Effect.void,
} satisfies DesktopWindow.DesktopWindow["Service"]),
),
@@ -478,4 +490,70 @@ describe("DesktopBackendPool", () => {
assert.equal(Option.isNone(yield* pool.get(id)), true);
}).pipe(Effect.provide(layerPool(Ref.makeUnsafe("Windows")))),
);
+
+ it.effect("reloads a main window that read the WSL endpoint before the Windows fallback", () =>
+ Effect.gen(function* () {
+ const events: string[] = [];
+ let resolves = 0;
+ const resolvePrimary = Effect.sync(() =>
+ resolves++ === 0
+ ? {
+ ...runningConfig,
+ preflightFailure: Option.some({
+ reason: "WSL still unavailable",
+ fatal: false,
+ retryLimit: 1,
+ }),
+ }
+ : runningConfig,
+ );
+ const ready = yield* Deferred.make();
+ yield* Effect.gen(function* () {
+ const primary = yield* (yield* DesktopBackendPool.DesktopBackendPool).primary;
+ yield* primary.start;
+ yield* TestClock.adjust(Duration.seconds(1));
+ yield* Deferred.await(ready);
+
+ assert.deepEqual(events, ["reload", "ready"]);
+ }).pipe(
+ Effect.provide(
+ layerPool(Ref.makeUnsafe("WSL"), {
+ resolvePrimary,
+ spawner: ChildProcessSpawner.make(() =>
+ Effect.gen(function* () {
+ const exited = yield* Deferred.make();
+ const exit = Deferred.succeed(exited, ChildProcessSpawner.ExitCode(0)).pipe(
+ Effect.asVoid,
+ );
+ yield* Effect.addFinalizer(() => exit);
+ return ChildProcessSpawner.makeHandle({
+ pid: ChildProcessSpawner.ProcessId(123),
+ stdout: Stream.empty,
+ stderr: Stream.empty,
+ all: Stream.empty,
+ exitCode: Deferred.await(exited),
+ isRunning: Effect.succeed(true),
+ kill: () => exit,
+ stdin: Sink.drain,
+ getInputFd: () => Sink.drain,
+ getOutputFd: () => Stream.empty,
+ unref: Effect.succeed(Effect.void),
+ });
+ }),
+ ),
+ httpClient: HttpClient.make((request) =>
+ Effect.succeed(
+ HttpClientResponse.fromWeb(request, new Response(null, { status: 200 })),
+ ),
+ ),
+ onMainContentsCommand: (command) => Effect.sync(() => void events.push(command)),
+ onReady: Effect.sync(() => void events.push("ready")).pipe(
+ Effect.andThen(Deferred.succeed(ready, undefined)),
+ Effect.asVoid,
+ ),
+ }),
+ ),
+ );
+ }),
+ );
});
diff --git a/apps/desktop/src/backend/DesktopBackendPool.ts b/apps/desktop/src/backend/DesktopBackendPool.ts
index d69e1ce1427fe..62c811996b1a0 100644
--- a/apps/desktop/src/backend/DesktopBackendPool.ts
+++ b/apps/desktop/src/backend/DesktopBackendPool.ts
@@ -167,10 +167,22 @@ export const layer = Layer.effect(
// One wait at a time: each run's shutdown or readiness ends the previous run's wait.
const updateMarkerWait = yield* FiberHandle.make();
+ // The main window loads during startup and reads the primary endpoint once; a Windows fallback
+ // before the first readiness replaces the WSL endpoint it read.
+ let primaryWasReady = false;
+ let reloadMainOnReady = false;
+ const reloadStaleMain = Effect.suspend(() => {
+ primaryWasReady = true;
+ if (!reloadMainOnReady) return Effect.void;
+ reloadMainOnReady = false;
+ return desktopWindow.runMainContentsCommand("reload");
+ });
+
// Persist fatal Windows fallbacks; transient transport failures must preserve the user's WSL preference.
const handlePrimaryPreflightFailure = Effect.fn("desktop.backendPool.primaryPreflightFailed")(
function* (failure: DesktopBackendManager.PreflightFailure) {
const { reason, fatal } = failure;
+ if (!primaryWasReady) reloadMainOnReady = true;
if (!fatal) {
yield* logBackendPoolWarning(
"primary WSL preflight retry window exhausted; using Windows for this launch",
@@ -215,6 +227,7 @@ export const layer = Layer.effect(
// Absorb window errors so readiness can reset restartAttempt.
onReady: (httpBaseUrl, pid) =>
FiberHandle.run(updateMarkerWait, releaseUpdateMarker(httpBaseUrl, pid)).pipe(
+ Effect.andThen(reloadStaleMain),
Effect.andThen(desktopWindow.handleBackendReady(httpBaseUrl)),
// Only once the main window exists, so the recovery window never closes into nothing.
Effect.andThen(SubscriptionRef.set(primaryBackendStartup, { _tag: "Ready" })),
diff --git a/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.test.ts b/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.test.ts
index e82e3afea7303..c15ce3932bb80 100644
--- a/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.test.ts
+++ b/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.test.ts
@@ -1,11 +1,13 @@
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
import { assert, describe, it } from "@effect/vitest";
+import * as Clock from "effect/Clock";
import * as Deferred from "effect/Deferred";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Ref from "effect/Ref";
+import * as Result from "effect/Result";
import * as HttpClient from "effect/http/HttpClient";
import * as HttpClientRequest from "effect/http/HttpClientRequest";
import * as HttpClientResponse from "effect/http/HttpClientResponse";
@@ -238,4 +240,34 @@ describe("DesktopLocalEnvironmentAuth", () => {
assert.strictEqual(yield* Ref.get(requestCount), 1);
}).pipe(Effect.provide(TestClock.layer())),
);
+
+ it.effect("waits through a backend that stalls for 30 seconds after it is ready", () =>
+ Effect.gen(function* () {
+ const requestCount = yield* Ref.make(0);
+ const layerHttpClient = Layer.succeed(
+ HttpClient.HttpClient,
+ HttpClient.make((request) =>
+ Effect.gen(function* () {
+ yield* Ref.update(requestCount, (count) => count + 1);
+ const now = yield* Clock.currentTimeMillis;
+ return now < 30_000 ? yield* Effect.never : tokenResponse(request);
+ }),
+ ),
+ );
+ const auth = yield* DesktopLocalEnvironmentAuth.DesktopLocalEnvironmentAuth.pipe(
+ Effect.provide(
+ DesktopLocalEnvironmentAuth.layer.pipe(
+ Layer.provide(Layer.mergeAll(layerPool, layerHttpClient, NodeCrypto.layerMac)),
+ ),
+ ),
+ );
+
+ const fiber = yield* auth.getBearerToken.pipe(Effect.result, Effect.forkChild);
+ yield* TestClock.adjust(Duration.seconds(45));
+ const result = yield* Fiber.join(fiber);
+
+ assert.isTrue(Result.isSuccess(result));
+ assert.strictEqual(yield* Ref.get(requestCount), 4);
+ }).pipe(Effect.provide(TestClock.layer())),
+ );
});
diff --git a/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.ts b/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.ts
index 6c7d24623d40f..89aa3cd2a678c 100644
--- a/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.ts
+++ b/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.ts
@@ -17,7 +17,8 @@ import * as HttpClient from "effect/http/HttpClient";
import * as DesktopBackendPool from "./DesktopBackendPool.ts";
-const BOOTSTRAP_TRANSIENT_RETRY_TIMEOUT = Duration.seconds(15);
+// Each /oauth/token attempt may take 10 s, so a backend busy after ready needs several attempts.
+const BOOTSTRAP_TRANSIENT_RETRY_TIMEOUT = Duration.seconds(60);
const BOOTSTRAP_TRANSIENT_RETRY_INTERVAL = Duration.millis(500);
const TRANSIENT_BOOTSTRAP_STATUS_CODES = new Set([502, 503, 504]);
diff --git a/apps/desktop/src/electron/ElectronAudio.test.ts b/apps/desktop/src/electron/ElectronAudio.test.ts
new file mode 100644
index 0000000000000..b38d7bbb3ae47
--- /dev/null
+++ b/apps/desktop/src/electron/ElectronAudio.test.ts
@@ -0,0 +1,60 @@
+import * as Effect from "effect/Effect";
+import * as HostProcess from "@t3tools/shared/HostProcess";
+import { app } from "electron";
+import { expect, vi } from "vite-plus/test";
+import { it } from "@effect/vitest";
+import * as Fiber from "effect/Fiber";
+
+const { getAppMetrics, kill } = vi.hoisted(() => ({ getAppMetrics: vi.fn(), kill: vi.fn() }));
+vi.mock("node:process", () => ({ kill }));
+vi.mock("electron", async () => {
+ const { EventEmitter } = await import("node:events");
+ return { app: Object.assign(new EventEmitter(), { getAppMetrics }) };
+});
+
+import { restart } from "./ElectronAudio.ts";
+
+const audio = { pid: 42, type: "Utility", serviceName: "audio.mojom.AudioService" };
+
+it.effect("coalesces recovery and waits for its own audio utility to exit", () =>
+ Effect.gen(function* () {
+ getAppMetrics.mockReturnValue([
+ { pid: 1, type: "Utility", serviceName: "network.mojom.NetworkService" },
+ { pid: 2, type: "Browser", serviceName: audio.serviceName },
+ audio,
+ ]);
+ const started = Promise.withResolvers();
+ kill.mockReset().mockImplementation(() => {
+ started.resolve();
+ });
+ const pending = yield* Effect.forkChild(
+ Effect.all([restart(), restart()], { concurrency: "unbounded" }),
+ );
+ yield* Effect.promise(() => started.promise);
+ app.emit(
+ "child-process-gone",
+ {},
+ { type: "Utility", serviceName: "network.mojom.NetworkService" },
+ );
+ expect(app.listenerCount("child-process-gone")).toBe(1);
+ app.emit("child-process-gone", {}, audio);
+ expect(yield* Fiber.join(pending)).toEqual([true, true]);
+ expect(kill.mock.calls).toEqual([[42, "SIGTERM"]]);
+ expect(app.listenerCount("child-process-gone")).toBe(0);
+ }).pipe(Effect.provideService(HostProcess.Platform, "linux")),
+);
+
+it.effect.each(["linux", "darwin", "win32"] as const)(
+ "leaves other processes alone on %s",
+ (platform) =>
+ Effect.gen(function* () {
+ getAppMetrics.mockReturnValue([
+ { pid: 1, type: "Utility", serviceName: "network.mojom.NetworkService" },
+ ]);
+ kill.mockReset();
+ expect(yield* restart().pipe(Effect.provideService(HostProcess.Platform, platform))).toBe(
+ false,
+ );
+ expect(kill).not.toHaveBeenCalled();
+ }),
+);
diff --git a/apps/desktop/src/electron/ElectronAudio.ts b/apps/desktop/src/electron/ElectronAudio.ts
new file mode 100644
index 0000000000000..6a7f290d6fd83
--- /dev/null
+++ b/apps/desktop/src/electron/ElectronAudio.ts
@@ -0,0 +1,62 @@
+// @effect-diagnostics globalTimers:off -- The shared native restart deadline must outlive individual IPC callers.
+// @effect-diagnostics nodeBuiltinImport:off -- Only Electron's main process can restart its Chromium audio utility.
+import * as NodeProcess from "node:process";
+import * as Effect from "effect/Effect";
+import * as Schema from "effect/Schema";
+import * as HostProcess from "@t3tools/shared/HostProcess";
+import { app, type Details, type Event } from "electron";
+
+class AudioServiceRestartError extends Schema.TaggedError()(
+ "AudioServiceRestartError",
+ { cause: Schema.Defect() },
+) {}
+
+let pendingRestart: Promise | undefined;
+
+export const restart = Effect.fn("ElectronAudio.restart")(function* () {
+ if ((yield* HostProcess.Platform) !== "linux") return false;
+ return yield* Effect.tryPromise({
+ try: () => {
+ if (pendingRestart) return pendingRestart;
+ const audio = app
+ .getAppMetrics()
+ .find(
+ (metric) =>
+ metric.type === "Utility" && metric.serviceName === "audio.mojom.AudioService",
+ );
+ if (!audio) return Promise.resolve(false);
+ // A failed PulseAudio context survives new getUserMedia calls; Chromium reconnects when its utility exits.
+ pendingRestart = new Promise((resolve, reject) => {
+ const cleanup = () => {
+ clearTimeout(timer);
+ app.removeListener("child-process-gone", onGone);
+ };
+ const onGone = (_event: Event, details: Details) => {
+ if (details.type === "Utility" && details.serviceName === audio.serviceName) {
+ cleanup();
+ resolve(true);
+ }
+ };
+ const timer = setTimeout(() => {
+ cleanup();
+ resolve(false);
+ }, 5_000);
+ app.on("child-process-gone", onGone);
+ try {
+ NodeProcess.kill(audio.pid, "SIGTERM");
+ } catch (cause) {
+ cleanup();
+ reject(cause);
+ }
+ }).finally(() => {
+ pendingRestart = undefined;
+ });
+ return pendingRestart;
+ },
+ catch: (cause) => new AudioServiceRestartError({ cause }),
+ }).pipe(
+ Effect.catch((cause) =>
+ Effect.logWarning("Could not restart the audio service", cause).pipe(Effect.as(false)),
+ ),
+ );
+});
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 57d7101cf9ec7..60b72deb293a5 100644
--- a/apps/desktop/src/ipc/DesktopIpcHandlers.ts
+++ b/apps/desktop/src/ipc/DesktopIpcHandlers.ts
@@ -44,6 +44,7 @@ import {
getWindowFullscreenState,
openExternal,
readMedia,
+ restartAudioService,
openSystemSettings,
checkSystemPermission,
pasteAsText,
@@ -109,6 +110,7 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers"
yield* ipc.handle(getHostEnvironmentId);
yield* ipc.handle(getLocalEnvironmentBearerToken);
+ yield* ipc.handle(restartAudioService);
yield* ipc.handle(getClientSettings);
yield* ipc.handle(setClientSettings);
yield* ipc.handle(getConnectionCatalog);
diff --git a/apps/desktop/src/ipc/channels.ts b/apps/desktop/src/ipc/channels.ts
index b7bb5e579572f..9e5c7296a3a03 100644
--- a/apps/desktop/src/ipc/channels.ts
+++ b/apps/desktop/src/ipc/channels.ts
@@ -101,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";
@@ -139,3 +140,5 @@ export const RECEIVE_PROVIDER_AUTH_CALLBACK_CHANNEL = "desktop:receive-provider-
export const CANCEL_PROVIDER_AUTH_CALLBACK_CHANNEL = "desktop:cancel-provider-auth-callback";
export const TAKE_LEGACY_LOCAL_STORAGE_CHANNEL = "desktop:take-legacy-local-storage";
export const COMPLETE_LEGACY_LOCAL_STORAGE_CHANNEL = "desktop:complete-legacy-local-storage";
+
+export const RESTART_AUDIO_SERVICE_CHANNEL = "desktop:restart-audio-service";
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/providerAuth.ts b/apps/desktop/src/ipc/methods/providerAuth.ts
index fbde6a409f3f2..d7f432815d2ae 100644
--- a/apps/desktop/src/ipc/methods/providerAuth.ts
+++ b/apps/desktop/src/ipc/methods/providerAuth.ts
@@ -23,8 +23,13 @@ export const receiveProviderAuthCallback = DesktopIpc.makeIpcMethod({
const context = yield* Effect.context();
const runPromise = Effect.runPromiseWith(context);
const callbackUrl = yield* Effect.tryPromise({
- try: () =>
- receiveCodexAuthCallback(authorizationUrl, (url) => runPromise(shell.openExternal(url))),
+ try: (signal) =>
+ receiveCodexAuthCallback(
+ authorizationUrl,
+ (url) => runPromise(shell.openExternal(url)),
+ undefined,
+ signal,
+ ),
catch: () =>
new CodexAuthCallbackError({
detail:
diff --git a/apps/desktop/src/ipc/methods/window.test.ts b/apps/desktop/src/ipc/methods/window.test.ts
index fbeda6d2f2dcd..de202529c4113 100644
--- a/apps/desktop/src/ipc/methods/window.test.ts
+++ b/apps/desktop/src/ipc/methods/window.test.ts
@@ -1,6 +1,8 @@
import { assert, describe, it } from "@effect/vitest";
import * as NodeServices from "@effect/platform-node/NodeServices";
import type { ManagedPolicyLimits } from "@t3tools/contracts";
+import { EDITORS, REMOTE_CAPABLE_EDITOR_IDS } from "@t3tools/contracts";
+import { resolveEditorCommand } from "@t3tools/shared/editor";
import * as HostProcess from "@t3tools/shared/HostProcess";
import { ManagedPolicyFileError } from "@t3tools/shared/managedPolicyFile";
import * as FileSystem from "effect/FileSystem";
@@ -517,3 +519,108 @@ it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
assert.include(editors, "webstorm");
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
+
+describe("probeRemoteEditors PATH scan", () => {
+ const platform = HostProcess.Platform.defaultValue();
+ const launcherName = (command: string) => (platform === "win32" ? `${command}.cmd` : command);
+
+ const makeFakePath = Effect.fnUntraced(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-probe-path-" });
+ const dirs = ["a", "b", "c", "d"].map((name) => path.join(root, name));
+ for (const dir of dirs) yield* fs.makeDirectory(dir, { recursive: true });
+ // Launchers in different PATH directories, deliberately not in REMOTE_CAPABLE_EDITOR_IDS order.
+ for (const [dir, command] of [
+ [dirs[2]!, "webstorm"],
+ [dirs[0]!, "cursor"],
+ [dirs[3]!, "code"],
+ [dirs[1]!, "zeditor"],
+ ] as const) {
+ const file = path.join(dir, launcherName(command));
+ yield* fs.writeFileString(file, "#!/bin/sh\n");
+ if (platform !== "win32") yield* fs.chmod(file, 0o755);
+ }
+ return {
+ root,
+ env: {
+ HOME: root,
+ USERPROFILE: root,
+ PATH: dirs.join(platform === "win32" ? ";" : ":"),
+ PATHEXT: ".COM;.EXE;.BAT;.CMD",
+ },
+ };
+ });
+
+ const countingFileSystem = (counter: { stat: number; reads: Map }) =>
+ Layer.effect(
+ FileSystem.FileSystem,
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ return FileSystem.FileSystem.of({
+ ...fs,
+ stat: (target) => {
+ counter.stat += 1;
+ return fs.stat(target);
+ },
+ readDirectory: (target, options) => {
+ counter.reads.set(target, (counter.reads.get(target) ?? 0) + 1);
+ return fs.readDirectory(target, options);
+ },
+ });
+ }),
+ ).pipe(Layer.provideMerge(NodeServices.layer));
+
+ const serialReference = (env: Record) =>
+ Effect.gen(function* () {
+ const available: Array = [];
+ for (const editorId of REMOTE_CAPABLE_EDITOR_IDS) {
+ const editor = EDITORS.find((candidate) => candidate.id === editorId);
+ if (editor && Option.isSome(yield* resolveEditorCommand(editor, env))) {
+ available.push(editorId);
+ }
+ }
+ return available;
+ });
+
+ it.effect("reads each PATH directory once instead of stat-ing every candidate per editor", () =>
+ Effect.gen(function* () {
+ const { env: baseEnv } = yield* makeFakePath();
+ const delimiter = platform === "win32" ? ";" : ":";
+ const uncachedCounter = { stat: 0, reads: new Map() };
+ const cachedCounter = { stat: 0, reads: new Map() };
+ const uncachedEnv = { ...baseEnv, PATH: `${baseEnv.PATH}${delimiter}${baseEnv.HOME}x1` };
+ const cachedEnv = { ...baseEnv, PATH: `${baseEnv.PATH}${delimiter}${baseEnv.HOME}x2` };
+ const uncached = yield* serialReference(uncachedEnv).pipe(
+ Effect.provide(countingFileSystem(uncachedCounter)),
+ );
+ const cached = yield* probeRemoteEditors
+ .handler(undefined)
+ .pipe(
+ Effect.provideService(HostProcess.Environment, cachedEnv),
+ Effect.provideService(HostProcess.Platform, platform),
+ Effect.provide(countingFileSystem(cachedCounter)),
+ );
+ // The host can add editors from app folders the fixture can't redirect (e.g. /Applications).
+ const fixtureEditors = ["cursor", "vscode", "zed", "webstorm"];
+ assert.deepStrictEqual(
+ uncached.filter((id) => fixtureEditors.includes(id)),
+ fixtureEditors,
+ );
+ assert.deepStrictEqual(cached, uncached);
+ assert.isAbove(uncachedCounter.stat, 0);
+ // On every platform the probe lists each PATH directory at most once. Only PATH entries count:
+ // resolveEditorCommand also reads app folders such as /Applications on macOS.
+ const pathReads = cachedEnv.PATH.split(delimiter)
+ .filter((entry) => entry.length > 0)
+ .map((entry) => cachedCounter.reads.get(entry) ?? 0);
+ assert.isAbove(Math.max(...pathReads), 0);
+ assert.isAtMost(Math.max(...pathReads), 1);
+ // Without the listings, Windows stats every PATH entry x PATHEXT candidate for each editor;
+ // elsewhere there is no PATHEXT, so the stat count is about the same either way.
+ if (platform === "win32") {
+ assert.isBelow(cachedCounter.stat, uncachedCounter.stat / 2);
+ }
+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
+ );
+});
diff --git a/apps/desktop/src/ipc/methods/window.ts b/apps/desktop/src/ipc/methods/window.ts
index cee92e1ead38c..38887ec71d906 100644
--- a/apps/desktop/src/ipc/methods/window.ts
+++ b/apps/desktop/src/ipc/methods/window.ts
@@ -17,6 +17,7 @@ import {
} from "@t3tools/contracts";
import { PROJECT_FAVICON_EXTENSIONS } from "@t3tools/shared/projectFavicon";
import { resolveEditorCommand } from "@t3tools/shared/editor";
+import { withPathDirectoryListings } from "@t3tools/shared/shell";
import * as HostProcess from "@t3tools/shared/HostProcess";
import { isRelayTracingEnabled } from "@t3tools/shared/otelEnvironment";
import * as FileSystem from "effect/FileSystem";
@@ -36,6 +37,7 @@ import * as DesktopAppSettings from "../../settings/DesktopAppSettings.ts";
import * as DesktopWslBackend from "../../wsl/DesktopWslBackend.ts";
import * as DesktopWslEnvironment from "../../wsl/DesktopWslEnvironment.ts";
import * as ElectronApp from "../../electron/ElectronApp.ts";
+import * as ElectronAudio from "../../electron/ElectronAudio.ts";
import * as ElectronDialog from "../../electron/ElectronDialog.ts";
import * as ElectronMenu from "../../electron/ElectronMenu.ts";
import * as ElectronShell from "../../electron/ElectronShell.ts";
@@ -427,20 +429,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]);
}),
});
@@ -588,3 +596,10 @@ export const checkSystemPermission = DesktopIpc.makeIpcMethod({
return yield* Effect.promise(check);
}),
});
+
+export const restartAudioService = DesktopIpc.makeIpcMethod({
+ channel: IpcChannels.RESTART_AUDIO_SERVICE_CHANNEL,
+ payload: Schema.Void,
+ result: Schema.Boolean,
+ handler: ElectronAudio.restart,
+});
diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts
index 003009f7190fa..432577917a3ea 100644
--- a/apps/desktop/src/main.ts
+++ b/apps/desktop/src/main.ts
@@ -1,8 +1,8 @@
import * as MacPermissions from "./permissions/MacPermissions.ts";
+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 e0ac5f2161051..ba9c17aae2695 100644
--- a/apps/desktop/src/preload.ts
+++ b/apps/desktop/src/preload.ts
@@ -115,6 +115,7 @@ contextBridge.exposeInMainWorld("desktopBridge", {
ipcRenderer.sendSync(IpcChannels.GET_RELAY_TELEMETRY_ENABLED_CHANNEL) === true,
getPathForFile: (file: File) => webUtils.getPathForFile(file),
getClientPlatform: () => clientPlatform,
+ restartAudioService: () => ipcRenderer.invoke(IpcChannels.RESTART_AUDIO_SERVICE_CHANNEL),
setNotificationBadge: (badge) =>
ipcRenderer.invoke(IpcChannels.SET_NOTIFICATION_BADGE_CHANNEL, badge),
onNotificationBadgeClear: (listener) => {
@@ -414,6 +415,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 88c45f37cc467..7808682dfd82b 100644
--- a/apps/desktop/src/shell/DesktopShellEnvironment.test.ts
+++ b/apps/desktop/src/shell/DesktopShellEnvironment.test.ts
@@ -2,6 +2,7 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, describe, it } from "@effect/vitest";
import * as HostProcess from "@t3tools/shared/HostProcess";
+import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as Deferred from "effect/Deferred";
@@ -62,6 +63,26 @@ function makeProcess(output: string, exitCode = 0): ChildProcessSpawner.ChildPro
});
}
+function makeSlowProcess(
+ output: string,
+ delay: Duration.Input,
+): ChildProcessSpawner.ChildProcessHandle {
+ const stdout = Stream.fromEffect(Effect.as(Effect.sleep(delay), textEncoder.encode(output)));
+ return ChildProcessSpawner.makeHandle({
+ pid: ChildProcessSpawner.ProcessId(125),
+ stdout,
+ stderr: Stream.empty,
+ all: stdout,
+ exitCode: Effect.as(Effect.sleep(delay), ChildProcessSpawner.ExitCode(0)),
+ isRunning: Effect.succeed(true),
+ kill: () => Effect.void,
+ stdin: Sink.drain,
+ getInputFd: () => Sink.drain,
+ getOutputFd: () => Stream.empty,
+ unref: Effect.succeed(Effect.void),
+ });
+}
+
function makeHungProcess(): ChildProcessSpawner.ChildProcessHandle {
return ChildProcessSpawner.makeHandle({
pid: ChildProcessSpawner.ProcessId(124),
@@ -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);
@@ -670,6 +691,129 @@ describe("DesktopShellEnvironment", () => {
}),
);
+ it.effect("retries the user's shell when only the fallback shell answered", () =>
+ Effect.gen(function* () {
+ const env: NodeJS.ProcessEnv = { SHELL: "/usr/bin/fish", PATH: "/usr/bin" };
+ const commands: string[] = [];
+ let fishReady = false;
+ yield* runShellEnvironment({
+ env,
+ platform: "linux",
+ handler: (command) => {
+ if (command._tag !== "StandardCommand") return "";
+ commands.push(command.command);
+ if (command.command !== "/usr/bin/fish") return envOutput({ PATH: "/usr/bin" });
+ return fishReady
+ ? envOutput({ PATH: "/fish/bin:/usr/bin" })
+ : { output: "", exitCode: 7 };
+ },
+ use: (service) =>
+ Effect.gen(function* () {
+ assert.isTrue(yield* service.awaitDiscovery);
+ assert.equal(env.PATH, "/usr/bin");
+ // The Linux probe checks the D-Bus socket on the real filesystem, which the clock does not await.
+ const published = yield* service.updates.pipe(
+ Stream.filter((snapshot) => snapshot.environment.PATH === "/fish/bin:/usr/bin"),
+ Stream.runHead,
+ Effect.forkChild({ startImmediately: true }),
+ );
+
+ fishReady = true;
+ yield* TestClock.adjust("30 seconds");
+ assert.isTrue(Option.isSome(yield* Fiber.join(published)));
+ assert.equal(env.PATH, "/fish/bin:/usr/bin");
+ return true;
+ }),
+ }).pipe(Effect.provide(Logger.layer([])));
+ assert.deepEqual(commands, ["/usr/bin/fish", "/bin/bash", "/usr/bin/fish"]);
+
+ // With no user shell to wait for, the fallback's answer is final.
+ commands.length = 0;
+ yield* runShellEnvironment({
+ env: { PATH: "/usr/bin" },
+ platform: "linux",
+ handler: (command) => {
+ if (command._tag === "StandardCommand") commands.push(command.command);
+ return envOutput({ PATH: "/usr/bin" });
+ },
+ use: (service) =>
+ Effect.gen(function* () {
+ assert.isTrue(yield* service.awaitDiscovery);
+ yield* TestClock.adjust("5 minutes");
+ return true;
+ }),
+ }).pipe(Effect.provide(Logger.layer([])));
+ assert.deepEqual(commands, ["/bin/bash"]);
+ }),
+ );
+
+ it.effect("gives background retries time for a locked or slow shell, then publishes", () =>
+ Effect.gen(function* () {
+ const env: NodeJS.ProcessEnv = { SHELL: "/bin/zsh", PATH: "/usr/bin" };
+ // Startup fails fast, the first retry meets a shell blocked on a lock, the second a slow one.
+ const spawned = yield* Effect.forEach([0, 1, 2], () => Deferred.make());
+ const stopped = yield* Deferred.make();
+ let attempts = 0;
+ yield* runShellEnvironment({
+ env,
+ platform: "darwin",
+ handler: () => "",
+ processSpawner: ChildProcessSpawner.make((command) => {
+ if (command._tag !== "StandardCommand" || command.command !== "/bin/zsh") {
+ return Effect.succeed(makeProcess(""));
+ }
+ const attempt = attempts++;
+ const spawn = Deferred.succeed(spawned[attempt]!, undefined);
+ if (attempt === 0) return spawn.pipe(Effect.as(makeProcess("")));
+ if (attempt === 1) {
+ return spawn.pipe(
+ Effect.andThen(
+ Effect.acquireRelease(Effect.succeed(makeHungProcess()), () =>
+ Deferred.succeed(stopped, command.options),
+ ),
+ ),
+ );
+ }
+ return spawn.pipe(
+ Effect.as(makeSlowProcess(envOutput({ PATH: "/fresh/bin" }), "20 seconds")),
+ );
+ }),
+ use: (service) =>
+ Effect.gen(function* () {
+ assert.isFalse(yield* service.awaitDiscovery);
+ const published = yield* service.updates.pipe(
+ Stream.drop(1),
+ Stream.runHead,
+ Effect.forkChild({ startImmediately: true }),
+ );
+
+ yield* TestClock.adjust("30 seconds");
+ yield* Deferred.await(spawned[1]!);
+ // pyenv waits up to 60 s on its rehash lock before the shell continues.
+ yield* TestClock.adjust("1 minute");
+ assert.isFalse(yield* Deferred.isDone(stopped));
+ yield* TestClock.adjust("1 minute");
+ const stop = yield* Deferred.await(stopped);
+ // pyenv releases that lock in an EXIT trap, which SIGTERM runs and SIGKILL skips.
+ assert.equal(stop.killSignal, "SIGTERM");
+ assert.isAtLeast(Duration.toMillis(stop.forceKillAfter ?? 0), 5_000);
+
+ yield* TestClock.adjust("30 seconds");
+ yield* Deferred.await(spawned[2]!);
+ yield* TestClock.adjust("20 seconds");
+ const snapshot = yield* Fiber.join(published);
+ assert.equal(env.PATH, "/fresh/bin:/usr/bin");
+ assert.isTrue(Option.isSome(snapshot) && snapshot.value.discovered);
+ assert.equal(
+ Option.isSome(snapshot) ? snapshot.value.environment.PATH : undefined,
+ "/fresh/bin:/usr/bin",
+ );
+ return true;
+ }),
+ });
+ }),
+ );
+
it.effect("recovers the login-shell PATH when the first probe outlasts the timeout", () =>
Effect.gen(function* () {
const env: NodeJS.ProcessEnv = { SHELL: "/bin/zsh", PATH: "/usr/bin:/bin:/usr/sbin:/sbin" };
diff --git a/apps/desktop/src/shell/DesktopShellEnvironment.ts b/apps/desktop/src/shell/DesktopShellEnvironment.ts
index 299b0902b57a5..351150aa4b987 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 {
@@ -124,6 +134,20 @@ const LOGIN_SHELL_TIMEOUT = Duration.seconds(5);
const SLOW_LOGIN_SHELL_TIMEOUT = Duration.seconds(20);
const LAUNCHCTL_TIMEOUT = Duration.seconds(2);
const PROCESS_TERMINATE_GRACE = Duration.seconds(1);
+const STARTUP_PROBE: ProbeBudget = {
+ timeout: LOGIN_SHELL_TIMEOUT,
+ slowTimeout: SLOW_LOGIN_SHELL_TIMEOUT,
+ terminateGrace: PROCESS_TERMINATE_GRACE,
+};
+// Retries block nothing, so they outlast pyenv's 60 s wait on its rehash lock, and SIGTERM gets
+// time to run the exit trap that releases it. A SIGKILL leaves the lock for two minutes.
+const RETRY_PROBE: ProbeBudget = {
+ timeout: Duration.minutes(2),
+ terminateGrace: Duration.seconds(10),
+};
+// A Mac asleep at launch fails the first probe on wake, and nothing else would probe again.
+const DISCOVERY_RETRY_DELAY = Duration.seconds(30);
+const DISCOVERY_RETRIES = 10;
const trimNonEmpty = (value: string | null | undefined): Option.Option =>
Option.fromNullishOr(value).pipe(
@@ -131,10 +155,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, "");
@@ -153,39 +179,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(
@@ -265,6 +268,7 @@ const runCommandOutput = Effect.fn("desktop.shellEnvironment.runCommandOutput")(
readonly args: ReadonlyArray;
readonly env: NodeJS.ProcessEnv;
readonly timeout: Duration.Duration;
+ readonly terminateGrace?: Duration.Duration;
readonly shell?: boolean;
}): Effect.fn.Return<
string,
@@ -283,7 +287,7 @@ const runCommandOutput = Effect.fn("desktop.shellEnvironment.runCommandOutput")(
stdout: "pipe",
stderr: "ignore",
killSignal: "SIGTERM",
- forceKillAfter: PROCESS_TERMINATE_GRACE,
+ forceKillAfter: input.terminateGrace ?? PROCESS_TERMINATE_GRACE,
}),
);
return yield* Effect.all([Stream.mkString(Stream.decodeText(child.stdout)), child.exitCode], {
@@ -349,6 +353,7 @@ const readLoginShellEnvironment = (
names: ReadonlyArray,
env: NodeJS.ProcessEnv,
timeout: Duration.Duration,
+ terminateGrace: Duration.Duration,
): Effect.Effect<
EnvironmentPatch,
DesktopShellEnvironmentCommandTimeoutError,
@@ -362,6 +367,7 @@ const readLoginShellEnvironment = (
args: ["-ilc", buildEnvironmentCaptureCommand(shell, names)],
env,
timeout,
+ terminateGrace,
}).pipe(Effect.map((output) => extractEnvironment(output, names)));
const readLaunchctlPath = (env: NodeJS.ProcessEnv) =>
@@ -378,6 +384,7 @@ const readWindowsEnvironment = Effect.fn("desktop.shellEnvironment.readWindowsEn
names: ReadonlyArray,
options: WindowsProbeOptions,
env: NodeJS.ProcessEnv,
+ budget: ProbeBudget,
): Effect.fn.Return {
if (names.length === 0) return {};
@@ -395,7 +402,8 @@ const readWindowsEnvironment = Effect.fn("desktop.shellEnvironment.readWindowsEn
command,
args,
env,
- timeout: LOGIN_SHELL_TIMEOUT,
+ timeout: budget.timeout,
+ terminateGrace: budget.terminateGrace,
}).pipe(orEmptyOnTimeout);
const environment = extractEnvironment(output, names);
if (Object.keys(environment).length > 0) {
@@ -413,8 +421,13 @@ const installWindowsEnvironment = Effect.fn("desktop.shellEnvironment.installWin
): Effect.fn.Return {
const [noProfile, profile] = yield* Effect.all(
[
- readWindowsEnvironment(["PATH"], { loadProfile: false }, config.env),
- readWindowsEnvironment(WINDOWS_PROFILE_ENV_NAMES, { loadProfile: true }, config.env),
+ readWindowsEnvironment(["PATH"], { loadProfile: false }, config.env, config.budget),
+ readWindowsEnvironment(
+ WINDOWS_PROFILE_ENV_NAMES,
+ { loadProfile: true },
+ config.env,
+ config.budget,
+ ),
],
{ concurrency: 2 },
);
@@ -438,6 +451,9 @@ const installWindowsEnvironment = Effect.fn("desktop.shellEnvironment.installWin
},
);
+const listUserShells = (env: NodeJS.ProcessEnv): ReadonlyArray =>
+ [env.SHELL?.trim(), readUserLoginShell()].filter((shell): shell is string => Boolean(shell));
+
const installPosixEnvironment = Effect.fn("desktop.shellEnvironment.installPosixEnvironment")(
function* (
config: ShellEnvironmentConfig,
@@ -448,22 +464,28 @@ const installPosixEnvironment = Effect.fn("desktop.shellEnvironment.installPosix
> {
const fileSystem = yield* FileSystem.FileSystem;
const shellEnvironment: EnvironmentPatch = {};
- const userShells = [config.env.SHELL?.trim(), readUserLoginShell()];
+ const userShells = listUserShells(config.env);
let answeredBy: string | undefined;
let waitedForSlowShell = false;
for (const shell of listLoginShellCandidates(config.platform, config.env.SHELL)) {
const read = (timeout: Duration.Duration) =>
- readLoginShellEnvironment(shell, LOGIN_SHELL_ENV_NAMES, config.env, timeout);
+ readLoginShellEnvironment(
+ shell,
+ LOGIN_SHELL_ENV_NAMES,
+ config.env,
+ timeout,
+ config.budget.terminateGrace,
+ );
Object.assign(
shellEnvironment,
- yield* read(LOGIN_SHELL_TIMEOUT).pipe(
+ yield* read(config.budget.timeout).pipe(
Effect.catchTags({
DesktopShellEnvironmentCommandTimeoutError: (error) => {
- const retry = !waitedForSlowShell;
+ const slowTimeout = waitedForSlowShell ? undefined : config.budget.slowTimeout;
waitedForSlowShell = true;
return logShellEnvironmentCommandError(error).pipe(
- Effect.andThen(retry ? read(SLOW_LOGIN_SHELL_TIMEOUT) : Effect.succeed({})),
+ Effect.andThen(slowTimeout ? read(slowTimeout) : Effect.succeed({})),
);
},
}),
@@ -484,7 +506,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),
]);
@@ -577,7 +599,10 @@ const installPosixEnvironment = Effect.fn("desktop.shellEnvironment.installPosix
}
const prepared = Option.isSome(trimNonEmpty(shellEnvironment.PATH));
- return { prepared, fromUserShell: prepared && userShells.includes(answeredBy) };
+ return {
+ prepared,
+ fromUserShell: prepared && answeredBy !== undefined && userShells.includes(answeredBy),
+ };
},
);
@@ -661,38 +686,60 @@ export const make = Effect.gen(function* () {
yield* Ref.set(latest, Option.some(message));
yield* PubSub.publish(changes, message);
});
- const refresh = Effect.gen(function* () {
- // Refresh from the inherited baseline so removed cached paths and values do not survive.
- const fresh = { ...inherited };
- const discovery = yield* installShellEnvironment({
- env: fresh,
- platform: environment.platform,
- });
- const { prepared } = discovery;
- const patch = Object.fromEntries(
- Object.keys(ShellEnvironmentPatch.fields).map((name) => [name, fresh[name] ?? null]),
- );
- if (prepared || Option.isNone(yield* Ref.get(latest))) yield* publish(patch, prepared);
- if (prepared) {
- const cached = Object.fromEntries(
- CACHED_ENV_NAMES.flatMap((name) => (fresh[name] ? [[name, fresh[name]]] : [])),
- );
- const persist = Effect.gen(function* () {
- const encoded = yield* encodeCache({ version: 1, key, environment: cached });
- yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true });
- yield* fileSystem.writeFileString(cachePath + ".tmp", encoded, { mode: 0o600 });
- yield* fileSystem.rename(cachePath + ".tmp", cachePath);
+ const probe = Effect.fn("desktop.shellEnvironment.refresh")(
+ function* (budget: ProbeBudget) {
+ // Refresh from the inherited baseline so removed cached paths and values do not survive.
+ const fresh = { ...inherited };
+ const discovery = yield* installShellEnvironment({
+ env: fresh,
+ platform: environment.platform,
+ budget,
});
- yield* persist.pipe(
- Effect.catch(() => Effect.logWarning("Could not cache shell environment")),
+ const { prepared } = discovery;
+ const patch = Object.fromEntries(
+ Object.keys(ShellEnvironmentPatch.fields).map((name) => [name, fresh[name] ?? null]),
);
- }
- return discovery;
- }).pipe(
+ if (prepared || Option.isNone(yield* Ref.get(latest))) yield* publish(patch, prepared);
+ if (prepared) {
+ const cached = Object.fromEntries(
+ CACHED_ENV_NAMES.flatMap((name) => (fresh[name] ? [[name, fresh[name]]] : [])),
+ );
+ const persist = Effect.gen(function* () {
+ const encoded = yield* encodeCache({ version: 1, key, environment: cached });
+ yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true });
+ yield* fileSystem.writeFileString(cachePath + ".tmp", encoded, { mode: 0o600 });
+ yield* fileSystem.rename(cachePath + ".tmp", cachePath);
+ });
+ yield* persist.pipe(
+ Effect.catch(() => Effect.logWarning("Could not cache shell environment")),
+ );
+ }
+ return discovery;
+ },
Effect.provideService(FileSystem.FileSystem, fileSystem),
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
- Effect.withSpan("desktop.shellEnvironment.refresh"),
+ );
+ // A fallback shell's PATH can miss folders the user's own shell adds, so keep asking that shell.
+ const awaitsUserShell = listUserShells(inherited).length > 0;
+ const settled = ({ prepared, fromUserShell }: ShellDiscovery) =>
+ fromUserShell || (prepared && !awaitsUserShell);
+ const refresh = probe(STARTUP_PROBE).pipe(
Effect.onExit((exit) => Deferred.done(discovered, exit)),
+ Effect.flatMap((discovery) =>
+ settled(discovery)
+ ? Effect.void
+ : Effect.sleep(DISCOVERY_RETRY_DELAY).pipe(
+ Effect.andThen(
+ probe(RETRY_PROBE).pipe(
+ Effect.repeat({
+ until: settled,
+ schedule: Schedule.spaced(DISCOVERY_RETRY_DELAY),
+ times: DISCOVERY_RETRIES - 1,
+ }),
+ ),
+ ),
+ ),
+ ),
);
const installIntoProcess = yield* Effect.cached(
Effect.gen(function* () {
diff --git a/apps/desktop/src/updates/DesktopRemoteUpdates.test.ts b/apps/desktop/src/updates/DesktopRemoteUpdates.test.ts
index 1f5321148b77b..5cdf2ba1b56dc 100644
--- a/apps/desktop/src/updates/DesktopRemoteUpdates.test.ts
+++ b/apps/desktop/src/updates/DesktopRemoteUpdates.test.ts
@@ -102,6 +102,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",
@@ -119,6 +142,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);
+ }),
+ );
+ });
+
it.effect("switches to the requested track before preparing its release", () => {
// In-memory settings keep the channel write off real disk I/O.
const harness = makeHarness({ beforeSetUpdateChannel: Effect.void });
@@ -667,16 +733,15 @@ describe("DesktopRemoteUpdates", () => {
it.effect("waits for a background check before installing a prepared update", () => {
const backgroundCheckStarted = Deferred.makeUnsafe();
const releaseBackgroundCheck = Deferred.makeUnsafe();
- let checks = 0;
+ let blockCheck = false;
const harness = makeHarness({
- checkForUpdates: Effect.suspend(() => {
- checks += 1;
- return checks === 2
+ checkForUpdates: Effect.suspend(() =>
+ blockCheck
? Deferred.succeed(backgroundCheckStarted, undefined).pipe(
Effect.andThen(Deferred.await(releaseBackgroundCheck)),
)
- : Effect.void;
- }),
+ : Effect.void,
+ ),
});
return runRemoteUpdatesTest(harness, ({ requests, commits }) =>
@@ -689,9 +754,10 @@ describe("DesktopRemoteUpdates", () => {
harness.emit("update-downloaded", { version: "1.2.4" });
yield* settle;
+ blockCheck = true;
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,
@@ -701,7 +767,6 @@ describe("DesktopRemoteUpdates", () => {
yield* settle;
assert.equal(harness.quitAndInstalls(), 0);
- harness.emit("update-downloaded", { version: "1.2.4" });
yield* Deferred.succeed(releaseBackgroundCheck, undefined);
yield* Fiber.join(backgroundCheck);
yield* settle;
diff --git a/apps/desktop/src/updates/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 7ee2ff5dd51c1..33ed00a764738 100644
--- a/apps/desktop/src/updates/DesktopUpdates.test.ts
+++ b/apps/desktop/src/updates/DesktopUpdates.test.ts
@@ -1,7 +1,7 @@
import * as NodeModule from "node:module";
import { assert, describe, it } from "@effect/vitest";
-import { DESKTOP_UPDATE_RESTART_MARKER_FILE } from "@t3tools/contracts";
+import { DESKTOP_UPDATE_RESTART_MARKER_FILE, DesktopUpdateStateSchema } from "@t3tools/contracts";
import { computeReleaseNotes } from "electron-updater/out/providers/GitHubProvider.js";
import * as Cause from "effect/Cause";
import * as Deferred from "effect/Deferred";
@@ -13,6 +13,7 @@ import * as Logger from "effect/Logger";
import * as Option from "effect/Option";
import * as References from "effect/References";
import * as Ref from "effect/Ref";
+import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import * as TestClock from "effect/testing/TestClock";
@@ -25,6 +26,8 @@ import * as DesktopUpdatePolicy from "./DesktopUpdatePolicy.ts";
import * as DesktopUpdates from "./DesktopUpdates.ts";
import { flushCallbacks, makeHarness } from "./updatesTestHarness.ts";
+const encodeUpdateState = Schema.encodeEffect(DesktopUpdateStateSchema);
+
type ReleaseFeed = Parameters[2];
type RunningVersion = Parameters[0];
@@ -125,7 +128,7 @@ describe("DesktopUpdates", () => {
).pipe(Effect.provide(harness.layer));
});
- it.effect("checks for newer releases after an update has been downloaded", () => {
+ it.effect("re-checks an offered update without announcing it again", () => {
const harness = makeHarness();
return Effect.scoped(
@@ -138,14 +141,23 @@ describe("DesktopUpdates", () => {
releaseNotes: "## What's changed\n- fix: queued update",
});
yield* flushCallbacks;
+ const offeredStates = harness.sentStates.length;
+
+ yield* updates.check("poll");
+ harness.emit("update-available", { version: "1.2.4" });
+ yield* flushCallbacks;
+ assert.equal(harness.sentStates.length, offeredStates);
+
harness.emit("update-downloaded", { version: "1.2.4" });
yield* flushCallbacks;
+ const downloadedStates = harness.sentStates.length;
const result = yield* updates.check("poll");
assert.isTrue(result.checked);
harness.emit("update-available", { version: "1.2.4" });
yield* flushCallbacks;
+ assert.equal(harness.sentStates.length, downloadedStates);
const unchangedState = yield* updates.getState;
assert.equal(unchangedState.status, "downloaded");
@@ -267,15 +279,26 @@ describe("DesktopUpdates", () => {
).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
});
- it.effect(
- "rejects install while a refresh check is in progress and releases the reservation",
- () =>
+ it.effect.each([
+ { action: "download", offer: "update-available", found: null, accepted: true },
+ { action: "install", offer: "update-downloaded", found: null, accepted: true },
+ { action: "download", offer: "update-available", found: "1.2.5", accepted: true },
+ { action: "install", offer: "update-downloaded", found: "1.2.5", accepted: false },
+ ] as const)(
+ "a $action waiting out a refresh check acts on what it found ($found)",
+ ({ action, offer, found, accepted }) =>
Effect.gen(function* () {
const checkStarted = yield* Deferred.make();
const releaseCheck = yield* Deferred.make();
const harness = makeHarness({
checkForUpdates: Deferred.succeed(checkStarted, undefined).pipe(
Effect.andThen(Deferred.await(releaseCheck)),
+ // electron-updater emits the check's outcome before its promise resolves.
+ Effect.andThen(
+ Effect.sync(() => {
+ if (found !== null) harness.emit("update-available", { version: found });
+ }),
+ ),
),
});
@@ -283,22 +306,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)));
}),
@@ -323,10 +344,11 @@ describe("DesktopUpdates", () => {
const installFiber = yield* updates.install.pipe(Effect.forkScoped);
yield* Deferred.await(installStarted);
+ const checksBefore = harness.checkCount();
const checkResult = yield* updates.check("manual");
assert.isFalse(checkResult.checked);
- assert.equal(harness.checkCount(), 0);
+ assert.equal(harness.checkCount(), checksBefore);
yield* Deferred.succeed(releaseInstall, undefined);
const installResult = yield* Fiber.join(installFiber);
@@ -337,7 +359,9 @@ describe("DesktopUpdates", () => {
);
it.effect("preserves a queued installer after a background updater error", () => {
- const harness = makeHarness();
+ const harness = makeHarness({
+ checkForUpdates: Effect.sync(() => harness.emit("update-not-available")),
+ });
return Effect.scoped(
Effect.gen(function* () {
@@ -473,6 +497,145 @@ describe("DesktopUpdates", () => {
).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
});
+ it.effect("downloads the newest release published since the last check", () => {
+ // electron-updater downloads the release its last checkForUpdates found.
+ let published = "1.2.4";
+ let lastChecked: string | undefined;
+ const harness = makeHarness({
+ checkForUpdates: Effect.sync(() => {
+ lastChecked = published;
+ harness.emit("update-available", { version: published });
+ }),
+ downloadUpdate: Effect.sync(() => {
+ harness.emit("update-downloaded", { version: lastChecked });
+ }),
+ });
+
+ return Effect.scoped(
+ Effect.gen(function* () {
+ const updates = yield* DesktopUpdates.DesktopUpdates;
+ yield* updates.configure;
+ yield* updates.check("poll");
+ yield* flushCallbacks;
+ assert.equal((yield* updates.getState).availableVersion, "1.2.4");
+
+ published = "1.2.5";
+ const result = yield* updates.download;
+ yield* flushCallbacks;
+ assert.isTrue(result.completed);
+ assert.equal((yield* updates.getState).downloadedVersion, "1.2.5");
+ }),
+ ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
+ });
+
+ it.effect("installs a release published after the retained download", () => {
+ let published = "1.2.4";
+ let lastChecked: string | undefined;
+ let installedVersion: string | null | undefined;
+ const harness = makeHarness({
+ checkForUpdates: Effect.sync(() => {
+ lastChecked = published;
+ harness.emit("update-available", { version: published });
+ }),
+ downloadUpdate: Effect.sync(() => {
+ harness.emit("update-downloaded", { version: lastChecked });
+ }),
+ quitAndInstall: Effect.sync(() => {
+ installedVersion = harness.sentStates.at(-1)?.downloadedVersion;
+ }),
+ });
+
+ return Effect.scoped(
+ Effect.gen(function* () {
+ const updates = yield* DesktopUpdates.DesktopUpdates;
+ yield* updates.configure;
+ yield* updates.check("poll");
+ yield* flushCallbacks;
+ yield* updates.download;
+ yield* flushCallbacks;
+ assert.equal((yield* updates.getState).downloadedVersion, "1.2.4");
+
+ published = "1.2.5";
+ const checksBefore = harness.checkCount();
+ const result = yield* updates.installPrepared("1.2.4");
+ assert.isTrue(result.accepted);
+ // A second check before downloading could find a stale feed's older release.
+ assert.equal(harness.checkCount(), checksBefore + 1);
+ assert.equal(harness.quitAndInstalls(), 1);
+ assert.equal(installedVersion, "1.2.5");
+ }),
+ ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
+ });
+
+ it.effect("downloads the known offer when the check before downloading fails", () => {
+ let checks = 0;
+ const harness = makeHarness({
+ checkForUpdates: Effect.suspend(() => {
+ checks += 1;
+ if (checks > 1) {
+ return Effect.fail(
+ new ElectronUpdater.ElectronUpdaterCheckForUpdatesError({
+ channel: null,
+ cause: new Error("offline"),
+ }),
+ );
+ }
+ harness.emit("update-available", { version: "1.2.4" });
+ return Effect.void;
+ }),
+ downloadUpdate: Effect.sync(() => {
+ harness.emit("update-downloaded", { version: "1.2.4" });
+ }),
+ });
+
+ return Effect.scoped(
+ Effect.gen(function* () {
+ const updates = yield* DesktopUpdates.DesktopUpdates;
+ yield* updates.configure;
+ yield* updates.check("poll");
+ yield* flushCallbacks;
+
+ const result = yield* updates.download;
+ yield* flushCallbacks;
+ assert.isTrue(result.completed);
+ assert.equal((yield* updates.getState).downloadedVersion, "1.2.4");
+ // Remote requests treat a published error after their own check as final.
+ assert.notInclude(
+ harness.sentStates.map((state) => state.status),
+ "error",
+ );
+ }),
+ ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
+ });
+
+ it.effect("installs the retained download when a stale feed offers an older release", () => {
+ let published = "1.2.5";
+ let installedVersion: string | null | undefined;
+ const harness = makeHarness({
+ checkForUpdates: Effect.sync(() => harness.emit("update-available", { version: published })),
+ downloadUpdate: Effect.sync(() => harness.emit("update-downloaded", { version: "1.2.5" })),
+ quitAndInstall: Effect.sync(() => {
+ installedVersion = harness.sentStates.at(-1)?.downloadedVersion;
+ }),
+ });
+
+ return Effect.scoped(
+ Effect.gen(function* () {
+ const updates = yield* DesktopUpdates.DesktopUpdates;
+ yield* updates.configure;
+ yield* updates.check("poll");
+ yield* updates.download;
+ yield* flushCallbacks;
+
+ published = "1.2.4";
+ const result = yield* updates.installPrepared("1.2.5");
+ assert.isTrue(result.accepted);
+ assert.equal(harness.downloadCount(), 1);
+ assert.equal(installedVersion, "1.2.5");
+ }),
+ ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
+ });
+
it.effect("restores download state and permits retry after interruption", () =>
Effect.gen(function* () {
const actionStarted = yield* Deferred.make();
@@ -1262,6 +1425,7 @@ describe("DesktopUpdates under a managed policy", () => {
assert.equal(held.status, "disabled");
assert.include(held.message ?? "", message);
assert.isTrue(held.channelBlockedByPolicy);
+ assert.isTrue((yield* encodeUpdateState(held)).channelBlockedByPolicy);
assert.isFalse((yield* updates.check("menu")).checked);
assert.equal(harness.checkCount(), 0);
diff --git a/apps/desktop/src/updates/DesktopUpdates.ts b/apps/desktop/src/updates/DesktopUpdates.ts
index db31e0bc112ba..775a9ff6b04ff 100644
--- a/apps/desktop/src/updates/DesktopUpdates.ts
+++ b/apps/desktop/src/updates/DesktopUpdates.ts
@@ -63,7 +63,7 @@ const CHANNEL_CHANGE_RETRY_DELAY = Duration.seconds(1);
const CHANNEL_CHANGE_RETRIES = 30;
const AUTO_UPDATE_STARTUP_DELAY = "15 seconds";
const AUTO_UPDATE_POLL_INTERVAL = "4 hours";
-const PREPARED_INSTALL_CHECK_WAIT = Duration.seconds(90);
+const UPDATE_CHECK_WAIT = Duration.seconds(90);
type UpdateAction = "check" | "download" | "install" | "install-recovery" | "channel";
@@ -318,6 +318,10 @@ function getCanRetryFromState(state: DesktopUpdateState): boolean {
return state.availableVersion !== null || state.downloadedVersion !== null;
}
+function isOffered(state: DesktopUpdateState): boolean {
+ return state.status === "available" || state.status === "downloaded";
+}
+
function shouldBroadcastDownloadProgress(
currentState: DesktopUpdateState,
nextPercent: number,
@@ -518,6 +522,23 @@ export const make = Effect.gen(function* () {
),
);
+ // Re-runs admit after each finished action, so a caller waiting on a check decides on its result.
+ const admitAfterCheck = Effect.fn("desktop.updates.admitAfterCheck")(function* (
+ admit: Effect.Effect<"admitted" | "refused" | "wait-for-check">,
+ ) {
+ const actionCompletions = yield* PubSub.subscribe(finishedUpdateActions);
+ let admission = yield* stateMutex.withPermits(1)(admit);
+ while (admission === "wait-for-check") {
+ const finishedAction = yield* PubSub.take(actionCompletions).pipe(
+ Effect.timeoutOption(UPDATE_CHECK_WAIT),
+ );
+ admission = Option.isNone(finishedAction)
+ ? "refused"
+ : yield* stateMutex.withPermits(1)(admit);
+ }
+ return admission;
+ });
+
const applyAutoUpdaterChannel = Effect.fn("desktop.updates.applyAutoUpdaterChannel")(function* (
channel: DesktopUpdateChannel,
) {
@@ -536,6 +557,17 @@ export const make = Effect.gen(function* () {
});
});
+ // The flag is shared updater state, so callers flip it only while holding a reservation.
+ const runUpdaterCheck = Effect.fn("desktop.updates.runUpdaterCheck")(function* (
+ allowDowngrade: boolean,
+ ) {
+ const restoreDowngrade = yield* electronUpdater.allowDowngrade;
+ if (allowDowngrade) yield* electronUpdater.setAllowDowngrade(true);
+ return yield* electronUpdater.checkForUpdates.pipe(
+ Effect.ensuring(electronUpdater.setAllowDowngrade(restoreDowngrade).pipe(Effect.ignore)),
+ );
+ });
+
const checkForUpdates = Effect.fn("desktop.updates.checkForUpdates")(function* (
reason: string,
actionReservation: "acquire" | "held" = "acquire",
@@ -559,15 +591,13 @@ 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.
- const restoreDowngrade = yield* electronUpdater.allowDowngrade;
- if (allowDowngrade) yield* electronUpdater.setAllowDowngrade(true);
- return yield* electronUpdater.checkForUpdates.pipe(
- Effect.ensuring(electronUpdater.setAllowDowngrade(restoreDowngrade).pipe(Effect.ignore)),
+ return yield* runUpdaterCheck(allowDowngrade).pipe(
Effect.as(true),
Effect.catchTags({
ElectronUpdaterCheckForUpdatesError: Effect.fn(
@@ -596,17 +626,56 @@ 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"))) {
+ // Install refreshes before downloading, and a second check could pick a stale, older release.
+ const downloadAvailableUpdate = Effect.fn("desktop.updates.downloadAvailableUpdate")(function* (
+ refresh: boolean,
+ ) {
+ 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 offered = yield* Ref.get(updateStateRef);
+ let state = offered;
return yield* Effect.gen(function* () {
+ if (refresh) {
+ // electron-updater downloads what its last check found, which can be hours old.
+ yield* logUpdaterInfo("checking for updates", { reason: "download" });
+ yield* runUpdaterCheck(
+ offered.channel !== desktopUpdateChannelOf(environment.appVersion),
+ ).pipe(
+ // A failed check keeps electron-updater's earlier result, so the known offer still downloads.
+ Effect.catchTags({
+ ElectronUpdaterCheckForUpdatesError: (error) =>
+ logUpdaterWarning(error.message, {
+ errorTag: error._tag,
+ cause: describeUpdateErrorCause(error.cause),
+ }),
+ }),
+ );
+ }
+ state = yield* Ref.get(updateStateRef);
+ if (state.status !== "available") {
+ return { accepted: true, completed: false };
+ }
yield* setState(reduceDesktopUpdateStateOnDownloadStart(state));
yield* electronUpdater.setDisableDifferentialDownload(
isArm64HostRunningIntelBuild(environment.runtimeInfo),
@@ -655,7 +724,7 @@ export const make = Effect.gen(function* () {
}),
Effect.ensuring(finishUpdateAction("download")),
);
- }).pipe(Effect.withSpan("desktop.updates.downloadAvailableUpdate"));
+ });
const updateRestartMarkerDir = environment.path.join(environment.baseDir, "runtime");
const updateRestartMarkerPath = environment.path.join(
@@ -798,47 +867,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 };
}
@@ -922,7 +979,42 @@ export const make = Effect.gen(function* () {
state: yield* Ref.get(updateStateRef),
};
}
- const result = yield* installDownloadedUpdate(expectedVersion);
+ let installVersion = expectedVersion;
+ // A download can be hours old: a release published since replaces it before restarting.
+ const retained = yield* Ref.get(updateStateRef);
+ if (
+ retained.downloadedVersion !== null &&
+ (expectedVersion === undefined || retained.downloadedVersion === expectedVersion) &&
+ (yield* checkForUpdates(
+ "install",
+ "acquire",
+ retained.channel !== desktopUpdateChannelOf(environment.appVersion),
+ )) &&
+ (yield* Ref.get(updateStateRef)).status === "available"
+ ) {
+ const refreshed = yield* Ref.get(updateStateRef);
+ // electron-updater compares a stale feed with the running build, not the retained download.
+ if (
+ refreshed.availableVersion === null ||
+ compareSemverVersions(refreshed.availableVersion, retained.downloadedVersion) <= 0
+ ) {
+ yield* setState(retained);
+ } else {
+ const download = yield* downloadAvailableUpdate(false);
+ if (!download.completed) {
+ return {
+ accepted: download.accepted,
+ completed: false,
+ failed: download.accepted,
+ state: yield* Ref.get(updateStateRef),
+ };
+ }
+ if (expectedVersion !== undefined) {
+ installVersion = (yield* Ref.get(updateStateRef)).downloadedVersion ?? expectedVersion;
+ }
+ }
+ }
+ const result = yield* installDownloadedUpdate(installVersion);
return {
accepted: result.accepted,
completed: result.completed,
@@ -982,6 +1074,7 @@ export const make = Effect.gen(function* () {
yield* Ref.set(lastLoggedDownloadMilestoneRef, -1);
return;
}
+ if (isOffered(state) && state.availableVersion === info.version) return;
const checkedAt = yield* currentIsoTimestamp;
const { releaseNotes, omittedReleaseCount } = normalizeDesktopUpdateReleaseNotes(
@@ -1161,6 +1254,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);
};
@@ -1328,7 +1423,7 @@ export const make = Effect.gen(function* () {
};
}),
download: Effect.gen(function* () {
- const result = yield* downloadAvailableUpdate;
+ const result = yield* downloadAvailableUpdate(true);
return {
accepted: result.accepted,
completed: result.completed,
diff --git a/apps/desktop/src/window/DesktopApplicationMenu.test.ts b/apps/desktop/src/window/DesktopApplicationMenu.test.ts
index 612ec441ba99b..46004ca302295 100644
--- a/apps/desktop/src/window/DesktopApplicationMenu.test.ts
+++ b/apps/desktop/src/window/DesktopApplicationMenu.test.ts
@@ -3,7 +3,9 @@ import { assert, describe, it } from "@effect/vitest";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
+import * as Option from "effect/Option";
+import type { DesktopUpdateCheckResult, DesktopUpdateState } from "@t3tools/contracts";
import * as Electron from "electron";
import { vi } from "vite-plus/test";
@@ -18,6 +20,7 @@ import * as DesktopApplicationMenu from "./DesktopApplicationMenu.ts";
import * as DesktopConfig from "../app/DesktopConfig.ts";
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
import * as DesktopUpdates from "../updates/DesktopUpdates.ts";
+import { createInitialDesktopUpdateState } from "../updates/updateMachine.ts";
import * as DesktopWindow from "./DesktopWindow.ts";
const environmentInput = {
@@ -56,27 +59,37 @@ const layerElectronApp = Layer.succeed(ElectronApp.ElectronApp, {
on: () => Effect.void,
} satisfies ElectronApp.ElectronApp["Service"]);
-const layerElectronDialog = Layer.succeed(ElectronDialog.ElectronDialog, {
- pickFolder: () => Effect.succeedNone,
- pickFiles: () => Effect.succeed([]),
- showMessageBox: () => Effect.succeed({ response: 0, checkboxChecked: false }),
- showErrorBox: () => Effect.void,
-} satisfies ElectronDialog.ElectronDialog["Service"]);
-
-const layerDesktopUpdates = Layer.succeed(DesktopUpdates.DesktopUpdates, {
- getState: Effect.die("unexpected getState"),
- isActionActive: Effect.succeed(false),
- isInstallActive: Effect.succeed(false),
- subscribe: Effect.die("unexpected subscribe"),
- emitState: Effect.void,
- disabledReason: Effect.succeedNone,
- configure: Effect.void,
- setChannel: () => Effect.die("unexpected setChannel"),
- check: () => Effect.die("unexpected check"),
- download: Effect.die("unexpected download"),
- install: Effect.die("unexpected install"),
- installPrepared: () => Effect.die("unexpected installPrepared"),
-} satisfies DesktopUpdates.DesktopUpdates["Service"]);
+interface MenuServices {
+ readonly checkResult?: DesktopUpdateCheckResult;
+ readonly shownMessageBox?: Deferred.Deferred;
+}
+
+const layerElectronDialog = ({ shownMessageBox }: MenuServices) =>
+ Layer.succeed(ElectronDialog.ElectronDialog, {
+ pickFolder: () => Effect.succeedNone,
+ pickFiles: () => Effect.succeed([]),
+ showMessageBox: (options) =>
+ (shownMessageBox ? Deferred.succeed(shownMessageBox, options) : Effect.void).pipe(
+ Effect.as({ response: options.cancelId ?? 0, checkboxChecked: false }),
+ ),
+ showErrorBox: () => Effect.void,
+ } satisfies ElectronDialog.ElectronDialog["Service"]);
+
+const layerDesktopUpdates = ({ checkResult }: MenuServices) =>
+ Layer.succeed(DesktopUpdates.DesktopUpdates, {
+ getState: Effect.die("unexpected getState"),
+ isActionActive: Effect.succeed(false),
+ isInstallActive: Effect.succeed(false),
+ subscribe: Effect.die("unexpected subscribe"),
+ emitState: Effect.void,
+ disabledReason: Effect.succeedNone,
+ configure: Effect.void,
+ setChannel: () => Effect.die("unexpected setChannel"),
+ check: () => (checkResult ? Effect.succeed(checkResult) : Effect.die("unexpected check")),
+ download: Effect.die("unexpected download"),
+ install: Effect.die("unexpected install"),
+ installPrepared: () => Effect.die("unexpected installPrepared"),
+ } satisfies DesktopUpdates.DesktopUpdates["Service"]);
const layerDesktopWindow = (selectedAction: Deferred.Deferred) =>
Layer.succeed(DesktopWindow.DesktopWindow, {
@@ -113,6 +126,7 @@ const configureMenu = (
selectedAction: Deferred.Deferred,
applicationMenuTemplate: Deferred.Deferred,
environment: Partial = {},
+ services: MenuServices = {},
) =>
Effect.gen(function* () {
const menu = yield* DesktopApplicationMenu.DesktopApplicationMenu;
@@ -122,8 +136,8 @@ const configureMenu = (
DesktopApplicationMenu.layer.pipe(
Layer.provideMerge(layerElectronMenu(applicationMenuTemplate)),
Layer.provideMerge(layerDesktopWindow(selectedAction)),
- Layer.provideMerge(layerDesktopUpdates),
- Layer.provideMerge(layerElectronDialog),
+ Layer.provideMerge(layerDesktopUpdates(services)),
+ Layer.provideMerge(layerElectronDialog(services)),
Layer.provideMerge(layerElectronApp),
Layer.provideMerge(
DesktopEnvironment.layer({ ...environmentInput, ...environment }).pipe(
@@ -134,6 +148,54 @@ const configureMenu = (
),
);
+const checkForUpdatesFromMacMenu = (state: Partial) =>
+ Effect.gen(function* () {
+ const applicationMenuTemplate =
+ yield* Deferred.make();
+ const shownMessageBox = yield* Deferred.make();
+ yield* configureMenu(
+ yield* Deferred.make(),
+ applicationMenuTemplate,
+ { platform: "darwin" },
+ {
+ checkResult: {
+ checked: true,
+ state: {
+ ...createInitialDesktopUpdateState(
+ "0.1.5",
+ { hostArch: "arm64", appArch: "arm64", runningUnderArm64Translation: false },
+ "latest",
+ ),
+ enabled: true,
+ ...state,
+ },
+ },
+ shownMessageBox,
+ },
+ );
+
+ const appMenu = (yield* Deferred.await(applicationMenuTemplate))[0];
+ if (!Array.isArray(appMenu?.submenu)) {
+ throw new Error("Expected the macOS app menu submenu to be an array.");
+ }
+ const checkForUpdates = appMenu.submenu.find((item) => item.label === "Check for Updates...");
+ if (typeof checkForUpdates?.click !== "function") {
+ throw new Error("Expected Check for Updates... menu item to have a click handler.");
+ }
+
+ // Every stub completes synchronously, so the menu action has finished when click returns.
+ checkForUpdates.click(
+ {} as Electron.MenuItem,
+ {} as Electron.BrowserWindow,
+ {} as KeyboardEvent,
+ );
+ const dialog = yield* Deferred.poll(shownMessageBox);
+ if (Option.isNone(dialog)) {
+ throw new Error("Check for Updates... finished without showing any dialog.");
+ }
+ return yield* dialog.value;
+ });
+
describe("DesktopApplicationMenu", () => {
it.effect("leaves the accelerator to Chromium instead of injecting a paste", () =>
Effect.gen(function* () {
@@ -285,4 +347,25 @@ describe("DesktopApplicationMenu", () => {
assert.equal(yield* Deferred.await(selectedAction), "main-reload");
}),
);
+ it.effect("tells the user which update the menu check found", () =>
+ Effect.gen(function* () {
+ const dialog = yield* checkForUpdatesFromMacMenu({
+ status: "available",
+ availableVersion: "0.1.7",
+ });
+ assert.include(`${dialog.title ?? ""} ${dialog.message} ${dialog.detail ?? ""}`, "0.1.7");
+ }),
+ );
+
+ it.effect("tells the user a downloaded update is ready when the menu check runs", () =>
+ Effect.gen(function* () {
+ const dialog = yield* checkForUpdatesFromMacMenu({
+ status: "downloaded",
+ availableVersion: "0.1.7",
+ downloadedVersion: "0.1.7",
+ downloadPercent: 100,
+ });
+ assert.include(`${dialog.title ?? ""} ${dialog.message} ${dialog.detail ?? ""}`, "0.1.7");
+ }),
+ );
});
diff --git a/apps/desktop/src/window/DesktopApplicationMenu.ts b/apps/desktop/src/window/DesktopApplicationMenu.ts
index 44d2c234f8358..b4025ebfde8ef 100644
--- a/apps/desktop/src/window/DesktopApplicationMenu.ts
+++ b/apps/desktop/src/window/DesktopApplicationMenu.ts
@@ -64,6 +64,9 @@ const runMainContentsCommand = Effect.fn("desktop.menu.runMainContentsCommand")(
yield* desktopWindow.runMainContentsCommand(command);
});
+const describeUpdate = (version: string | null) =>
+ version === null ? "A new version of T3 Code" : `T3 Code ${version}`;
+
const checkForUpdatesFromMenu = Effect.gen(function* () {
const updates = yield* DesktopUpdates.DesktopUpdates;
const electronDialog = yield* ElectronDialog.ElectronDialog;
@@ -77,6 +80,35 @@ const checkForUpdatesFromMenu = Effect.gen(function* () {
message: `T3 Code ${updateState.currentVersion} is currently the newest version available.`,
buttons: ["OK"],
});
+ } else if (updateState.status === "available") {
+ const { response } = yield* electronDialog.showMessageBox({
+ type: "info",
+ title: "Update available",
+ message: `${describeUpdate(updateState.availableVersion)} is available.`,
+ detail: `You're running T3 Code ${updateState.currentVersion}.`,
+ buttons: ["Download", "Later"],
+ defaultId: 0,
+ cancelId: 1,
+ });
+ if (response === 0) yield* updates.download;
+ } else if (updateState.status === "downloading") {
+ yield* electronDialog.showMessageBox({
+ type: "info",
+ title: "Update downloading",
+ message: `${describeUpdate(updateState.availableVersion)} is already downloading.`,
+ buttons: ["OK"],
+ });
+ } else if (updateState.status === "downloaded") {
+ const { response } = yield* electronDialog.showMessageBox({
+ type: "info",
+ title: "Update ready",
+ message: `${describeUpdate(updateState.downloadedVersion ?? updateState.availableVersion)} is ready to install.`,
+ detail: "T3 Code will restart to install it. Any running tasks will be interrupted.",
+ buttons: ["Restart", "Later"],
+ defaultId: 0,
+ cancelId: 1,
+ });
+ if (response === 0) yield* updates.install;
} else if (updateState.status === "error") {
yield* electronDialog.showMessageBox({
type: "warning",
diff --git a/apps/desktop/src/window/DesktopWindow.test.ts b/apps/desktop/src/window/DesktopWindow.test.ts
index 497b315ef5225..46311dbba8122 100644
--- a/apps/desktop/src/window/DesktopWindow.test.ts
+++ b/apps/desktop/src/window/DesktopWindow.test.ts
@@ -207,17 +207,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,
@@ -243,6 +246,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;
}) {
@@ -291,7 +300,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)
@@ -302,7 +313,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(
@@ -314,7 +332,9 @@ function layerTest(input: {
recordMetrics: () => Effect.void,
shutdown: Effect.void,
}),
- layerDesktopEnvironment,
+ input.platform === undefined
+ ? layerDesktopEnvironment
+ : layerDesktopEnvironmentFor(input.platform),
layerDesktopAppSettings,
layerDesktopClientSettings,
layerDesktopServerExposure,
@@ -423,7 +443,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(
@@ -826,7 +847,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();
@@ -846,7 +867,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);
@@ -857,6 +881,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();
@@ -1170,6 +1226,68 @@ describe("DesktopWindow", () => {
}),
);
+ it.effect(
+ "brings the window back after the renderer dies more often than the reload budget",
+ () =>
+ Effect.gen(function* () {
+ const fakeWindow = makeFakeBrowserWindow();
+ const createCount = yield* Ref.make(0);
+ const mainWindow = yield* Ref.make>(Option.none());
+ const layer = layerTest({ window: fakeWindow.window, createCount, mainWindow });
+
+ yield* Effect.gen(function* () {
+ const desktopWindow = yield* DesktopWindow.DesktopWindow;
+ yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
+
+ const renderProcessGone = fakeWindow.webContentsListeners.get("render-process-gone");
+ if (!renderProcessGone) {
+ return yield* Effect.die("render-process-gone listener was not registered");
+ }
+ for (let crash = 1; crash <= 4; crash++) {
+ const loadsBefore = fakeWindow.loadURL.mock.calls.length;
+ renderProcessGone({}, { reason: "oom", exitCode: -536870904 });
+ yield* TestClock.adjust(crash < 4 ? 1_000 : 60_000);
+ yield* Effect.promise(() => Promise.resolve());
+ assert.isAbove(
+ fakeWindow.loadURL.mock.calls.length,
+ loadsBefore,
+ `window shows nothing after renderer crash ${crash}`,
+ );
+ }
+ }).pipe(Effect.provide(layer));
+ }),
+ );
+
+ 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 43404e2d6cfb9..4628be44d5ce1 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,
@@ -942,20 +942,33 @@ export const make = Effect.gen(function* () {
rendererRecoveryTimestamps = rendererRecoveryTimestamps.filter(
(timestamp) => now - timestamp < RENDERER_RECOVERY_WINDOW_MS,
);
- const shouldRecover =
- recoverable &&
- !window.isDestroyed() &&
- rendererRecoveryTimestamps.length < RENDERER_RECOVERY_MAX_ATTEMPTS;
+ const shouldRecover = recoverable && !window.isDestroyed();
+ // Past the budget, wait for the oldest attempt to leave the window instead of
+ // giving up, so a crash loop backs off but never leaves the window blank.
+ const oldestAttempt =
+ rendererRecoveryTimestamps.length >= RENDERER_RECOVERY_MAX_ATTEMPTS
+ ? rendererRecoveryTimestamps[
+ rendererRecoveryTimestamps.length - RENDERER_RECOVERY_MAX_ATTEMPTS
+ ]
+ : undefined;
+ const reloadInMs =
+ oldestAttempt === undefined
+ ? RENDERER_RECOVERY_RELOAD_DELAY_MS
+ : Math.max(
+ RENDERER_RECOVERY_RELOAD_DELAY_MS,
+ oldestAttempt + RENDERER_RECOVERY_WINDOW_MS - now,
+ );
yield* logWindowWarning("main window render process gone", {
reason: details.reason,
exitCode: details.exitCode,
recovering: shouldRecover,
+ ...(shouldRecover ? { reloadInMs } : {}),
});
if (!shouldRecover) {
return;
}
- rendererRecoveryTimestamps.push(now);
- yield* Effect.sleep(RENDERER_RECOVERY_RELOAD_DELAY_MS);
+ rendererRecoveryTimestamps.push(now + reloadInMs);
+ yield* Effect.sleep(reloadInMs);
if (!window.isDestroyed()) {
loadApplication();
}
@@ -1018,7 +1031,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 +1118,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 +1216,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 0787956a72b76..7f4a2507a736e 100644
--- a/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts
+++ b/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts
@@ -172,7 +172,7 @@ describe.skipIf(posixShellRunner === null)("WSL runtime install script (executed
" }",
' eval "$2"',
"); }",
- buildWslRuntimeProbeScript(fixture.runtimeRoot),
+ buildWslRuntimeProbeScript(),
].join("\n"),
);
@@ -207,7 +207,7 @@ describe.skipIf(posixShellRunner === null)("WSL runtime install script (executed
[
"bash() { return 127; }",
'export PATH="/fixture/bin:/usr/bin:/bin"',
- buildWslRuntimeProbeScript(fixture.runtimeRoot),
+ buildWslRuntimeProbeScript(),
].join("\n"),
);
diff --git a/apps/desktop/src/wsl/DesktopWslEnvironment.ts b/apps/desktop/src/wsl/DesktopWslEnvironment.ts
index 4e5e5b423f20e..5ba7d3794fad1 100644
--- a/apps/desktop/src/wsl/DesktopWslEnvironment.ts
+++ b/apps/desktop/src/wsl/DesktopWslEnvironment.ts
@@ -110,10 +110,7 @@ export class DesktopWslEnvironment extends Context.Service<
) => Effect.Effect;
readonly pruneRuntimes: (distro: string | null, runtimeId: string) => Effect.Effect;
readonly invalidateRuntime: (distro: string | null, runtimeId: string) => Effect.Effect;
- readonly probeRuntime: (
- distro: string | null,
- linuxAppRoot: string,
- ) => Effect.Effect;
+ readonly probeRuntime: (distro: string | null) => Effect.Effect;
readonly ensureNodePty: (
distro: string | null,
linuxAppRoot: string,
@@ -483,11 +480,9 @@ require("node-pty");
NODE`;
// Resolve version-managed Node for providers without making runtime readiness depend on it.
-export const buildWslRuntimeProbeScript = (linuxAppRoot: string) =>
- [
- `bash -lc ${shellQuote(`${buildWslNodeEnvPreamble()}${RESOLVED_PATH_LINE}`)} 2>/dev/null || ${RESOLVED_PATH_LINE}`,
- `${shellQuote(`${linuxAppRoot}/t3`)} --version >/dev/null 2>&1`,
- ].join("\n");
+// The install script already ran the staged t3, so running it again here only adds a second startup.
+export const buildWslRuntimeProbeScript = () =>
+ `bash -lc ${shellQuote(`${buildWslNodeEnvPreamble()}${RESOLVED_PATH_LINE}`)} 2>/dev/null || ${RESOLVED_PATH_LINE}`;
const TOOLCHAIN_CHECK_SCRIPT = [
"for tool in node make g++ python3; do",
@@ -601,30 +596,17 @@ const formatMissingToolsReason = (
const probeWslRuntimeImpl = Effect.fn("DesktopWslEnvironment.probeWslRuntimeImpl")(function* (
distro: string | null,
- linuxAppRoot: string,
): Effect.fn.Return {
- const probe = yield* runWslShell(
- distro,
- buildWslRuntimeProbeScript(linuxAppRoot),
- PROBE_TIMEOUT,
- {
- resolveNode: false,
- },
- );
+ const probe = yield* runWslShell(distro, buildWslRuntimeProbeScript(), PROBE_TIMEOUT, {
+ resolveNode: false,
+ });
const transportFailureReason = formatWslShellTransportFailureReason(
probe.transportFailure,
- "the staged runtime",
+ "the login-shell PATH",
);
if (transportFailureReason !== null) {
return { ok: false, reason: transportFailureReason } as const;
}
- if (probe.exitCode !== 0) {
- const trimmedTail = probe.stderr.trim().slice(-500);
- return {
- ok: false,
- reason: `${linuxAppRoot}/t3 --version failed (exit ${probe.exitCode})${trimmedTail ? `: ${trimmedTail}` : ""}`,
- } as const;
- }
const resolvedPath = parseResolvedPath(probe.stdout);
if (resolvedPath === null) {
return {
@@ -1175,7 +1157,7 @@ export interface DesktopWslEnvironmentTestStub {
) => PrepareWslRuntimeResult;
readonly pruneRuntimes?: (distro: string | null, runtimeId: string) => Effect.Effect;
readonly invalidateRuntime?: (distro: string | null, runtimeId: string) => Effect.Effect;
- readonly probeRuntime?: (distro: string | null, linuxAppRoot: string) => ProbeWslRuntimeResult;
+ readonly probeRuntime?: (distro: string | null) => ProbeWslRuntimeResult;
readonly ensureNodePty?: (
distro: string | null,
linuxAppRoot: string,
@@ -1222,16 +1204,14 @@ export const layerTest = (stub: DesktopWslEnvironmentTestStub = {}) => {
return stub.invalidateRuntime?.(distro, runtimeId) ?? Effect.void;
},
),
- probeRuntime: Effect.fn("DesktopWslEnvironment.probeRuntime")(
- function (distro, linuxAppRoot) {
- return Effect.succeed(
- stub.probeRuntime?.(distro, linuxAppRoot) ?? {
- ok: true,
- resolvedPath: "/usr/bin:/bin",
- },
- );
- },
- ),
+ probeRuntime: Effect.fn("DesktopWslEnvironment.probeRuntime")(function (distro) {
+ return Effect.succeed(
+ stub.probeRuntime?.(distro) ?? {
+ ok: true,
+ resolvedPath: "/usr/bin:/bin",
+ },
+ );
+ }),
ensureNodePty: Effect.fn("DesktopWslEnvironment.ensureNodePty")(
function (distro, linuxAppRoot, options) {
return Effect.succeed(
@@ -1321,8 +1301,8 @@ export const layer = Layer.effect(
invalidateRuntime: Effect.fn("desktop.wsl.invalidateRuntime")(function (distro, runtimeId) {
return provideSpawner(invalidateWslRuntimeImpl(distro, runtimeId));
}),
- probeRuntime: Effect.fn("desktop.wsl.probeRuntime")(function (distro, linuxAppRoot) {
- return provideSpawner(probeWslRuntimeImpl(distro, linuxAppRoot));
+ probeRuntime: Effect.fn("desktop.wsl.probeRuntime")(function (distro) {
+ return provideSpawner(probeWslRuntimeImpl(distro));
}),
ensureNodePty: Effect.fn("desktop.wsl.ensureNodePty")(
function (distro, linuxAppRoot, options) {
diff --git a/apps/desktop/vite.config.ts b/apps/desktop/vite.config.ts
index 455901299edc3..3e6fd9531106b 100644
--- a/apps/desktop/vite.config.ts
+++ b/apps/desktop/vite.config.ts
@@ -164,6 +164,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..6527342d674e5
--- /dev/null
+++ b/apps/marketing/src/lib/releases.test.ts
@@ -0,0 +1,18 @@
+import { afterEach, describe, expect, it, vi } from "vite-plus/test";
+
+import { fetchLatestRelease } from "./releases";
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+describe("fetchLatestRelease", () => {
+ it("rejects a GitHub API error response instead of returning it as a release", async () => {
+ vi.stubGlobal("sessionStorage", { getItem: () => null });
+ vi.stubGlobal("fetch", async () =>
+ Response.json({ message: "API rate limit exceeded" }, { status: 403 }),
+ );
+
+ await expect(fetchLatestRelease("stable")).rejects.toThrow("403");
+ });
+});
diff --git a/apps/marketing/src/lib/releases.ts b/apps/marketing/src/lib/releases.ts
index 7dc63bdaed859..f50103972cdd8 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/marketing/src/pages/[...locale]/index.astro b/apps/marketing/src/pages/[...locale]/index.astro
index 3d8d44568d448..e8f4b5f1b5fa5 100644
--- a/apps/marketing/src/pages/[...locale]/index.astro
+++ b/apps/marketing/src/pages/[...locale]/index.astro
@@ -1234,6 +1234,8 @@ const mobileEndorsementRows = [
section { padding: 56px 0; }
.sec-cta { padding: 80px 0; }
.container { padding-left: 20px; padding-right: 20px; }
+ /* A nowrap tag widens its column past the grid, which then clips the other column. */
+ .harness-tag { white-space: normal; }
.endorsements-head {
margin-bottom: 40px;
}
@@ -1265,4 +1267,8 @@ const mobileEndorsementRows = [
font-size: 11px;
}
}
+
+ @media (max-width: 360px) {
+ .harness { padding-left: 12px; padding-right: 12px; }
+ }
diff --git a/apps/mobile/deps/react-native-screens-5.0.0-t3.50.tgz b/apps/mobile/deps/react-native-screens-5.0.0-t3.50.tgz
deleted file mode 100644
index 74c351ddc3371..0000000000000
Binary files a/apps/mobile/deps/react-native-screens-5.0.0-t3.50.tgz and /dev/null differ
diff --git a/apps/mobile/deps/react-native-screens-5.0.0-t3.58.tgz b/apps/mobile/deps/react-native-screens-5.0.0-t3.58.tgz
new file mode 100644
index 0000000000000..06f9fc0fa91b9
Binary files /dev/null and b/apps/mobile/deps/react-native-screens-5.0.0-t3.58.tgz differ
diff --git a/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift b/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift
index 96551d05bbb55..253376fe5e4d3 100644
--- a/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift
+++ b/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift
@@ -1,7 +1,8 @@
import ExpoModulesCore
import UIKit
+import UniformTypeIdentifiers
-private struct ComposerTokenPayload: Decodable {
+private struct ComposerTokenPayload: Decodable, Equatable {
let type: String
let source: String
let label: String
@@ -9,8 +10,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 {
@@ -38,12 +47,12 @@ private enum ComposerEnterBehavior: String {
}
private final class ComposerTextAttachment: NSTextAttachment {
- let source: String
- let label: String
+ let token: ComposerTokenPayload
+ var source: String { token.source }
+ var label: String { token.label }
- init(source: String, label: String, image: UIImage, size: CGSize, baselineOffset: CGFloat) {
- self.source = source
- self.label = label
+ init(token: ComposerTokenPayload, image: UIImage, size: CGSize, baselineOffset: CGFloat) {
+ self.token = token
super.init(data: nil, ofType: nil)
self.image = image
bounds = CGRect(x: 0, y: baselineOffset, width: size.width, height: size.height)
@@ -80,7 +89,6 @@ private final class ComposerTextView: UITextView {
var onPasteContext: (([String: String]) -> Void)?
var onPasteText: ((String, NSRange) -> Void)?
var clipboardFragment = ""
- var onAttributedMutation: (() -> Void)?
var onSubmit: ((Bool) -> Void)?
var isReadOnly = false
var textPasteThresholdBytes = 0
@@ -242,8 +250,9 @@ private final class ComposerTextView: UITextView {
return
}
}
+ // pasteboard.string is only the first item; super.paste inserts every text item.
if !bypassTextPasteInterception,
- let text = pasteboard.string, shouldInterceptTextPaste(text) {
+ let text = pasteboard.strings?.joined(), shouldInterceptTextPaste(text) {
onPasteText?(text, selectedRange)
return
}
@@ -301,18 +310,28 @@ private final class ComposerTextView: UITextView {
func loadImages(from providers: [NSItemProvider]) {
let group = DispatchGroup()
let lock = NSLock()
- var images = [UIImage?](repeating: nil, count: providers.count)
+ var images = [(data: Data, fileExtension: String)?](repeating: nil, count: providers.count)
for (index, provider) in providers.enumerated() {
group.enter()
- provider.loadObject(ofClass: UIImage.self) { object, _ in
- defer { group.leave() }
- guard let image = object as? UIImage else {
- return
- }
+ let store = { (image: (data: Data, fileExtension: String)?) in
lock.lock()
images[index] = image
lock.unlock()
+ group.leave()
+ }
+ let loadPNG = {
+ _ = provider.loadObject(ofClass: UIImage.self) { object, _ in
+ store((object as? UIImage)?.pngData().map { ($0, "png") })
+ }
+ }
+ // Decoding a GIF to UIImage keeps only its first frame, so pass its bytes through.
+ if provider.hasItemConformingToTypeIdentifier(UTType.gif.identifier) {
+ _ = provider.loadDataRepresentation(forTypeIdentifier: UTType.gif.identifier) { data, _ in
+ if let data { store((data, "gif")) } else { loadPNG() }
+ }
+ } else {
+ loadPNG()
}
}
@@ -320,7 +339,9 @@ private final class ComposerTextView: UITextView {
guard let self, !self.isReadOnly else {
return
}
- let urls = images.compactMap { $0 }.compactMap(Self.writeTemporaryImage)
+ let urls = images.compactMap { $0 }.compactMap {
+ Self.writeTemporaryImage($0.data, fileExtension: $0.fileExtension)
+ }
if !urls.isEmpty {
self.onPasteImages?(urls)
}
@@ -342,9 +363,7 @@ private final class ComposerTextView: UITextView {
return super.cut(sender)
}
copy(sender)
- textStorage.replaceCharacters(in: selectedRange, with: "")
- selectedRange = NSRange(location: selectedRange.location, length: 0)
- onAttributedMutation?()
+ replaceDisplayRange(selectedRange)
}
func serializedText() -> String {
@@ -400,9 +419,10 @@ private final class ComposerTextView: UITextView {
}
private static func writeTemporaryImage(_ image: UIImage) -> String? {
- guard let data = image.pngData() else {
- return nil
- }
+ image.pngData().flatMap { writeTemporaryImage($0, fileExtension: "png") }
+ }
+
+ private static func writeTemporaryImage(_ data: Data, fileExtension: String) -> String? {
let directory = FileManager.default.temporaryDirectory
.appendingPathComponent(pastedImageDirectoryName, isDirectory: true)
do {
@@ -411,7 +431,7 @@ private final class ComposerTextView: UITextView {
withIntermediateDirectories: true
)
removeStaleTemporaryImages(in: directory)
- let url = directory.appendingPathComponent("\(UUID().uuidString).png")
+ let url = directory.appendingPathComponent("\(UUID().uuidString).\(fileExtension)")
try data.write(to: url, options: .atomic)
return url.absoluteString
} catch {
@@ -542,9 +562,6 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro
"selection": ["start": selection.start, "end": selection.end],
])
}
- textView.onAttributedMutation = { [weak self] in
- self?.emitTextChange()
- }
textView.onSubmit = { [weak self] alternate in
self?.onComposerSubmit(["alternate": alternate])
}
@@ -714,8 +731,12 @@ 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) ?? []
+ // Rebuild only when a chip on screen would look different: typing before a chip moves its
+ // offsets, and Undo restores the chip it removed. A rebuild there makes iOS autocorrect
+ // behind the caret, and replacing the text drops UIKit's Redo.
+ tokensNeedRebuild = tokensNeedRebuild || !nextTokens.elementsEqual(renderedChipTokens(), by: { $0.rendersLike($1) })
+ tokens = nextTokens
}
let previousSelection = sourceSelection()
value = document.value
@@ -739,6 +760,7 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro
func setPlaceholder(_ placeholder: String) {
placeholderLabel.text = placeholder
+ textView.accessibilityLabel = placeholder
setNeedsLayout()
}
@@ -1027,8 +1049,7 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro
font: chipFont
)
let attachment = ComposerTextAttachment(
- source: token.source,
- label: token.label,
+ token: token,
image: image,
size: image.size,
baselineOffset: chipFont.ascender - image.size.height
@@ -1328,9 +1349,22 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro
}
}
+ private func renderedChipTokens() -> [ComposerTokenPayload] {
+ var rendered: [ComposerTokenPayload] = []
+ textView.textStorage.enumerateAttribute(
+ .attachment,
+ in: NSRange(location: 0, length: textView.textStorage.length)
+ ) { value, _, _ in
+ if let attachment = value as? ComposerTextAttachment {
+ rendered.append(attachment.token)
+ }
+ }
+ return rendered
+ }
+
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 +1373,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..6b69f29d308d5 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,62 @@ 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))")
+}
+
+// Cutting a chip is undoable: Undo restores the chip and tells the parent, Redo removes it again.
+// The parent echoes each edit with its re-derived chips; those echoes must not rebuild the text.
+do {
+ let view = makeEditor("hi @README.md ok", tokensJson: mention("README.md", at: 3))
+ func echo() {
+ let revision = view.onComposerChange.payloads.last?["eventCount"] as? Int ?? 0
+ let chips = view.text.contains("@README.md") ? mention("README.md", at: 3) : "[]"
+ view.setControlledDocumentJson(document(view.text, revision: revision, isNativeEcho: true, tokensJson: chips))
+ }
+ view.editor.selectedRange = NSRange(location: 3, length: 2)
+ view.editor.cut(nil)
+ check(view.text == "hi ok", "Cut left the selection behind: \(view.text)")
+ check(view.onComposerChange.payloads.last?["value"] as? String == "hi ok", "Cut did not emit the new value")
+ echo()
+ view.editor.undoManager?.undo()
+ check(view.text == "hi @README.md ok", "Undo did not restore the cut text: \(view.text)")
+ let restored = view.chip(at: 3)
+ check(restored is ComposerTextAttachment, "Undo did not restore the cut chip")
+ check(view.onComposerChange.payloads.last?["value"] as? String == "hi @README.md ok", "Undo did not emit the restored value")
+ echo()
+ check(view.chip(at: 3) === restored, "The parent's echo of the restored chip rebuilt the text and dropped Redo")
+ view.editor.undoManager?.redo()
+ check(view.text == "hi ok", "Redo did not cut again: \(view.text)")
+}
+
print("composer editor tests passed")
private let dropEditor = ComposerTextView()
@@ -174,6 +237,40 @@ for readOnly in [true, false] {
check(provider.loadCount == 0, "Locked inputs must not load pasted image providers")
}
+func interceptedPaste(_ items: [String]) -> String? {
+ let savedItems = UIPasteboard.general.items
+ defer { UIPasteboard.general.items = savedItems }
+ let editor = ComposerTextView()
+ editor.textPasteThresholdBytes = 32 * 1024
+ var intercepted: String?
+ editor.onPasteText = { text, _ in intercepted = text }
+ UIPasteboard.general.items = items.map { [UTType.utf8PlainText.identifier: $0] }
+ editor.paste(nil)
+ return intercepted
+}
+let halfA = String(repeating: "A", count: 20_000)
+let halfB = String(repeating: "B", count: 20_000)
+check(interceptedPaste([halfA, halfB]) == halfA + halfB, "Text items that together reach the threshold must fold")
+
+// Two-frame animated GIF: a mixed paste keeps the GIF's original bytes and the still image's PNG, in order.
+private let gifBytes = Data(base64Encoded: "R0lGODlhAQABAIEAAP8AAAAAAAAAAAAAACH/C05FVFNDQVBFMi4wAwEAAAAh+QQACgAAACwAAAAAAQABAAAIBAABBAQAIfkEAAoAAAAsAAAAAAEAAQCBAP8AAAAAAAAAAAAACAQAAQQEADs=")!
+private let gifProvider = NSItemProvider()
+gifProvider.registerDataRepresentation(forTypeIdentifier: UTType.gif.identifier, visibility: .all) { completion in
+ completion(gifBytes, nil)
+ return nil
+}
+private let gifEditor = ComposerTextView()
+gifEditor.onPasteImages = { urls in
+ let files = urls.compactMap(URL.init(string:))
+ let contents = files.compactMap { try? Data(contentsOf: $0) }
+ files.forEach { try? FileManager.default.removeItem(at: $0) }
+ check(files.map(\.pathExtension) == ["gif", "png"], "A mixed paste must keep each image's format, in order: \(urls)")
+ check(contents.first == gifBytes, "A pasted animated GIF must keep its original bytes")
+ check(contents.count == 2 && contents[1] == image.pngData(), "The still image beside a GIF must still attach as PNG")
+ print("Composer GIF-paste checks passed")
+ exit(0)
+}
+
// Inline provider completion places the attachment callback before this main-queue check.
DispatchQueue.main.async {
check(pastedImages.count == 1, "An accepted provider-based paste must emit exactly one attachment batch")
@@ -190,6 +287,7 @@ DispatchQueue.main.async {
"The attachment must contain the pasted image's pixels")
check(pasteEditor.text == "Keep this draft", "Image paste must preserve the draft text")
print("Composer provider-paste checks passed")
- exit(0)
+ check(gifProvider.canLoadObject(ofClass: UIImage.self), "A GIF provider must take the image paste path")
+ gifEditor.paste(itemProviders: [gifProvider, ImmediateImageProvider(image: image)])
}
dispatchMain()
diff --git a/apps/mobile/modules/t3-native-controls/ios/T3NativeControlsModule.swift b/apps/mobile/modules/t3-native-controls/ios/T3NativeControlsModule.swift
index af67e80afebb4..c8ec3886974a9 100644
--- a/apps/mobile/modules/t3-native-controls/ios/T3NativeControlsModule.swift
+++ b/apps/mobile/modules/t3-native-controls/ios/T3NativeControlsModule.swift
@@ -10,6 +10,10 @@ public final class T3NativeControlsModule: Module {
private let presentationSources = T3PresentationSources()
private var videoPresentation: T3NativeVideoPresentation?
private var filePresentation: T3NativeFilePresentation?
+ private var imageViewer: T3NativeImageViewer?
+ /// 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")
@@ -85,26 +89,42 @@ public final class T3NativeControlsModule: Module {
else {
throw URLError(.badURL)
}
- let file = try self.makeFilePresentation(sourceIdentifiers: sourceIdentifiers, identifier: identifier,
- promise: promise)
- guard let presenter = self.appContext?.utilities?.currentViewController() else {
- file.dismiss()
- return
- }
- file.present(urls: urls, titles: titles, selectedIndex: selectedIndex, from: presenter)
+ // A viewer still animating closed must not block the next one, as Quick Look's error alert did.
+ self.imageViewer?.finishImmediately()
+ guard self.filePresentation == nil, self.videoPresentation == nil,
+ let presenter = self.appContext?.utilities?.currentViewController()
+ else { throw URLError(.cannotLoadFromNetwork) }
+ let viewer = T3NativeImageViewer(
+ identifier: identifier, sources: self.presentationSources, sourceIdentifiers: sourceIdentifiers,
+ onFinish: { [weak self] in self?.setFinishedFilePreview(identifier) },
+ completion: { [weak self] error in
+ if self?.imageViewer?.identifier == identifier { self?.imageViewer = nil }
+ if let error { promise.reject(error) } else { promise.resolve(nil) }
+ }
+ )
+ self.imageViewer = viewer
+ viewer.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) }
+ if self.imageViewer?.identifier == identifier { self.imageViewer?.update(index: index, url: url) }
}.runOnQueue(.main)
OnDestroy {
let presentation = self.videoPresentation
let file = self.filePresentation
+ let images = self.imageViewer
DispatchQueue.main.async {
presentation?.dismiss()
file?.dismiss()
+ images?.dismiss()
}
}
@@ -261,7 +281,7 @@ public final class T3NativeControlsModule: Module {
let isPlayableURL = url.isFileURL
? FileManager.default.isReadableFile(atPath: url.path)
: (["https", "http"].contains(url.scheme?.lowercased() ?? "") && url.host != nil)
- guard videoPresentation == nil, filePresentation == nil,
+ guard videoPresentation == nil, filePresentation == nil, imageViewer == nil,
let presenter = appContext?.utilities?.currentViewController(),
isPlayableURL
else {
@@ -289,29 +309,37 @@ public final class T3NativeControlsModule: Module {
if videoPresentation?.identifier == identifier { videoPresentation?.dismiss() }
}
- private func makeFilePresentation(sourceIdentifiers: [String], identifier: String,
+ private func makeFilePresentation(sourceIdentifier: String, identifier: String,
promise: Promise) throws -> T3NativeFilePresentation {
- guard filePresentation == nil, videoPresentation == nil,
+ guard filePresentation == nil, videoPresentation == nil, imageViewer == 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, sourceIdentifier: sourceIdentifier,
+ 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)
+ let file = try makeFilePresentation(sourceIdentifier: sourceIdentifier, identifier: identifier, promise: promise)
guard let presenter = appContext?.utilities?.currentViewController() else { file.dismiss(); return }
file.present(url: url, title: title, from: presenter)
}
private func dismissFilePresentation(identifier: String) {
if filePresentation?.identifier == identifier { filePresentation?.dismiss() }
+ if imageViewer?.identifier == identifier { imageViewer?.dismiss() }
}
private static func saveImageToLibrary(url: URL, mimeType: String, name: String, 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..a939fc473f100 100644
--- a/apps/mobile/modules/t3-native-controls/ios/T3NativeFilePresentation.swift
+++ b/apps/mobile/modules/t3-native-controls/ios/T3NativeFilePresentation.swift
@@ -8,232 +8,149 @@ 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?() }
}
}
+/// A load faster than this zooms straight from the thumbnail without a spinner.
+private let spinnerDelayNanoseconds: UInt64 = 250_000_000
+
+/// Quick Look for PDFs and documents; images open in T3NativeImageViewer.
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 urls: [URL?] = []
- private var states: [FilePreviewState] = []
- private var selectedIndex = 0
- 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 let sourceIdentifier: String
+ private var file: URL?
+ private var item: FilePreviewItem?
+ private var download: 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) {
+ init(identifier: String, sources: T3PresentationSources, sourceIdentifier: String,
+ onFinish: @escaping () -> Void, completion: @escaping (Error?) -> Void) {
self.identifier = identifier
self.sources = sources
- self.sourceIdentifiers = sourceIdentifiers
+ self.sourceIdentifier = sourceIdentifier
+ 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)
- }
-
- /// 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.
- func present(urls: [URL?], titles: [String], selectedIndex: Int, from presenter: UIViewController) {
- load(urls: urls, titles: titles, selectedIndex: selectedIndex, from: presenter, opensWhileLoading: true)
- }
-
- /// 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 let url else {
- failed(index, error: 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()
- }
+ spinnerDelay = Task { @MainActor [self] in
+ try? await Task.sleep(nanoseconds: spinnerDelayNanoseconds)
+ guard !Task.isCancelled else { return }
+ showSpinner()
}
- loadNext()
- }
-
- /// 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
+ download = 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()
+ settle(result, title: title, presenter: presenter)
}
- 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(_ result: Result, title: String, presenter: UIViewController) {
+ 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 {
+ 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)
+ openError = NSError(
+ domain: "T3NativePresentation",
+ code: 3,
+ userInfo: [NSLocalizedDescriptionKey: "This file type cannot be previewed on this device."]
+ )
+ finish()
+ return
+ }
+ self.file = file
+ show(file: file, title: title, presenter: presenter)
+ case .failure(let error):
openError = error
- dismiss()
- return
+ finish()
}
- states[index] = .failed
- refresh(index)
}
- private func show() {
- guard let presenter else { finish(); return }
- placeholder?.cancel()
+ private func show(file: URL, title: String, presenter: UIViewController) {
+ cancelLoading()
+ let item = FilePreviewItem()
+ item.previewItemURL = file
+ item.previewItemTitle = title
+ self.item = item
let preview = FilePreviewController()
preview.delegate = self
preview.dataSource = self
- preview.currentPreviewItemIndex = selectedIndex
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,
+ let source = sources?.view(for: sourceIdentifier),
+ 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() {
+ download?.cancel()
+ download = 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.
@@ -249,27 +166,23 @@ final class T3NativeFilePresentation: NSObject, QLPreviewControllerDataSource,
}
}
- func numberOfPreviewItems(in controller: QLPreviewController) -> Int { items.count }
+ func numberOfPreviewItems(in controller: QLPreviewController) -> Int { item == nil ? 0 : 1 }
func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> QLPreviewItem {
- items[index]
+ item ?? FilePreviewItem()
}
- private func sourceView(for item: QLPreviewItem) -> UIView? {
- guard !UIAccessibility.isReduceMotionEnabled,
- let index = items.firstIndex(where: { $0 === item }),
- sourceIdentifiers.indices.contains(index)
- else { return nil }
- return sources?.view(for: sourceIdentifiers[index])
+ private var sourceView: UIView? {
+ UIAccessibility.isReduceMotionEnabled ? nil : sources?.view(for: sourceIdentifier)
}
func previewController(_ controller: QLPreviewController, transitionViewFor item: QLPreviewItem) -> UIView? {
- sourceView(for: item)
+ sourceView
}
func previewController(_ controller: QLPreviewController, frameFor item: QLPreviewItem,
inSourceView view: AutoreleasingUnsafeMutablePointer) -> CGRect {
- guard let source = sourceView(for: item) else { return .zero }
+ guard let source = sourceView else { return .zero }
view.pointee = source
return source.bounds
}
@@ -278,47 +191,49 @@ 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()
+ if let file { Self.remove(file) }
+ file = nil
+ item = nil
+ 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())
+ }
+
+ /// Writes the bytes behind a file, data or http(s) URL to `destination`, returning the MIME type it declares.
+ nonisolated private static func copyOriginal(_ url: URL, to destination: URL) async throws -> String? {
+ if url.isFileURL {
+ try FileManager.default.copyItem(at: url, to: destination)
+ return nil
+ }
+ if url.scheme == "data" {
+ try Data(contentsOf: url).write(to: destination, options: .atomic)
+ return url.absoluteString.lowercased().hasPrefix("data:image/svg+xml") ? "image/svg+xml" : nil
+ }
+ guard ["https", "http"].contains(url.scheme?.lowercased() ?? "") else { throw URLError(.unsupportedURL) }
+ let (temporaryFile, response) = try await URLSession.shared.download(from: url)
+ guard let response = response as? HTTPURLResponse, (200..<300).contains(response.statusCode) else {
+ throw URLError(.badServerResponse)
}
- items.removeAll()
- urls.removeAll()
- states.removeAll()
- let result = error ?? openError
- DispatchQueue.main.async { [completion] in completion(result) }
+ try FileManager.default.moveItem(at: temporaryFile, to: destination)
+ return response.mimeType
}
/// Copy original bytes so preview and sharing do not mutate a draft or workspace file.
- nonisolated private static func prepareFile(url: URL, title: String) async throws -> URL {
+ nonisolated static func prepareFile(url: URL, title: String) async throws -> URL {
try Task.checkCancellation()
let directory = FileManager.default.temporaryDirectory.appendingPathComponent("t3-preview-\(UUID().uuidString)")
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
do {
let download = directory.appendingPathComponent("original")
- if url.isFileURL {
- try FileManager.default.copyItem(at: url, to: download)
- } else if url.scheme == "data" {
- try Data(contentsOf: url).write(to: download, options: .atomic)
- } else {
- guard ["https", "http"].contains(url.scheme?.lowercased() ?? "") else {
- throw URLError(.unsupportedURL)
- }
- let (temporaryFile, response) = try await URLSession.shared.download(from: url)
- guard let response = response as? HTTPURLResponse, (200..<300).contains(response.statusCode) else {
- throw URLError(.badServerResponse)
- }
- try FileManager.default.moveItem(at: temporaryFile, to: download)
- }
+ let mimeType = try await copyOriginal(url, to: download)
try Task.checkCancellation()
// Detect images and PDFs by content; preserve other extensions so Quick Look can decide support.
let filename = URL(fileURLWithPath: title).lastPathComponent as NSString
@@ -330,7 +245,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-native-controls/ios/T3NativeImageViewer.swift b/apps/mobile/modules/t3-native-controls/ios/T3NativeImageViewer.swift
new file mode 100644
index 0000000000000..382e92875f303
--- /dev/null
+++ b/apps/mobile/modules/t3-native-controls/ios/T3NativeImageViewer.swift
@@ -0,0 +1,952 @@
+import ImageIO
+import Photos
+import UIKit
+
+/// Full-screen image gallery modelled on Messages. It opens at once from the tapped thumbnail's
+/// own pixels and sharpens when the original arrives, so a slow or failed load never holds it back.
+final class T3NativeImageViewer: NSObject {
+ let identifier: String
+ private let completion: (Error?) -> Void
+ private let onFinish: () -> Void
+ private weak var sources: T3PresentationSources?
+ private let sourceIdentifiers: [String]
+ private var titles: [String] = []
+ private var urls: [URL?] = []
+ /// The original bytes on disk, kept for sharing.
+ private var files: [URL?] = []
+ private var placeholders: [UIImage?] = []
+ private var loads: [Int: Task] = [:]
+ private var decodes: [Int: Task] = [:]
+ /// The last queued decode; each one waits for it, so one original decodes at a time.
+ private var decodeQueue: Task?
+ /// Pages showing their decoded original; only the current page and its neighbours keep one.
+ private var decoded: Set = []
+ private var currentIndex = 0
+ private var controller: T3ImageViewerController?
+ private var finished = false
+
+ init(identifier: String, sources: T3PresentationSources, sourceIdentifiers: [String],
+ onFinish: @escaping () -> Void, completion: @escaping (Error?) -> Void) {
+ self.identifier = identifier
+ self.sources = sources
+ self.sourceIdentifiers = sourceIdentifiers
+ self.onFinish = onFinish
+ self.completion = completion
+ super.init()
+ }
+
+ func present(urls: [URL?], titles: [String], selectedIndex: Int, from presenter: UIViewController) {
+ self.urls = urls
+ self.titles = titles
+ files = Array(repeating: nil, count: urls.count)
+ currentIndex = selectedIndex
+ let viewer = T3ImageViewerController(titles: titles, selectedIndex: selectedIndex)
+ viewer.sourceView = { [weak self] index in self?.sourceView(index) }
+ viewer.fileForPage = { [weak self] index in self?.file(at: index) }
+ viewer.onRetry = { [weak self] index in self?.load(index, retry: true) }
+ viewer.onDismissed = { [weak self] in self?.finish() }
+ viewer.onPageChange = { [weak self] index in self?.show(page: index) }
+ controller = viewer
+ viewer.loadViewIfNeeded()
+ placeholders = urls.indices.map { sourceView($0).flatMap(Self.thumbnail(of:)) }
+ for (index, placeholder) in placeholders.enumerated() {
+ if let placeholder { viewer.setImage(placeholder, at: index, full: false) }
+ }
+ presenter.present(T3ImageViewerNavigation(viewer: viewer), animated: false) { viewer.animateIn() }
+ for index in urls.indices { load(index, retry: false) }
+ }
+
+ /// 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 else { return }
+ guard let url else {
+ controller?.setFailed(at: index, retryable: false)
+ return
+ }
+ urls[index] = url
+ load(index, retry: false)
+ }
+
+ func dismiss() {
+ guard !finished else { return }
+ guard let controller else { finish(); return }
+ controller.close()
+ }
+
+ /// Ends at once, for a new viewer that must open while this one is still animating away.
+ func finishImmediately() {
+ guard !finished else { return }
+ controller?.presentingViewController?.dismiss(animated: false)
+ finish()
+ }
+
+ private func file(at index: Int) -> URL? {
+ files.indices.contains(index) ? files[index] : nil
+ }
+
+ private func sourceView(_ index: Int) -> UIView? {
+ guard sourceIdentifiers.indices.contains(index), !sourceIdentifiers[index].isEmpty else { return nil }
+ return sources?.view(for: sourceIdentifiers[index])
+ }
+
+ private func load(_ index: Int, retry: Bool) {
+ guard !finished, urls.indices.contains(index), let url = urls[index], loads[index] == nil else { return }
+ if retry { controller?.setLoading(at: index) }
+ let title = titles[index]
+ loads[index] = Task { @MainActor [self] in
+ defer { loads[index] = nil }
+ do {
+ let file = try await T3NativeFilePresentation.prepareFile(url: url, title: title)
+ guard !finished, !Task.isCancelled else { Self.remove(file); return }
+ if let previous = files[index] { Self.remove(previous) }
+ files[index] = file
+ decoded.remove(index)
+ if isNearCurrent(index) { decode(index) }
+ } catch {
+ guard !finished, !Task.isCancelled else { return }
+ controller?.setFailed(at: index, retryable: true)
+ }
+ }
+ }
+
+ /// Every original downloads up front, but a decoded one costs far more memory than its file,
+ /// so only pages next to the current one decode, and pages further away fall back to their thumbnail.
+ private func show(page index: Int) {
+ currentIndex = index
+ for other in decoded where !isNearCurrent(other) {
+ decoded.remove(other)
+ controller?.release(at: other, placeholder: placeholders[other])
+ }
+ // Queued decodes for pages paged past are skipped before they start.
+ for (other, task) in decodes where !isNearCurrent(other) { task.cancel() }
+ for near in files.indices where isNearCurrent(near) { decode(near) }
+ }
+
+ private func isNearCurrent(_ index: Int) -> Bool { abs(index - currentIndex) <= 1 }
+
+ private func decode(_ index: Int) {
+ guard !finished, let file = file(at: index), !decoded.contains(index), decodes[index] == nil else { return }
+ let source = sourceView(index)
+ let previous = decodeQueue
+ let task = Task { @MainActor [self] in
+ await previous?.value
+ var settled = false
+ defer {
+ decodes[index] = nil
+ // Paged away and back while this run waited: it was cancelled, so the page asks again.
+ if !settled, !finished, isNearCurrent(index), !decoded.contains(index) { decode(index) }
+ }
+ guard !finished, !Task.isCancelled, isNearCurrent(index), files[index] == file else { return }
+ // ImageIO reads SVG poorly or not at all; the thumbnail is vector, so redraw it at full-screen size.
+ let isSVG = file.pathExtension.lowercased() == "svg"
+ let image = isSVG ? nil : await Task.detached(priority: .userInitiated) { Self.decode(file) }.value
+ guard !finished, !Task.isCancelled, isNearCurrent(index), files[index] == file else { return }
+ if isSVG {
+ // The open transition hides the thumbnail, which draws blank until it is back.
+ await controller?.untilRevealed()
+ guard !finished, !Task.isCancelled, isNearCurrent(index), files[index] == file else { return }
+ }
+ settled = true
+ if let image = image ?? (isSVG ? source.flatMap(Self.render(_:)) : nil) {
+ decoded.insert(index)
+ controller?.setImage(image, at: index, full: true)
+ } else {
+ // A corrupt download or an SVG whose thumbnail is scrolled away; retrying downloads it again.
+ // A file that is not an image must not reach Share.
+ if !isSVG {
+ Self.remove(file)
+ files[index] = nil
+ }
+ controller?.setFailed(at: index, retryable: true)
+ }
+ }
+ decodes[index] = task
+ decodeQueue = task
+ }
+
+ private func finish() {
+ guard !finished else { return }
+ finished = true
+ for task in loads.values { task.cancel() }
+ loads.removeAll()
+ for task in decodes.values { task.cancel() }
+ decodes.removeAll()
+ decodeQueue = nil
+ for file in files.compactMap({ $0 }) { Self.remove(file) }
+ files.removeAll()
+ controller = nil
+ DispatchQueue.main.async { [completion] in completion(nil) }
+ // 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())
+ }
+
+ /// The decoded image a thumbnail already shows, uncropped, or a snapshot of a view that draws one.
+ /// The largest image view wins, so an overlaid icon is never mistaken for the picture.
+ private static func thumbnail(of view: UIView) -> UIImage? {
+ var queue = [view]
+ var best: (image: UIImage, area: CGFloat)?
+ while let candidate = queue.popLast() {
+ queue.append(contentsOf: candidate.subviews)
+ guard let image = (candidate as? UIImageView)?.image, image.size.width > 0, image.size.height > 0 else { continue }
+ let area = candidate.bounds.width * candidate.bounds.height
+ if area > best?.area ?? 0 { best = (image, area) }
+ }
+ if let best, best.area >= view.bounds.width * view.bounds.height / 2 { return best.image }
+ return snapshot(view, scale: view.window?.screen.scale ?? 2)
+ }
+
+ private static func render(_ view: UIView) -> UIImage? {
+ let screen = view.window?.screen.bounds.size ?? CGSize(width: 1024, height: 1024)
+ let fit = min(screen.width / max(view.bounds.width, 1), screen.height / max(view.bounds.height, 1))
+ // The thumbnail was shown again after the open transition, in a frame not yet on screen.
+ return snapshot(view, scale: max(1, fit) * (view.window?.screen.scale ?? 2), afterScreenUpdates: true)
+ }
+
+ private static func snapshot(_ view: UIView, scale: CGFloat, afterScreenUpdates: Bool = false) -> UIImage? {
+ guard view.bounds.width > 1, view.bounds.height > 1, view.window != nil else { return nil }
+ let format = UIGraphicsImageRendererFormat()
+ format.scale = scale
+ format.opaque = false
+ return UIGraphicsImageRenderer(bounds: view.bounds, format: format).image { _ in
+ view.drawHierarchy(in: view.bounds, afterScreenUpdates: afterScreenUpdates)
+ }
+ }
+
+ /// Decodes off the main thread at no more than zooming needs, and keeps GIFs animated.
+ nonisolated private static func decode(_ file: URL) -> UIImage? {
+ guard let source = CGImageSourceCreateWithURL(file as CFURL, nil) else { return nil }
+ let count = CGImageSourceGetCount(source)
+ guard count > 0 else { return nil }
+ let options: [CFString: Any] = [
+ kCGImageSourceCreateThumbnailFromImageAlways: true,
+ kCGImageSourceCreateThumbnailWithTransform: true,
+ kCGImageSourceShouldCacheImmediately: true,
+ kCGImageSourceThumbnailMaxPixelSize: 4096,
+ ]
+ var animationOptions = options
+ animationOptions[kCGImageSourceThumbnailMaxPixelSize] = 1024
+ animationOptions[kCGImageSourceShouldCacheImmediately] = nil
+ // Every frame stays decoded while it plays, so an animation over this budget shows its first frame.
+ if count > 1, let first = CGImageSourceCreateThumbnailAtIndex(source, 0, animationOptions as CFDictionary),
+ first.bytesPerRow * first.height * count <= animationByteBudget {
+ var frames: [(image: UIImage, delay: Double)] = [(UIImage(cgImage: first), frameDuration(source, 0))]
+ for index in 1.. 1 { return UIImage.animatedImage(with: timeline, duration: Double(timeline.count) * tick) }
+ }
+ return CGImageSourceCreateThumbnailAtIndex(source, 0, options as CFDictionary).map { UIImage(cgImage: $0) }
+ }
+
+ nonisolated private static func frameDuration(_ source: CGImageSource, _ index: Int) -> Double {
+ let properties = CGImageSourceCopyPropertiesAtIndex(source, index, nil) as? [CFString: Any]
+ let gif = properties?[kCGImagePropertyGIFDictionary] as? [CFString: Any]
+ let png = properties?[kCGImagePropertyPNGDictionary] as? [CFString: Any]
+ let delay = gif?[kCGImagePropertyGIFUnclampedDelayTime] as? Double
+ ?? gif?[kCGImagePropertyGIFDelayTime] as? Double
+ ?? png?[kCGImagePropertyAPNGUnclampedDelayTime] as? Double
+ ?? png?[kCGImagePropertyAPNGDelayTime] as? Double
+ ?? 0.1
+ // Browsers treat near-zero delays as 0.1s.
+ return delay < 0.011 ? 0.1 : delay
+ }
+}
+
+private let animationByteBudget = 64 * 1024 * 1024
+
+private extension Array {
+ subscript(safe index: Int) -> Element? { indices.contains(index) ? self[index] : nil }
+}
+
+/// One zoomable page. Its content never exceeds its bounds at the fitted zoom, so a vertical
+/// drag has nothing to scroll and always reaches the dismiss gesture.
+private final class T3ImageViewerPage: UIView, UIScrollViewDelegate {
+ let scroll = UIScrollView()
+ let imageView = UIImageView()
+ private let spinner = UIActivityIndicatorView(style: .large)
+ private let failure = UIStackView()
+ private var spinnerDelay: DispatchWorkItem?
+ private var laidOutSize = CGSize.zero
+ private(set) var isFull = false
+ var onRetry: (() -> Void)?
+
+ override init(frame: CGRect) {
+ super.init(frame: frame)
+ scroll.delegate = self
+ scroll.showsVerticalScrollIndicator = false
+ scroll.showsHorizontalScrollIndicator = false
+ scroll.contentInsetAdjustmentBehavior = .never
+ scroll.decelerationRate = .fast
+ scroll.alwaysBounceVertical = false
+ scroll.alwaysBounceHorizontal = false
+ scroll.bouncesZoom = true
+ addSubview(scroll)
+ imageView.contentMode = .scaleAspectFill
+ imageView.clipsToBounds = true
+ imageView.isAccessibilityElement = true
+ imageView.accessibilityTraits = .image
+ scroll.addSubview(imageView)
+ spinner.color = .white
+ spinner.hidesWhenStopped = true
+ addSubview(spinner)
+ configureFailure()
+ }
+
+ @available(*, unavailable)
+ required init?(coder: NSCoder) { nil }
+
+ private func configureFailure() {
+ let icon = UIImageView(image: UIImage(systemName: "exclamationmark.triangle"))
+ icon.tintColor = UIColor(white: 1, alpha: 0.8)
+ icon.preferredSymbolConfiguration = UIImage.SymbolConfiguration(pointSize: 28, weight: .regular)
+ let label = UILabel()
+ label.text = "This image could not be loaded."
+ label.textColor = UIColor(white: 1, alpha: 0.8)
+ label.font = .preferredFont(forTextStyle: .subheadline)
+ label.adjustsFontForContentSizeCategory = true
+ label.textAlignment = .center
+ label.numberOfLines = 0
+ var configuration = UIButton.Configuration.gray()
+ configuration.title = "Try Again"
+ configuration.cornerStyle = .capsule
+ configuration.baseForegroundColor = .white
+ configuration.baseBackgroundColor = UIColor(white: 1, alpha: 0.18)
+ let retry = UIButton(configuration: configuration, primaryAction: UIAction { [weak self] _ in self?.onRetry?() })
+ failure.axis = .vertical
+ failure.alignment = .center
+ failure.spacing = 12
+ failure.isHidden = true
+ for view in [icon, label, retry] { failure.addArrangedSubview(view) }
+ addSubview(failure)
+ }
+
+ var image: UIImage? { imageView.image }
+
+ func setImage(_ image: UIImage, full: Bool) {
+ guard full || !isFull else { return }
+ let previous = imageView.image?.size
+ imageView.image = image
+ isFull = full
+ stopLoading()
+ failure.isHidden = true
+ let ratio = { (size: CGSize) in size.width / max(size.height, 1) }
+ // A sharper copy of the same picture keeps the reader's zoom; a different shape starts over.
+ if previous == nil || abs(ratio(previous ?? .zero) - ratio(image.size)) > 0.01 { laidOutSize = .zero }
+ setNeedsLayout()
+ }
+
+ /// Gives back a far-away page's decoded original, keeping the thumbnail until it returns.
+ func release(to placeholder: UIImage?) {
+ guard isFull else { return }
+ isFull = false
+ imageView.image = placeholder
+ laidOutSize = .zero
+ setNeedsLayout()
+ setLoading()
+ }
+
+ func setLoading() {
+ failure.isHidden = true
+ imageView.alpha = 1
+ guard imageView.image == nil, spinnerDelay == nil else { return }
+ let work = DispatchWorkItem { [weak self] in self?.spinner.startAnimating() }
+ spinnerDelay = work
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.25, execute: work)
+ }
+
+ func setFailed(retryable: Bool) {
+ stopLoading()
+ guard !isFull else { return }
+ failure.arrangedSubviews.last?.isHidden = !retryable
+ failure.isHidden = false
+ // A thumbnail stays visible behind the message, dimmed.
+ imageView.alpha = imageView.image == nil ? 1 : 0.35
+ }
+
+ private func stopLoading() {
+ spinnerDelay?.cancel()
+ spinnerDelay = nil
+ spinner.stopAnimating()
+ imageView.alpha = 1
+ }
+
+ var isZoomed: Bool { scroll.zoomScale > scroll.minimumZoomScale + 0.01 }
+
+ func resetZoom(animated: Bool) { scroll.setZoomScale(scroll.minimumZoomScale, animated: animated) }
+
+ override func layoutSubviews() {
+ super.layoutSubviews()
+ scroll.frame = bounds
+ spinner.center = CGPoint(x: bounds.midX, y: bounds.midY)
+ let width = min(bounds.width - 48, 320)
+ let height = failure.systemLayoutSizeFitting(CGSize(width: width, height: 0),
+ withHorizontalFittingPriority: .required,
+ verticalFittingPriority: .fittingSizeLevel).height
+ failure.frame = CGRect(x: (bounds.width - width) / 2, y: (bounds.height - height) / 2, width: width, height: height)
+ guard bounds.size != laidOutSize, let size = imageView.image?.size, size.width > 0, size.height > 0 else { return }
+ laidOutSize = bounds.size
+ let fit = min(bounds.width / size.width, bounds.height / size.height)
+ scroll.minimumZoomScale = 1
+ scroll.zoomScale = 1
+ imageView.transform = .identity
+ imageView.frame = CGRect(x: 0, y: 0, width: size.width * fit, height: size.height * fit)
+ scroll.contentSize = imageView.frame.size
+ // Enough to fill the screen and then some, or to see the original's pixels.
+ let fill = max(bounds.width / imageView.frame.width, bounds.height / imageView.frame.height)
+ let pixels = 1 / fit / (window?.screen.scale ?? 2)
+ scroll.maximumZoomScale = max(3, fill * 1.5, pixels)
+ centerImage()
+ }
+
+ /// The fitted frame of the image, for the opening transition.
+ func fittedFrame(in view: UIView) -> CGRect {
+ layoutIfNeeded()
+ return imageView.convert(imageView.bounds, to: view)
+ }
+
+ func viewForZooming(in scrollView: UIScrollView) -> UIView? { imageView }
+
+ func scrollViewDidZoom(_ scrollView: UIScrollView) { centerImage() }
+
+ private func centerImage() {
+ let content = scroll.contentSize
+ imageView.center = CGPoint(x: max(content.width, scroll.bounds.width) / 2,
+ y: max(content.height, scroll.bounds.height) / 2)
+ }
+
+ func toggleZoom(at point: CGPoint) {
+ if isZoomed { resetZoom(animated: true); return }
+ guard imageView.image != nil else { return }
+ let location = convert(point, to: imageView)
+ let fill = max(scroll.bounds.width / imageView.bounds.width, scroll.bounds.height / imageView.bounds.height)
+ let scale = min(scroll.maximumZoomScale, fill > 1.2 ? fill : 2.5)
+ let width = scroll.bounds.width / scale
+ let height = scroll.bounds.height / scale
+ scroll.zoom(to: CGRect(x: location.x - width / 2, y: location.y - height / 2, width: width, height: height),
+ animated: true)
+ }
+}
+
+/// System bars, so UIKit places Close, the title, Save and Share: at the top and bottom of an iPhone,
+/// and in the side bar of an unfolded iPhone Duo.
+private final class T3ImageViewerNavigation: UINavigationController {
+ init(viewer: T3ImageViewerController) {
+ super.init(rootViewController: viewer)
+ modalPresentationStyle = .overFullScreen
+ modalPresentationCapturesStatusBarAppearance = true
+ overrideUserInterfaceStyle = .dark
+ view.backgroundColor = .clear
+ if #unavailable(iOS 26.0) {
+ // Before iOS 26 bars at the scroll edge are transparent; iOS 26 gives them its edge blur instead.
+ let bar = UINavigationBarAppearance()
+ bar.configureWithDefaultBackground()
+ navigationBar.scrollEdgeAppearance = bar
+ navigationBar.compactScrollEdgeAppearance = bar
+ let tools = UIToolbarAppearance()
+ tools.configureWithDefaultBackground()
+ toolbar.scrollEdgeAppearance = tools
+ toolbar.compactScrollEdgeAppearance = tools
+ }
+ setNavigationBarHidden(true, animated: false)
+ setToolbarHidden(true, animated: false)
+ }
+
+ @available(*, unavailable)
+ required init?(coder: NSCoder) { nil }
+
+ override var childForStatusBarHidden: UIViewController? { topViewController }
+ override var childForStatusBarStyle: UIViewController? { topViewController }
+ override var childForHomeIndicatorAutoHidden: UIViewController? { topViewController }
+}
+
+final class T3ImageViewerController: UIViewController, UIScrollViewDelegate, UIGestureRecognizerDelegate {
+ var sourceView: (Int) -> UIView? = { _ in nil }
+ var fileForPage: (Int) -> URL? = { _ in nil }
+ var onRetry: (Int) -> Void = { _ in }
+ var onPageChange: (Int) -> Void = { _ in }
+ var onDismissed: () -> Void = {}
+
+ private let titles: [String]
+ private var currentIndex: Int
+ private let backdrop = UIView()
+ private let pager = UIScrollView()
+ private var pages: [T3ImageViewerPage] = []
+ private let titleLabel = UILabel()
+ private let counterLabel = UILabel()
+ private lazy var dismissPan = UIPanGestureRecognizer(target: self, action: #selector(handleDismissPan(_:)))
+ private var chromeHidden = false
+ private var chromeHiddenBeforeDrag = false
+ private var dragAnchor = CGPoint.zero
+ private var transitioning = true
+ private var closeRequested = false
+ private var closing = false
+ private var revealed = false
+ private var revealWaiters: [CheckedContinuation] = []
+ private var laidOutSize = CGSize.zero
+ private var isLayingOut = false
+ private lazy var saveItem = UIBarButtonItem(
+ title: "Save to Photos", image: UIImage(systemName: "square.and.arrow.down"),
+ primaryAction: UIAction { [weak self] _ in self?.save() })
+ private lazy var shareItem = UIBarButtonItem(
+ systemItem: .action, primaryAction: UIAction { [weak self] _ in self?.share() })
+ private static let pageGap: CGFloat = 20
+
+ init(titles: [String], selectedIndex: Int) {
+ self.titles = titles
+ currentIndex = selectedIndex
+ super.init(nibName: nil, bundle: nil)
+ }
+
+ @available(*, unavailable)
+ required init?(coder: NSCoder) { nil }
+
+ override var prefersStatusBarHidden: Bool { chromeHidden }
+ override var preferredStatusBarStyle: UIStatusBarStyle { .lightContent }
+ override var prefersHomeIndicatorAutoHidden: Bool { chromeHidden }
+ override var preferredStatusBarUpdateAnimation: UIStatusBarAnimation { .fade }
+
+ override func viewDidLoad() {
+ super.viewDidLoad()
+ view.backgroundColor = .clear
+ backdrop.backgroundColor = .black
+ backdrop.alpha = 0
+ view.addSubview(backdrop)
+ pager.isPagingEnabled = true
+ pager.showsHorizontalScrollIndicator = false
+ pager.showsVerticalScrollIndicator = false
+ pager.contentInsetAdjustmentBehavior = .never
+ pager.alwaysBounceVertical = false
+ pager.delegate = self
+ pager.isHidden = true
+ view.addSubview(pager)
+ for index in titles.indices {
+ let page = T3ImageViewerPage()
+ page.imageView.accessibilityLabel = titles[index]
+ page.onRetry = { [weak self] in self?.onRetry(index) }
+ page.scroll.panGestureRecognizer.require(toFail: dismissPan)
+ page.setLoading()
+ pages.append(page)
+ pager.addSubview(page)
+ }
+ pager.panGestureRecognizer.require(toFail: dismissPan)
+ dismissPan.delegate = self
+ dismissPan.maximumNumberOfTouches = 1
+ view.addGestureRecognizer(dismissPan)
+ let doubleTap = UITapGestureRecognizer(target: self, action: #selector(handleDoubleTap(_:)))
+ doubleTap.numberOfTapsRequired = 2
+ pager.addGestureRecognizer(doubleTap)
+ let singleTap = UITapGestureRecognizer(target: self, action: #selector(handleSingleTap))
+ singleTap.require(toFail: doubleTap)
+ pager.addGestureRecognizer(singleTap)
+ configureChrome()
+ updateTitle()
+ }
+
+ private func configureChrome() {
+ navigationItem.leftBarButtonItem = UIBarButtonItem(
+ systemItem: .close, primaryAction: UIAction { [weak self] _ in self?.close() })
+ if #unavailable(iOS 26.0) {
+ // Before iOS 26 a navigation item has no subtitle, so the count sits under the title by hand.
+ titleLabel.font = .preferredFont(forTextStyle: .headline)
+ counterLabel.font = .preferredFont(forTextStyle: .caption1)
+ counterLabel.textColor = .secondaryLabel
+ for label in [titleLabel, counterLabel] {
+ label.textAlignment = .center
+ label.adjustsFontForContentSizeCategory = true
+ label.lineBreakMode = .byTruncatingMiddle
+ }
+ let titles = UIStackView(arrangedSubviews: [titleLabel, counterLabel])
+ titles.axis = .vertical
+ titles.alignment = .center
+ navigationItem.titleView = titles
+ }
+ toolbarItems = [.flexibleSpace(), saveItem, shareItem]
+ setContentScrollView(pager, for: .top)
+ setContentScrollView(pager, for: .bottom)
+ }
+
+ /// Shows or hides the bars through UIKit, which also moves them out of an iPhone Duo's side bar.
+ private func setBarsVisible(_ visible: Bool) {
+ navigationController?.setNavigationBarHidden(!visible, animated: true)
+ navigationController?.setToolbarHidden(!visible, animated: true)
+ }
+
+ private func updateTitle() {
+ updateActions()
+ let title = titles[safe: currentIndex]
+ let counter = titles.count > 1 ? "\(currentIndex + 1) of \(titles.count)" : nil
+ navigationItem.title = title
+ if #available(iOS 26.0, *) { navigationItem.subtitle = counter }
+ titleLabel.text = title
+ counterLabel.text = counter
+ counterLabel.isHidden = counter == nil
+ }
+
+ override func viewDidLayoutSubviews() {
+ super.viewDidLayoutSubviews()
+ backdrop.frame = view.bounds
+ guard view.bounds.size != laidOutSize else { return }
+ laidOutSize = view.bounds.size
+ // Resizing the pager scrolls it; that must not move the reader to another page.
+ isLayingOut = true
+ defer { isLayingOut = false }
+ // Pages sit a gap apart, like Photos, so the pager is a gap wider than the screen.
+ let pageWidth = view.bounds.width + Self.pageGap
+ pager.frame = CGRect(x: -Self.pageGap / 2, y: 0, width: pageWidth, height: view.bounds.height)
+ for (index, page) in pages.enumerated() {
+ page.transform = .identity
+ page.frame = CGRect(x: CGFloat(index) * pageWidth + Self.pageGap / 2, y: 0,
+ width: view.bounds.width, height: view.bounds.height)
+ }
+ pager.contentSize = CGSize(width: pageWidth * CGFloat(pages.count), height: view.bounds.height)
+ pager.contentOffset = CGPoint(x: CGFloat(currentIndex) * pageWidth, y: 0)
+ }
+
+ func setImage(_ image: UIImage, at index: Int, full: Bool) {
+ guard let page = pages[safe: index] else { return }
+ page.setImage(image, full: full)
+ updateActions()
+ }
+
+ func setLoading(at index: Int) { pages[safe: index]?.setLoading() }
+
+ func release(at index: Int, placeholder: UIImage?) {
+ pages[safe: index]?.release(to: placeholder)
+ updateActions()
+ }
+
+ func setFailed(at index: Int, retryable: Bool) {
+ pages[safe: index]?.setFailed(retryable: retryable)
+ updateActions()
+ }
+
+ /// Save and Share act on the original, so they wait until the current page shows it.
+ private func updateActions() {
+ let ready = pages[safe: currentIndex]?.isFull == true
+ saveItem.isEnabled = ready
+ shareItem.isEnabled = ready
+ }
+
+ // MARK: Transitions
+
+ private var reduceMotion: Bool { UIAccessibility.isReduceMotionEnabled }
+
+ private func visibleSource(_ index: Int) -> UIView? {
+ guard !reduceMotion, let source = sourceView(index), source.window === view.window, !source.isHidden else { return nil }
+ let frame = source.convert(source.bounds, to: view)
+ guard frame.width > 1, frame.height > 1, view.bounds.intersects(frame) else { return nil }
+ return source
+ }
+
+ private static func cornerRadius(of view: UIView) -> CGFloat {
+ var queue = [view]
+ var depth = 0
+ while !queue.isEmpty, depth < 4 {
+ for candidate in queue where candidate.layer.cornerRadius > 0 { return candidate.layer.cornerRadius }
+ queue = queue.flatMap(\.subviews)
+ depth += 1
+ }
+ return 0
+ }
+
+ private func makeTransitionView(_ image: UIImage, frame: CGRect) -> UIImageView {
+ let transition = UIImageView(image: image)
+ transition.contentMode = .scaleAspectFill
+ transition.clipsToBounds = true
+ transition.frame = frame
+ view.addSubview(transition)
+ return transition
+ }
+
+ /// Returns once the open transition has finished and the thumbnails are on screen again.
+ func untilRevealed() async {
+ guard !revealed else { return }
+ await withCheckedContinuation { revealWaiters.append($0) }
+ }
+
+ func animateIn() {
+ view.layoutIfNeeded()
+ let page = pages[currentIndex]
+ let reveal = { [weak self] in
+ guard let self else { return }
+ self.pager.isHidden = false
+ self.transitioning = false
+ self.revealed = true
+ for waiter in self.revealWaiters { waiter.resume() }
+ self.revealWaiters.removeAll()
+ self.setNeedsStatusBarAppearanceUpdate()
+ UIAccessibility.post(notification: .screenChanged, argument: page.imageView)
+ if self.closeRequested { self.close() }
+ }
+ guard let image = page.image, let source = visibleSource(currentIndex) else {
+ pager.isHidden = false
+ pager.alpha = 0
+ setBarsVisible(true)
+ UIView.animate(withDuration: reduceMotion ? 0.2 : 0.25, animations: {
+ self.backdrop.alpha = 1
+ self.pager.alpha = 1
+ }, completion: { _ in reveal() })
+ return
+ }
+ let transition = makeTransitionView(image, frame: source.convert(source.bounds, to: view))
+ transition.layer.cornerRadius = Self.cornerRadius(of: source)
+ let sourceAlpha = source.alpha
+ source.alpha = 0
+ let target = page.fittedFrame(in: view)
+ let animator = UIViewPropertyAnimator(duration: 0.42, dampingRatio: 0.86) {
+ transition.frame = target
+ transition.layer.cornerRadius = 0
+ self.backdrop.alpha = 1
+ }
+ setBarsVisible(true)
+ animator.addCompletion { _ in
+ source.alpha = sourceAlpha
+ transition.removeFromSuperview()
+ reveal()
+ }
+ animator.startAnimation()
+ }
+
+ /// Closes back into the current page's thumbnail, or away in the drag's direction when it is gone.
+ func close(velocity: CGPoint = .zero) {
+ closeRequested = true
+ guard !transitioning, !closing else { return }
+ closing = true
+ transitioning = true
+ setNeedsStatusBarAppearanceUpdate()
+ setBarsVisible(false)
+ let page = pages[currentIndex]
+ guard let image = page.image else {
+ UIView.animate(withDuration: 0.2, animations: { self.view.alpha = 0 }, completion: { _ in self.finishClose() })
+ return
+ }
+ let transition = makeTransitionView(image, frame: page.imageView.convert(page.imageView.bounds, to: view))
+ pager.isHidden = true
+ guard let source = visibleSource(currentIndex) else {
+ let direction: CGFloat = velocity.y < 0 ? -1 : 1
+ let animator = UIViewPropertyAnimator(duration: 0.3, curve: .easeIn) {
+ transition.center.y += direction * self.view.bounds.height
+ self.backdrop.alpha = 0
+ if self.reduceMotion { transition.alpha = 0 }
+ }
+ animator.addCompletion { _ in self.finishClose() }
+ animator.startAnimation()
+ return
+ }
+ let sourceAlpha = source.alpha
+ source.alpha = 0
+ let target = source.convert(source.bounds, to: view)
+ let radius = Self.cornerRadius(of: source)
+ let speed = hypot(velocity.x, velocity.y)
+ let distance = hypot(target.midX - transition.center.x, target.midY - transition.center.y)
+ let initial = distance > 0 ? CGVector(dx: velocity.x / distance, dy: velocity.y / distance) : .zero
+ let timing = UISpringTimingParameters(dampingRatio: 0.88, initialVelocity: speed > 0 ? initial : .zero)
+ let animator = UIViewPropertyAnimator(duration: 0.4, timingParameters: timing)
+ animator.addAnimations {
+ transition.frame = target
+ transition.layer.cornerRadius = radius
+ self.backdrop.alpha = 0
+ }
+ animator.addCompletion { _ in
+ source.alpha = sourceAlpha
+ self.finishClose()
+ }
+ animator.startAnimation()
+ }
+
+ private func finishClose() {
+ presentingViewController?.dismiss(animated: false) { [onDismissed] in onDismissed() }
+ }
+
+ // MARK: Gestures
+
+ func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
+ guard gestureRecognizer === dismissPan else { return true }
+ guard !transitioning, !pager.isDragging, !pager.isDecelerating,
+ let page = pages[safe: currentIndex], !page.isZoomed
+ else { return false }
+ let velocity = dismissPan.velocity(in: view)
+ return abs(velocity.y) > abs(velocity.x)
+ }
+
+ @objc private func handleDismissPan(_ gesture: UIPanGestureRecognizer) {
+ let page = pages[currentIndex]
+ let translation = gesture.translation(in: view)
+ switch gesture.state {
+ case .began:
+ chromeHiddenBeforeDrag = chromeHidden
+ dragAnchor = gesture.location(in: page)
+ setChromeHidden(true)
+ case .changed:
+ // Shrink around the finger, as Photos does, so the touched spot stays under it.
+ let progress = min(1, abs(translation.y) / (view.bounds.height / 2))
+ let scale = 1 - 0.3 * progress
+ let offset = CGPoint(x: dragAnchor.x - page.bounds.midX, y: dragAnchor.y - page.bounds.midY)
+ page.transform = CGAffineTransform(translationX: translation.x + (1 - scale) * offset.x,
+ y: translation.y + (1 - scale) * offset.y).scaledBy(x: scale, y: scale)
+ backdrop.alpha = 1 - progress
+ case .ended, .cancelled, .failed:
+ let velocity = gesture.velocity(in: view)
+ let flung = abs(velocity.y) > 800 && velocity.y * translation.y > 0
+ if gesture.state == .ended, flung || abs(translation.y) > 120 {
+ close(velocity: velocity)
+ } else {
+ UIViewPropertyAnimator(duration: 0.35, dampingRatio: 0.8) {
+ page.transform = .identity
+ self.backdrop.alpha = 1
+ }.startAnimation()
+ setChromeHidden(chromeHiddenBeforeDrag)
+ }
+ default:
+ break
+ }
+ }
+
+ @objc private func handleDoubleTap(_ gesture: UITapGestureRecognizer) {
+ guard !transitioning, let page = pages[safe: currentIndex] else { return }
+ page.toggleZoom(at: gesture.location(in: page))
+ }
+
+ @objc private func handleSingleTap() {
+ guard !transitioning else { return }
+ setChromeHidden(!chromeHidden)
+ }
+
+ private func setChromeHidden(_ hidden: Bool) {
+ guard chromeHidden != hidden else { return }
+ chromeHidden = hidden
+ setBarsVisible(!hidden)
+ UIView.animate(withDuration: 0.2) { self.setNeedsStatusBarAppearanceUpdate() }
+ setNeedsUpdateOfHomeIndicatorAutoHidden()
+ }
+
+ func scrollViewDidScroll(_ scrollView: UIScrollView) {
+ guard scrollView === pager, !transitioning, !isLayingOut, pager.bounds.width > 0 else { return }
+ let index = Int((pager.contentOffset.x / pager.bounds.width).rounded())
+ guard pages.indices.contains(index), index != currentIndex else { return }
+ pages[currentIndex].resetZoom(animated: false)
+ currentIndex = index
+ updateTitle()
+ onPageChange(index)
+ }
+
+ private func scroll(to index: Int) {
+ guard pages.indices.contains(index), !transitioning else { return }
+ pager.setContentOffset(CGPoint(x: CGFloat(index) * pager.bounds.width, y: 0), animated: !reduceMotion)
+ }
+
+ // MARK: Share, keyboard and accessibility
+
+ private func save() {
+ let image = pages[currentIndex].isFull ? pages[currentIndex].image : nil
+ // Original bytes keep the format and metadata; an SVG only has its rendered image. The copy
+ // belongs to this save, since closing the viewer deletes its files before Photos may read them.
+ let original = fileForPage(currentIndex).flatMap { file -> URL? in
+ guard file.pathExtension.lowercased() != "svg", let source = CGImageSourceCreateWithURL(file as CFURL, nil), CGImageSourceGetCount(source) > 0 else { return nil }
+ let copy = FileManager.default.temporaryDirectory.appendingPathComponent("t3-save-\(UUID().uuidString)")
+ .appendingPathComponent(file.lastPathComponent)
+ do {
+ try FileManager.default.createDirectory(at: copy.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try FileManager.default.copyItem(at: file, to: copy)
+ return copy
+ } catch {
+ return nil
+ }
+ }
+ guard original != nil || image != nil else { return }
+ let cleanUp = { if let original { try? FileManager.default.removeItem(at: original.deletingLastPathComponent()) } }
+ PHPhotoLibrary.requestAuthorization(for: .addOnly) { [weak self] status in
+ guard status == .authorized || status == .limited else {
+ cleanUp()
+ DispatchQueue.main.async { self?.showSaveError("Allow T3 Code to add photos in Settings.") }
+ return
+ }
+ PHPhotoLibrary.shared().performChanges({
+ if let original {
+ PHAssetCreationRequest.forAsset().addResource(with: .photo, fileURL: original, options: nil)
+ } else if let image {
+ PHAssetChangeRequest.creationRequestForAsset(from: image)
+ }
+ }, completionHandler: { saved, error in
+ cleanUp()
+ DispatchQueue.main.async {
+ if saved {
+ self?.confirmSaved()
+ } else {
+ self?.showSaveError(error?.localizedDescription ?? "Photos could not save this image.")
+ }
+ }
+ })
+ }
+ }
+
+ private func confirmSaved() {
+ UINotificationFeedbackGenerator().notificationOccurred(.success)
+ UIAccessibility.post(notification: .announcement, argument: "Saved to Photos")
+ saveItem.image = UIImage(systemName: "checkmark")
+ DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) { [weak self] in
+ self?.saveItem.image = UIImage(systemName: "square.and.arrow.down")
+ }
+ }
+
+ private func showSaveError(_ message: String) {
+ let alert = UIAlertController(title: "Could not save image", message: message, preferredStyle: .alert)
+ alert.addAction(UIAlertAction(title: "OK", style: .default))
+ present(alert, animated: true)
+ }
+
+ private func share() {
+ let page = pages[currentIndex]
+ let item: Any? = fileForPage(currentIndex) ?? (page.isFull ? page.image : nil)
+ guard let item else { return }
+ let sheet = UIActivityViewController(activityItems: [item], applicationActivities: nil)
+ sheet.popoverPresentationController?.sourceItem = shareItem
+ present(sheet, animated: true)
+ }
+
+ override var canBecomeFirstResponder: Bool { true }
+
+ override func viewDidAppear(_ animated: Bool) {
+ super.viewDidAppear(animated)
+ becomeFirstResponder()
+ }
+
+ override var keyCommands: [UIKeyCommand]? {
+ [
+ UIKeyCommand(input: UIKeyCommand.inputEscape, modifierFlags: [], action: #selector(handleEscape)),
+ UIKeyCommand(input: UIKeyCommand.inputLeftArrow, modifierFlags: [], action: #selector(handlePrevious)),
+ UIKeyCommand(input: UIKeyCommand.inputRightArrow, modifierFlags: [], action: #selector(handleNext)),
+ ]
+ }
+
+ @objc private func handleEscape() { close() }
+ @objc private func handlePrevious() { scroll(to: currentIndex - 1) }
+ @objc private func handleNext() { scroll(to: currentIndex + 1) }
+
+ override func accessibilityPerformEscape() -> Bool {
+ close()
+ return true
+ }
+
+ override func accessibilityScroll(_ direction: UIAccessibilityScrollDirection) -> Bool {
+ switch direction {
+ case .left: scroll(to: currentIndex + 1)
+ case .right: scroll(to: currentIndex - 1)
+ default: return false
+ }
+ UIAccessibility.post(notification: .pageScrolled, argument: counterLabel.text)
+ return true
+ }
+}
diff --git a/apps/mobile/modules/t3-native-controls/ios/T3NativePresentation.swift b/apps/mobile/modules/t3-native-controls/ios/T3NativePresentation.swift
index 932ed1d0a3e5e..3b43334b1262d 100644
--- a/apps/mobile/modules/t3-native-controls/ios/T3NativePresentation.swift
+++ b/apps/mobile/modules/t3-native-controls/ios/T3NativePresentation.swift
@@ -7,21 +7,28 @@ final class T3PresentationSources {
init(_ view: UIView) { self.view = view }
}
- private var entries: [String: Entry] = [:]
+ /// The same file embedded twice registers twice; removing one copy keeps the other.
+ private var entries: [String: [Entry]] = [:]
func register(_ view: UIView, identifier: String) {
- entries[identifier] = Entry(view)
+ var list = (entries[identifier] ?? []).filter { $0.view != nil && $0.view !== view }
+ list.append(Entry(view))
+ entries[identifier] = list
}
func remove(_ view: UIView, identifier: String) {
- if entries[identifier]?.view == nil || entries[identifier]?.view === view {
- entries.removeValue(forKey: identifier)
- }
+ let list = (entries[identifier] ?? []).filter { $0.view != nil && $0.view !== view }
+ entries[identifier] = list.isEmpty ? nil : list
}
func view(for identifier: String) -> UIView? {
- // Use the child bounds, not the wrapper's potentially stretched layout bounds.
- entries[identifier]?.view?.subviews.first
+ let views = (entries[identifier] ?? []).compactMap(\.view)
+ // Prefer an on-screen copy, the latest first; use the child bounds, not the wrapper's stretched ones.
+ let source = views.last(where: { view in
+ guard let window = view.window else { return false }
+ return window.bounds.intersects(view.convert(view.bounds, to: window))
+ }) ?? views.last
+ return source?.subviews.first
}
}
diff --git a/apps/mobile/modules/t3-native-controls/ios/T3ScrollEdgeBleedView.swift b/apps/mobile/modules/t3-native-controls/ios/T3ScrollEdgeBleedView.swift
index 924fa4ddeb14a..6732f2dae2f18 100644
--- a/apps/mobile/modules/t3-native-controls/ios/T3ScrollEdgeBleedView.swift
+++ b/apps/mobile/modules/t3-native-controls/ios/T3ScrollEdgeBleedView.swift
@@ -4,8 +4,9 @@ import UIKit
/// Wraps a screen's header scroll view. Where a column pads its content away from the iPhone Duo's
/// vertical bar, this widens the scroll view under the bar, like the system apps' lists. UIKit
/// draws the header's scroll-edge effect inside the scroll view, so the blur reaches the bar while
-/// the content stays in the safe area. Everything happens in UIKit layout, so folds move the blur
-/// and the content together.
+/// the content stays in the safe area, and the scroll indicator runs along the screen edge past the
+/// bar, as in Messages. Everything happens in UIKit layout, so folds move the blur and the content
+/// together.
final class T3ScrollEdgeBleedView: ExpoView {
// Fabric recycles scroll views, so everything changed here is put back before this view leaves
// the window, which unmounting does before any recycling.
@@ -19,7 +20,6 @@ final class T3ScrollEdgeBleedView: ExpoView {
/// React Native's clipping, saved while bleeding. React Native only rewrites it when the
/// `overflow` style changes, so it stays off while bleeding.
private var containerClipped: Bool?
- private var indicatorObservations: [NSKeyValueObservation] = []
required init(appContext: AppContext? = nil) {
super.init(appContext: appContext)
@@ -137,31 +137,9 @@ final class T3ScrollEdgeBleedView: ExpoView {
containerClipped = containerClipped ?? true
container.layer.masksToBounds = false
}
- applyIndicatorInset()
- // React Native rewrites every indicator inset when its `scrollIndicatorInsets` prop changes,
- // which the keyboard-aware list animates while a reply streams; put the inset back at once.
- if bleeding, indicatorObservations.isEmpty {
- let keyPaths = [\UIScrollView.verticalScrollIndicatorInsets, \.scrollIndicatorInsets]
- indicatorObservations = keyPaths.map {
- scrollView.observe($0) { [weak self] _, _ in
- MainActor.assumeIsolated { self?.applyIndicatorInset() }
- }
- }
- } else if !bleeding {
- indicatorObservations = []
- }
applied = bleeding
}
- private func applyIndicatorInset() {
- guard let scrollView else { return }
- var indicators = scrollView.verticalScrollIndicatorInsets
- if indicators.right != bleed.right {
- indicators.right = bleed.right
- scrollView.verticalScrollIndicatorInsets = indicators
- }
- }
-
private func detach() {
guard scrollView != nil else { return }
bleed = .zero
diff --git a/apps/mobile/modules/t3-native-controls/ios/T3SidebarTabBarView.swift b/apps/mobile/modules/t3-native-controls/ios/T3SidebarTabBarView.swift
index 243490678c530..78fd2ec1fe379 100644
--- a/apps/mobile/modules/t3-native-controls/ios/T3SidebarTabBarView.swift
+++ b/apps/mobile/modules/t3-native-controls/ios/T3SidebarTabBarView.swift
@@ -56,6 +56,9 @@ final class T3SidebarTabBarView: ExpoView, UITabBarDelegate {
composeButton.isHidden = !showsCompose
tabBarTrailing.constant = showsCompose ? (compact ? -64 : -76) : 0
setNeedsLayout()
+ // JS moves this view's edge by the same amount, so the bar keeps its frame and won't lay
+ // itself out; compose is placed only from that layout.
+ tabBar.setNeedsLayout()
}
}
var appearance = "light" {
diff --git a/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/ReviewDiffCanvasDrawing.kt b/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/ReviewDiffCanvasDrawing.kt
index 7a1225cd392bf..2f1e4d9fd4a43 100644
--- a/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/ReviewDiffCanvasDrawing.kt
+++ b/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/ReviewDiffCanvasDrawing.kt
@@ -402,7 +402,7 @@ internal class ReviewDiffCanvasDrawing(context: Context) {
@Suppress("LongParameterList")
fun drawCode(
canvas: Canvas,
- content: String,
+ row: DiffRow,
tokens: List?,
codeX: Float,
baseline: Float,
@@ -417,12 +417,16 @@ internal class ReviewDiffCanvasDrawing(context: Context) {
canvas.restore()
return
}
- val runs = if (tokens.isNullOrEmpty()) listOf(DiffToken(content, null, 0)) else tokens
+ val runs = if (tokens.isNullOrEmpty()) listOf(DiffToken(row.content, null, 0)) else tokens
var line = 0
var x = codeX
var column = 0
- runs.forEach { run ->
- configureCodePaint(run.color ?: theme.text, run.fontStyle, style)
+ splitAtNote(runs, row.noteStart).forEach { (run, note) ->
+ configureCodePaint(
+ if (note) theme.warningText else run.color ?: theme.text,
+ run.fontStyle,
+ style,
+ )
var start = 0
while (start < run.content.length) {
while (line + 1 < lines.starts.size && lines.starts[line + 1] <= column + start) {
@@ -434,8 +438,10 @@ internal class ReviewDiffCanvasDrawing(context: Context) {
if (lineBaseline + textPaint.fontMetrics.descent >= canvas.clipBounds.top &&
lineBaseline + textPaint.fontMetrics.ascent <= canvas.clipBounds.bottom
) {
+ val segmentWidth = textPaint.measureText(run.content, start, end)
+ fillNote(canvas, note, x, x + segmentWidth, lineBaseline)
canvas.drawText(run.content, start, end, x, lineBaseline, textPaint)
- x += textPaint.measureText(run.content, start, end)
+ x += segmentWidth
}
start = end
}
@@ -443,6 +449,21 @@ internal class ReviewDiffCanvasDrawing(context: Context) {
}
}
+ fun noticeColor(row: DiffRow): Int =
+ if (row.tone == "warning") theme.warningText else theme.mutedText
+
+ fun noticeFill(row: DiffRow): Int =
+ if (row.tone == "warning") theme.warningBackground else theme.background
+
+ /** Fills behind a segment of a cut line's note; other segments are left alone. */
+ private fun fillNote(canvas: Canvas, note: Boolean, left: Float, right: Float, baseline: Float) {
+ if (!note) return
+ backgroundPaint.color = theme.warningBackground
+ val metrics = textPaint.fontMetrics
+ val top = baseline + metrics.ascent
+ canvas.drawRect(left, top, right, baseline + metrics.descent, backgroundPaint)
+ }
+
fun drawFileHeaderPathScrollFades(
canvas: Canvas,
pathRect: RectF,
@@ -532,3 +553,24 @@ private object ReviewDiffTypefaces {
else -> regular
}
}
+
+/** Splits color runs where a cut line's note starts; the flag marks the note's runs. */
+private fun splitAtNote(runs: List, noteStart: Int?): List> {
+ if (noteStart == null) return runs.map { it to false }
+ return buildList {
+ var offset = 0
+ for (run in runs) {
+ val end = offset + run.content.length
+ when {
+ end <= noteStart -> add(run to false)
+ offset >= noteStart -> add(run to true)
+ else -> {
+ val cut = noteStart - offset
+ add(run.copy(content = run.content.substring(0, cut)) to false)
+ add(run.copy(content = run.content.substring(cut)) to true)
+ }
+ }
+ offset = end
+ }
+ }
+}
diff --git a/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/ReviewDiffCodeLayout.kt b/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/ReviewDiffCodeLayout.kt
index 770bc656de569..83f32788e8ab8 100644
--- a/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/ReviewDiffCodeLayout.kt
+++ b/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/ReviewDiffCodeLayout.kt
@@ -182,6 +182,20 @@ internal class CodeLayoutCache {
}
}
}
+ row.noteStart?.takeIf { it in 0 until text.length }?.let { start ->
+ text.setSpan(
+ ForegroundColorSpan(theme.warningText),
+ start,
+ text.length,
+ Spanned.SPAN_EXCLUSIVE_EXCLUSIVE,
+ )
+ text.setSpan(
+ BackgroundColorSpan(theme.warningBackground),
+ start,
+ text.length,
+ Spanned.SPAN_EXCLUSIVE_EXCLUSIVE,
+ )
+ }
return text
}
}
diff --git a/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffModule.kt b/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffModule.kt
index 63ab13dde3d12..03609e3658e84 100644
--- a/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffModule.kt
+++ b/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffModule.kt
@@ -4,6 +4,16 @@ import expo.modules.kotlin.Promise
import expo.modules.kotlin.modules.Module
import expo.modules.kotlin.modules.ModuleDefinition
+private val REVIEW_DIFF_EVENTS = arrayOf(
+ "onDebug",
+ "onVisibleFileChange",
+ "onToggleFile",
+ "onToggleViewedFile",
+ "onPressLine",
+ "onToggleComment",
+ "onPressNotice",
+)
+
class T3ReviewDiffModule : Module() {
override fun definition() = ModuleDefinition {
Name("T3ReviewDiffSurface")
@@ -54,14 +64,7 @@ class T3ReviewDiffModule : Module() {
view.setInitialFileId(fileId)
}
- Events(
- "onDebug",
- "onVisibleFileChange",
- "onToggleFile",
- "onToggleViewedFile",
- "onPressLine",
- "onToggleComment",
- )
+ Events(REVIEW_DIFF_EVENTS)
AsyncFunction("scrollToFile") { view: T3ReviewDiffView, fileId: String, animated: Boolean ->
view.scrollToFile(fileId, animated)
diff --git a/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffView.kt b/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffView.kt
index 54ff86c611a8e..91bb6719ed8fa 100644
--- a/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffView.kt
+++ b/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffView.kt
@@ -31,6 +31,7 @@ class T3ReviewDiffView(context: Context, appContext: AppContext) : ExpoView(cont
private val onToggleViewedFile by EventDispatcher()
private val onPressLine by EventDispatcher()
private val onToggleComment by EventDispatcher()
+ private val onPressNotice by EventDispatcher()
private var rows: List = emptyList()
private var visibleRows: List = emptyList()
private var visibleRowIndices = IntArray(0)
@@ -432,6 +433,9 @@ class T3ReviewDiffView(context: Context, appContext: AppContext) : ExpoView(cont
}
}
"comment" -> onToggleComment(mapOf("commentId" to row.id))
+ "notice" -> if (gesture == "tap" && row.actionable) {
+ onPressNotice(mapOf("rowId" to row.id, "fileId" to row.resolvedFileId))
+ }
"line" -> {
val payload = mutableMapOf(
"rowId" to row.id,
@@ -534,7 +538,13 @@ internal data class DiffRow(
val wordDiffRanges: List,
val commentText: String,
val commentRangeLabel: String,
- val commentSectionTitle: String
+ val commentSectionTitle: String,
+ /** A notice drawn in the warning colors. */
+ val tone: String = "",
+ /** A notice that reports taps through `onPressNotice`. */
+ val actionable: Boolean = false,
+ /** Where a cut line's note starts in `content`. */
+ val noteStart: Int? = null
) {
val resolvedFileId: String get() = fileId.ifEmpty { id }
val isPlainAscii: Boolean = content.all { it in ' '..'~' }
@@ -564,7 +574,9 @@ internal data class DiffTheme(
val addBar: Int,
val deleteBar: Int,
val addText: Int,
- val deleteText: Int
+ val deleteText: Int,
+ val warningText: Int,
+ val warningBackground: Int
) {
companion object {
fun fallback(scheme: String): DiffTheme = if (scheme == "dark") {
@@ -582,6 +594,8 @@ internal data class DiffTheme(
deleteBar = Color.rgb(255, 46, 63),
addText = Color.rgb(94, 204, 113),
deleteText = Color.rgb(255, 103, 98),
+ warningText = Color.rgb(250, 204, 102),
+ warningBackground = Color.rgb(51, 38, 13),
)
} else {
DiffTheme(
@@ -598,6 +612,8 @@ internal data class DiffTheme(
deleteBar = Color.rgb(213, 44, 54),
addText = Color.rgb(25, 130, 67),
deleteText = Color.rgb(190, 38, 48),
+ warningText = Color.rgb(140, 92, 0),
+ warningBackground = Color.rgb(255, 245, 214),
)
}
@@ -617,6 +633,8 @@ internal data class DiffTheme(
deleteBar = color(json, "deleteBar", fallback.deleteBar),
addText = color(json, "addText", fallback.addText),
deleteText = color(json, "deleteText", fallback.deleteText),
+ warningText = color(json, "warningText", fallback.warningText),
+ warningBackground = color(json, "warningBackground", fallback.warningBackground),
)
} catch (_: Exception) {
fallback
@@ -1189,7 +1207,7 @@ private class DiffCanvasView(context: Context) : View(context) {
}
private fun drawNoticeRow(canvas: Canvas, row: DiffRow, top: Int, bottom: Int) {
- fill(canvas, theme.background, 0f, top.toFloat(), width.toFloat(), bottom.toFloat())
+ fill(canvas, drawing.noticeFill(row), 0f, top.toFloat(), width.toFloat(), bottom.toFloat())
val iconSize = 16f * density
val iconRect = RectF(
style.fileHeaderHorizontalPaddingPx + 2f * density,
@@ -1197,10 +1215,10 @@ private class DiffCanvasView(context: Context) : View(context) {
style.fileHeaderHorizontalPaddingPx + 2f * density + iconSize,
(top + bottom + iconSize) / 2f,
)
- drawing.drawNoticeIcon(canvas, iconRect, theme.mutedText)
+ drawing.drawNoticeIcon(canvas, iconRect, drawing.noticeColor(row))
drawing.configureUiPaint(
paint = textPaint,
- color = theme.mutedText,
+ color = drawing.noticeColor(row),
size = style.fileHeaderSubtextFontSizePx,
weight = style.fileHeaderSubtextFontWeight,
)
@@ -1313,7 +1331,7 @@ private class DiffCanvasView(context: Context) : View(context) {
drawing.configureCodePaint(theme.text, 0, style)
drawing.drawWordDiffRanges(canvas, row, codeX, top, firstLineBottom, lines)
val baseline = lines.baseline(top, firstLineBottom, textPaint)
- drawing.drawCode(canvas, row.content, tokensByRowId[row.id], codeX, baseline, style, lines)
+ drawing.drawCode(canvas, row, tokensByRowId[row.id], codeX, baseline, style, lines)
}
drawLineNumber(canvas, row, top, firstLineBottom)
@@ -1488,6 +1506,9 @@ private fun parseRows(value: String, isCancelled: () -> Boolean): List
commentText = row.optString("commentText"),
commentRangeLabel = row.optString("commentRangeLabel"),
commentSectionTitle = row.optString("commentSectionTitle"),
+ tone = row.optString("tone"),
+ actionable = row.optBoolean("actionable"),
+ noteStart = row.optNullableInt("noteStart"),
)
}
} catch (_: Exception) {
diff --git a/apps/mobile/modules/t3-review-diff/ios/ReviewDiffCodeLayout.swift b/apps/mobile/modules/t3-review-diff/ios/ReviewDiffCodeLayout.swift
index 7f96dc17a25e6..4c60b20c1add5 100644
--- a/apps/mobile/modules/t3-review-diff/ios/ReviewDiffCodeLayout.swift
+++ b/apps/mobile/modules/t3-review-diff/ios/ReviewDiffCodeLayout.swift
@@ -16,6 +16,13 @@ struct ReviewDiffCodeLineStarts: RandomAccessCollection {
/// ASCII uses fixed-pitch columns. TextKit handles shaping, tabs, and Unicode highlights.
/// Pass `unboundedWidth` to lay a row out on one line for horizontal scrolling.
+/** A cut line's note, drawn in its own colors. */
+struct ReviewDiffCodeNote {
+ let range: NSRange
+ let color: UIColor
+ let background: UIColor
+}
+
final class ReviewDiffCodeLayout: NSObject {
static let unboundedWidth = CGFloat.greatestFiniteMagnitude
@@ -84,7 +91,14 @@ final class ReviewDiffCodeLayout: NSObject {
return layout
}
- func decorate(text: NSAttributedString, highlights: [NSRange], color: UIColor, version: Int) {
+ // A cut line's note is not code, so it takes the warning colors over any token color.
+ func decorate(
+ text: NSAttributedString,
+ highlights: [NSRange],
+ color: UIColor,
+ note: ReviewDiffCodeNote? = nil,
+ version: Int
+ ) {
guard usesNativeLayout else { return }
let layout = nativeLayout()
guard layout.decorationVersion != version else { return }
@@ -105,6 +119,13 @@ final class ReviewDiffCodeLayout: NSObject {
storage.addAttribute(.backgroundColor, value: color, range: intersection)
}
}
+ if let note {
+ let intersection = NSIntersectionRange(note.range, fullRange)
+ if intersection.length > 0 {
+ storage.addAttribute(.foregroundColor, value: note.color, range: intersection)
+ storage.addAttribute(.backgroundColor, value: note.background, range: intersection)
+ }
+ }
storage.endEditing()
layout.decorationVersion = version
}
diff --git a/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffModule.swift b/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffModule.swift
index 2fcb8a4801809..d1be707b0d9d6 100644
--- a/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffModule.swift
+++ b/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffModule.swift
@@ -88,6 +88,7 @@ public class T3ReviewDiffModule: Module {
"onToggleViewedFile",
"onPressLine",
"onToggleComment",
+ "onPressNotice",
"onPullToRefresh"
)
diff --git a/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffView.swift b/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffView.swift
index a80a391380750..7fe4a068f9bbb 100644
--- a/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffView.swift
+++ b/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffView.swift
@@ -19,6 +19,12 @@ private struct ReviewDiffNativeRow: Decodable, Sendable {
let commentText: String?
let commentRangeLabel: String?
let commentSectionTitle: String?
+ /** A notice drawn in the warning colors. */
+ let tone: String?
+ /** A notice that reports taps through `onPressNotice`. */
+ let actionable: Bool?
+ /** Where a cut line's note starts in `content`, in UTF-16 units. */
+ let noteStart: Int?
}
private struct ReviewDiffNativeWordDiffRange: Decodable, Sendable {
@@ -52,6 +58,8 @@ private struct ReviewDiffNativeThemePayload: Decodable {
let deleteBar: String?
let addText: String?
let deleteText: String?
+ let warningText: String?
+ let warningBackground: String?
}
private struct ReviewDiffNativeTheme {
@@ -68,6 +76,8 @@ private struct ReviewDiffNativeTheme {
let deleteBar: UIColor
let addText: UIColor
let deleteText: UIColor
+ let warningText: UIColor
+ let warningBackground: UIColor
static func resolve(_ scheme: String) -> ReviewDiffNativeTheme {
resolve(scheme, payload: nil)
@@ -95,7 +105,10 @@ private struct ReviewDiffNativeTheme {
addBar: UIColor(reviewDiffHex: payload.addBar) ?? fallback.addBar,
deleteBar: UIColor(reviewDiffHex: payload.deleteBar) ?? fallback.deleteBar,
addText: UIColor(reviewDiffHex: payload.addText) ?? fallback.addText,
- deleteText: UIColor(reviewDiffHex: payload.deleteText) ?? fallback.deleteText
+ deleteText: UIColor(reviewDiffHex: payload.deleteText) ?? fallback.deleteText,
+ warningText: UIColor(reviewDiffHex: payload.warningText) ?? fallback.warningText,
+ warningBackground: UIColor(reviewDiffHex: payload.warningBackground)
+ ?? fallback.warningBackground
)
}
@@ -114,7 +127,9 @@ private struct ReviewDiffNativeTheme {
addBar: UIColor(red: 0.02, green: 0.82, blue: 0.54, alpha: 1),
deleteBar: UIColor(red: 1.00, green: 0.36, blue: 0.50, alpha: 1),
addText: UIColor(red: 0.10, green: 0.84, blue: 0.56, alpha: 1),
- deleteText: UIColor(red: 1.00, green: 0.38, blue: 0.52, alpha: 1)
+ deleteText: UIColor(red: 1.00, green: 0.38, blue: 0.52, alpha: 1),
+ warningText: UIColor(red: 0.98, green: 0.80, blue: 0.40, alpha: 1),
+ warningBackground: UIColor(red: 0.20, green: 0.15, blue: 0.05, alpha: 1)
)
}
@@ -131,7 +146,9 @@ private struct ReviewDiffNativeTheme {
addBar: UIColor(red: 0.02, green: 0.80, blue: 0.52, alpha: 1),
deleteBar: UIColor(red: 1.00, green: 0.34, blue: 0.48, alpha: 1),
addText: UIColor(red: 0.00, green: 0.56, blue: 0.34, alpha: 1),
- deleteText: UIColor(red: 0.90, green: 0.10, blue: 0.24, alpha: 1)
+ deleteText: UIColor(red: 0.90, green: 0.10, blue: 0.24, alpha: 1),
+ warningText: UIColor(red: 0.55, green: 0.36, blue: 0.00, alpha: 1),
+ warningBackground: UIColor(red: 1.00, green: 0.96, blue: 0.84, alpha: 1)
)
}
}
@@ -350,6 +367,7 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
let onToggleViewedFile = EventDispatcher()
let onPressLine = EventDispatcher()
let onToggleComment = EventDispatcher()
+ let onPressNotice = EventDispatcher()
let onPullToRefresh = EventDispatcher()
private let pullRefreshControl = UIRefreshControl()
@@ -383,6 +401,9 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
contentView.onToggleComment = { [weak self] commentId in
self?.onToggleComment(["commentId": commentId])
}
+ contentView.onPressNotice = { [weak self] payload in
+ self?.onPressNotice(payload)
+ }
contentView.onDrawMetrics = { [weak self] metrics in
self?.emitDebug("draw-metrics", metrics)
}
@@ -1214,6 +1235,7 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate {
var onToggleViewedFile: ((String) -> Void)?
var onPressLine: (([String: Any]) -> Void)?
var onToggleComment: ((String) -> Void)?
+ var onPressNotice: (([String: Any]) -> Void)?
var onDrawMetrics: (([String: Any]) -> Void)?
private var stickyWidth: CGFloat {
@@ -1555,6 +1577,11 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate {
return
}
+ if row.kind == "notice", row.actionable == true {
+ onPressNotice?(["rowId": row.id, "fileId": resolvedFileId(for: row)])
+ return
+ }
+
if row.kind == "line" {
onPressLine?(linePressPayload(for: row, gesture: "tap"))
return
@@ -2200,7 +2227,8 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate {
return
}
- theme.background.setFill()
+ let warning = row.tone == "warning"
+ (warning ? theme.warningBackground : theme.background).setFill()
context.fill(rect)
let hairline = 1 / traitCollection.displayScale
@@ -2214,7 +2242,8 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate {
width: iconSize,
height: iconSize
)
- drawNoticeIcon(rect: iconRect, color: theme.mutedText)
+ let noticeColor = warning ? theme.warningText : theme.mutedText
+ drawNoticeIcon(rect: iconRect, color: noticeColor)
drawSingleLineText(
row.text ?? "",
@@ -2224,7 +2253,7 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate {
width: max(24, viewportWidth - iconRect.maxX - 10 - style.fileHeaderHorizontalPadding),
height: fileHeaderSubtextFont.lineHeight
),
- color: theme.mutedText,
+ color: noticeColor,
font: fileHeaderSubtextFont
)
}
@@ -2554,6 +2583,13 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate {
NSRange(location: $0.start, length: $0.end - $0.start)
},
color: (change == "add" ? theme.addBar : theme.deleteBar).withAlphaComponent(0.28),
+ note: row.noteStart.map {
+ ReviewDiffCodeNote(
+ range: NSRange(location: $0, length: max(0, text.length - $0)),
+ color: theme.warningText,
+ background: theme.warningBackground
+ )
+ },
version: codeDecorationVersion
)
layout.draw(
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/java/expo/modules/t3terminal/TerminalCanvasView.kt b/apps/mobile/modules/t3-terminal/android/src/main/java/expo/modules/t3terminal/TerminalCanvasView.kt
index 50cd48b3380e7..7991383590dee 100644
--- a/apps/mobile/modules/t3-terminal/android/src/main/java/expo/modules/t3terminal/TerminalCanvasView.kt
+++ b/apps/mobile/modules/t3-terminal/android/src/main/java/expo/modules/t3terminal/TerminalCanvasView.kt
@@ -230,9 +230,7 @@ internal class TerminalCanvasView(context: Context) : View(context) {
if (text.isNotEmpty() && flags and FLAG_INVISIBLE == 0) {
configureTextPaint(flags, currentFrame.cellForegrounds[index])
canvas.drawText(text, left, top + baselineOffsetPx, paint)
- if (flags and FLAG_OVERLINE != 0) {
- canvas.drawRect(left, top + 1f, right, top + max(2f, density), paint)
- }
+ drawOverline(canvas, flags, left, top, right)
}
}
}
@@ -331,14 +329,22 @@ internal class TerminalCanvasView(context: Context) : View(context) {
canvas.drawRect(left, top, right, bottom, paint)
val index = currentFrame.cursorY * currentFrame.cols + currentFrame.cursorX
val text = currentFrame.cellText[index]
- if (text.isNotEmpty()) {
- configureTextPaint(currentFrame.cellFlags[index], currentFrame.background)
+ val flags = currentFrame.cellFlags[index]
+ if (text.isNotEmpty() && flags and FLAG_INVISIBLE == 0) {
+ configureTextPaint(flags, currentFrame.background)
canvas.drawText(text, left, top + baselineOffsetPx, paint)
+ drawOverline(canvas, flags, left, top, right)
}
}
}
}
+ private fun drawOverline(canvas: Canvas, flags: Int, left: Float, top: Float, right: Float) {
+ if (flags and FLAG_OVERLINE != 0) {
+ canvas.drawRect(left, top + 1f, right, top + max(2f, density), paint)
+ }
+ }
+
private fun columnAt(px: Float): Int {
val cols = frame?.cols ?: return 0
return ((px - contentPadding) / cellWidthPx).toInt().coerceIn(0, max(cols - 1, 0))
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/package.json b/apps/mobile/package.json
index 9810e2e3c8a29..2ab0e38d89e24 100644
--- a/apps/mobile/package.json
+++ b/apps/mobile/package.json
@@ -134,7 +134,7 @@
"react-native-pdf-jsi": "6.1.0",
"react-native-reanimated": "4.7.1",
"react-native-safe-area-context": "~5.11.1",
- "react-native-screens": "file:deps/react-native-screens-5.0.0-t3.50.tgz",
+ "react-native-screens": "file:deps/react-native-screens-5.0.0-t3.58.tgz",
"react-native-svg": "15.16.1",
"react-native-webview": "14.0.1",
"react-native-worklets": "0.13.1",
diff --git a/apps/mobile/src/components/ComposerAttachmentStrip.tsx b/apps/mobile/src/components/ComposerAttachmentStrip.tsx
index 49d30e06e45f3..66393de96bc62 100644
--- a/apps/mobile/src/components/ComposerAttachmentStrip.tsx
+++ b/apps/mobile/src/components/ComposerAttachmentStrip.tsx
@@ -18,6 +18,7 @@ import {
type DraftComposerImageAttachment,
} from "../lib/composerImages";
import { resolveOwnedComposerAttachmentFileUri } from "../lib/composerAttachmentFiles";
+import { rememberDraftImage } from "../lib/sentImageHandoff";
import { VideoAttachmentTile } from "./VideoAttachmentTile";
import { type MediaActionsSource } from "../lib/mediaActionsSource";
import { PresentationSource } from "./ui/NativePresentation";
@@ -161,6 +162,13 @@ function ComposerImageAttachment(
style={style}
className="bg-subtle"
resizeMode="cover"
+ onLoad={({ nativeEvent: { source } }) => {
+ if (previewUri !== null)
+ rememberDraftImage(attachment.id, {
+ uri: previewUri,
+ aspectRatio: source.width / source.height,
+ });
+ }}
/>
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/VideoThumbnailImage.tsx b/apps/mobile/src/components/VideoThumbnailImage.tsx
index 6f6fea83063ca..2a031b54b44f9 100644
--- a/apps/mobile/src/components/VideoThumbnailImage.tsx
+++ b/apps/mobile/src/components/VideoThumbnailImage.tsx
@@ -4,6 +4,7 @@ import { Atom, AsyncResult } from "effect/reactivity";
import { Image } from "expo-image";
import { useIsFocused } from "@react-navigation/native";
import type { VideoThumbnail } from "expo-video";
+import { useState } from "react";
import { StyleSheet } from "react-native";
import type { DraftComposerFileAttachment } from "../lib/composerImages";
@@ -41,7 +42,7 @@ export function VideoThumbnailImage(props: {
readonly contentFit?: "cover" | "contain";
}) {
const { cacheKey, source } = props;
- // Extraction runs only while the screen is focused; leaving it interrupts the load.
+ // Extraction starts only while the screen is focused; leaving it skips queued loads.
const isFocused = useIsFocused();
const loaded = useAtomValue(
source && isFocused ? videoThumbnailAtom({ cacheKey, source }) : noVideoThumbnail,
@@ -49,13 +50,17 @@ export function VideoThumbnailImage(props: {
const thumbnail =
(loaded._tag === "Success" ? loaded.value : null) ?? cachedVideoThumbnail(cacheKey);
- return thumbnail ? (
+ // iOS draws a frame object the moment its prop is set, with the contentFit the view has then,
+ // and a later contentFit never refits it. Send the frame after mount so contentFit is set first.
+ const [laidOut, setLaidOut] = useState(false);
+ return (
setLaidOut(true)}
+ source={laidOut ? thumbnail : null}
style={StyleSheet.absoluteFill}
contentFit={props.contentFit ?? "cover"}
recyclingKey={cacheKey}
accessible={false}
/>
- ) : null;
+ );
}
diff --git a/apps/mobile/src/components/ui/AndroidAnchoredMenu.android.tsx b/apps/mobile/src/components/ui/AndroidAnchoredMenu.android.tsx
index a17e48c2604c7..f9e3b2ac01249 100644
--- a/apps/mobile/src/components/ui/AndroidAnchoredMenu.android.tsx
+++ b/apps/mobile/src/components/ui/AndroidAnchoredMenu.android.tsx
@@ -61,6 +61,10 @@ export function AndroidAnchoredMenu(props: AndroidAnchoredMenuProps) {
setPath([]);
setOverlay(null);
};
+ // The in-window menu is pinned to the trigger's spot above the keyboard, which is stale once it hides.
+ if (anchor?.keyboardWasVisible === true && !keyboardVisible) {
+ close();
+ }
const open = () => {
anchorNode?.measureInWindow((x, y, width, height) => {
diff --git a/apps/mobile/src/components/ui/AppSymbol.android.tsx b/apps/mobile/src/components/ui/AppSymbol.android.tsx
index 7aaeac554417a..4a5a16298b956 100644
--- a/apps/mobile/src/components/ui/AppSymbol.android.tsx
+++ b/apps/mobile/src/components/ui/AppSymbol.android.tsx
@@ -91,6 +91,7 @@ import IconListNumbers from "@tabler/icons-react-native/IconListNumbers";
import IconMenu2 from "@tabler/icons-react-native/IconMenu2";
import IconMessageCircleQuestion from "@tabler/icons-react-native/IconMessageCircleQuestion";
import IconMessage from "@tabler/icons-react-native/IconMessage";
+import IconMail from "@tabler/icons-react-native/IconMail";
import IconMessageDots from "@tabler/icons-react-native/IconMessageDots";
import IconMessagePlus from "@tabler/icons-react-native/IconMessagePlus";
import IconMinus from "@tabler/icons-react-native/IconMinus";
@@ -140,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 = {
@@ -207,6 +209,7 @@ const ANDROID_ICON_BY_SF_SYMBOL = {
ellipsis: IconDots,
moon: IconMoon,
"ellipsis.circle": IconDotsCircleHorizontal,
+ "envelope.badge": IconMail,
"exclamationmark.triangle": IconAlertTriangle,
"exclamationmark.circle": IconAlertCircle,
eye: IconEye,
@@ -371,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..c9d950a3b58ac 100644
--- a/apps/mobile/src/components/ui/FilePreviewSession.tsx
+++ b/apps/mobile/src/components/ui/FilePreviewSession.tsx
@@ -11,7 +11,12 @@ import {
} from "../../lib/attachmentDownload";
import { usePreviewPresentation } from "../../lib/previewPresentation";
import { refreshAssetUrl } from "../../state/assets";
-import { filePreviewGallery, filePreviewKey, filePreviewName } from "../../lib/filePreviewGallery";
+import {
+ filePreviewGallery,
+ filePreviewKey,
+ filePreviewName,
+ filePreviewSourceIdentifier,
+} from "../../lib/filePreviewGallery";
import { FilePreviewGallery } from "./FilePreviewGallery";
import type { MediaActionsSource } from "../../lib/mediaActionsSource";
import type {
@@ -97,6 +102,7 @@ function ResolvedFilePreview(
readonly source: FilePreviewSource;
readonly onRequestClose: () => void;
readonly onOpenError?: (error: unknown) => void;
+ readonly onPresent: (isFinished: () => boolean) => void;
},
) {
const { progressiveGallery, Viewer } = props;
@@ -154,6 +160,7 @@ function ResolvedFilePreview(
return {
...item,
name: filePreviewName(item),
+ sourceIdentifier: filePreviewSourceIdentifier(item),
...(uri ? { uri } : uri === null ? { failed: true } : {}),
};
});
@@ -161,6 +168,7 @@ function ResolvedFilePreview(
);
@@ -205,6 +213,7 @@ function ResolvedFilePreview(
}}
onRequestClose={props.onRequestClose}
onOpenError={onOpenError}
+ onPresent={props.onPresent}
/>
);
}
@@ -220,15 +229,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/diagnostics/SettingsDiagnosticsRouteScreen.tsx b/apps/mobile/src/features/diagnostics/SettingsDiagnosticsRouteScreen.tsx
index 528a18541eb46..448fd929e42e8 100644
--- a/apps/mobile/src/features/diagnostics/SettingsDiagnosticsRouteScreen.tsx
+++ b/apps/mobile/src/features/diagnostics/SettingsDiagnosticsRouteScreen.tsx
@@ -96,10 +96,10 @@ export function SettingsDiagnosticsRouteScreen() {
{crashReportingAvailable ? : null}
diff --git a/apps/mobile/src/features/diffs/nativeReviewDiffSource.ts b/apps/mobile/src/features/diffs/nativeReviewDiffSource.ts
index 7f503239c21d2..4d73a7cda5c3c 100644
--- a/apps/mobile/src/features/diffs/nativeReviewDiffSource.ts
+++ b/apps/mobile/src/features/diffs/nativeReviewDiffSource.ts
@@ -19,6 +19,7 @@ function permanentSourceFailureReason(error: unknown): string | undefined {
if (name === "GitHubDiffFileContentsUnavailableError") return "github-source-unavailable";
for (const permanent of [
"provider-unsupported",
+ "repository-without-project",
"unsupported",
"oversized",
"binary",
diff --git a/apps/mobile/src/features/diffs/nativeReviewDiffSurface.ts b/apps/mobile/src/features/diffs/nativeReviewDiffSurface.ts
index bf8c6e8e311ca..2699bb995406c 100644
--- a/apps/mobile/src/features/diffs/nativeReviewDiffSurface.ts
+++ b/apps/mobile/src/features/diffs/nativeReviewDiffSurface.ts
@@ -47,6 +47,12 @@ export interface NativeReviewDiffRow {
readonly commentText?: string;
readonly commentRangeLabel?: string;
readonly commentSectionTitle?: string;
+ /** A notice drawn in the warning colors. */
+ readonly tone?: "warning";
+ /** A notice that reports taps through `onPressNotice`. */
+ readonly actionable?: boolean;
+ /** Where a cut line's note starts in `content`. */
+ readonly noteStart?: number;
}
export interface NativeReviewDiffWordDiffRange {
@@ -74,6 +80,8 @@ export interface NativeReviewDiffTheme {
readonly deleteBar: string;
readonly addText: string;
readonly deleteText: string;
+ readonly warningText: string;
+ readonly warningBackground: string;
}
export interface NativeReviewDiffStyle {
@@ -151,6 +159,9 @@ export interface NativeReviewDiffViewProps extends ViewProps {
}>,
) => void;
readonly onToggleComment?: (event: NativeSyntheticEvent<{ readonly commentId?: string }>) => void;
+ readonly onPressNotice?: (
+ event: NativeSyntheticEvent<{ readonly rowId?: string; readonly fileId?: string }>,
+ ) => void;
}
export interface NativeReviewDiffViewHandle {
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/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/HomeRouteScreen.tsx b/apps/mobile/src/features/home/HomeRouteScreen.tsx
index 6fdaa28914921..05ef660af4e91 100644
--- a/apps/mobile/src/features/home/HomeRouteScreen.tsx
+++ b/apps/mobile/src/features/home/HomeRouteScreen.tsx
@@ -2,8 +2,6 @@ import { uuidv4 } from "../../lib/uuid";
import { ThreadUndoNotice } from "./ThreadUndoNotice";
import { use } from "react";
import { NativePrimaryColumnContext } from "../../native/v5-workspace-context";
-import * as Arr from "effect/Array";
-import * as Order from "effect/Order";
import { useNavigation } from "@react-navigation/native";
import { useMemo, useState } from "react";
import { Platform } from "react-native";
@@ -41,7 +39,7 @@ import { useSelectWorkspaceTab } from "../layout/workspace/useSelectWorkspaceTab
import { useSelectWorkspaceDetail } from "../layout/workspace/useSelectWorkspaceDetail";
import { WorkspaceListEmptyDetail } from "../layout/workspace/WorkspaceListEmptyDetail";
import { WorkspaceListHeader } from "../layout/workspace/WorkspaceListHeader";
-import { buildHomeListFilterMenuItems } from "./home-list-filter-menu";
+import { buildHomeListFilterMenuItems, homeListFilterEnvironments } from "./home-list-filter-menu";
export function HomeRouteScreen() {
const nativePrimaryColumn = use(NativePrimaryColumnContext);
@@ -108,19 +106,7 @@ export function HomeRouteScreen() {
const pendingTasks = usePendingNewTasks();
const { openPendingTask, confirmDeletePendingTask } =
usePendingTaskListActions(selectThreadRoute);
- const connectionStateByEnvironmentId = new Map(
- workspaceEnvironments.map(
- (environment) => [environment.environmentId, environment.connectionState] as const,
- ),
- );
- const environments = Arr.sort(
- Object.values(savedConnectionsById).map((connection) => ({
- environmentId: connection.environmentId,
- label: connection.environmentLabel,
- connectionState: connectionStateByEnvironmentId.get(connection.environmentId) ?? "available",
- })),
- Order.mapInput(Order.String, (environment: { readonly label: string }) => environment.label),
- );
+ const environments = homeListFilterEnvironments(workspaceEnvironments);
const availableEnvironmentIds = useMemo(
() => new Set(environments.map((environment) => environment.environmentId)),
[environments],
diff --git a/apps/mobile/src/features/home/HomeScreen.tsx b/apps/mobile/src/features/home/HomeScreen.tsx
index 8110cca26793d..c2946c59ed065 100644
--- a/apps/mobile/src/features/home/HomeScreen.tsx
+++ b/apps/mobile/src/features/home/HomeScreen.tsx
@@ -7,7 +7,7 @@ import { useAndroidControlSizing } from "../../components/ui/useAndroidControlSi
import type { ThreadMoveDestination } from "../threads/threadOrder";
import type { LegendListRef } from "@legendapp/list/react-native";
import { AnimatedLegendList } from "@legendapp/list/reanimated";
-import { THREAD_SIDEBAR_ROW_LAYOUT } from "../threads/threadListAnimations";
+import { THREAD_LIST_ROW_LAYOUT } from "../threads/threadListAnimations";
import {
type EnvironmentProject,
type EnvironmentThreadShell,
@@ -62,6 +62,7 @@ import { useThreadSearch } from "../../state/queries";
import { requestThreadMessageJump } from "../threads/threadMessageJump";
import { useThreadListSearchMatches } from "../threads/useThreadListSearchMatches";
import { useThreadListV2 } from "../threads/useThreadListV2";
+import { useSidebarRowThreadKey } from "../threads/useSidebarRowThreadKey";
import { useThreadListNow } from "../threads/use-thread-list-now";
import { useSearchScrollRestoration } from "../layout/workspace/useSearchScrollRestoration";
import { useThreadJumpShortcuts } from "../keyboard/threadKeyboardShortcuts";
@@ -203,7 +204,8 @@ export function HomeScreen(props: HomeScreenProps) {
);
const columnMetrics = useNativeColumnLayoutMetrics();
const activeNewTask = useActiveNewTask();
- const selectedThreadKey = activeNewTask ? null : (primaryColumn?.selectedThreadKey ?? null);
+ const sidebarRowThreadKey = useSidebarRowThreadKey(primaryColumn?.selectedThreadKey ?? null);
+ const selectedThreadKey = activeNewTask ? null : sidebarRowThreadKey;
const fullSwipeWidth = primaryColumn && columnMetrics ? columnMetrics.width - 20 : undefined;
const queuedThreadKeys = useQueuedThreadKeys();
const openSwipeableRef = useRef(null);
@@ -469,7 +471,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 ??
@@ -752,7 +753,7 @@ export function HomeScreen(props: HomeScreenProps) {
{
settleLaunchSplashHomeRows();
diff --git a/apps/mobile/src/features/home/ThreadUndoNotice.tsx b/apps/mobile/src/features/home/ThreadUndoNotice.tsx
index caeb47a3c2195..544a2909124ea 100644
--- a/apps/mobile/src/features/home/ThreadUndoNotice.tsx
+++ b/apps/mobile/src/features/home/ThreadUndoNotice.tsx
@@ -51,7 +51,11 @@ export function ThreadUndoNotice(props: { readonly visible: boolean }) {
const bottom =
Platform.OS === "ios"
? foldedResting
- ? Math.max(rootMetrics.safeArea.bottom, keyboardHeight) + 8
+ ? // Sit level with the rail's tab pill, which floats inside the bottom safe area.
+ Math.max(
+ rootMetrics.bottomBarInset ?? rootMetrics.safeArea.bottom + 8,
+ keyboardHeight + 8,
+ )
: rootMetrics?.hasHinge && rootMetrics.verticalBarEdge !== "none"
? // The column's safe area already includes UIKit's search toolbar in this posture.
workspaceSearchBottomClearance({
diff --git a/apps/mobile/src/features/home/home-list-filter-menu.test.ts b/apps/mobile/src/features/home/home-list-filter-menu.test.ts
new file mode 100644
index 0000000000000..a6c6b95984e9b
--- /dev/null
+++ b/apps/mobile/src/features/home/home-list-filter-menu.test.ts
@@ -0,0 +1,35 @@
+import type { EnvironmentId } from "@t3tools/contracts";
+import { expect, it } from "vite-plus/test";
+
+import type { WorkspaceEnvironment } from "../../state/workspaceModel";
+import { homeListFilterEnvironments } from "./home-list-filter-menu";
+
+function environment(
+ environmentId: string,
+ environmentLabel: string,
+ isEnabled: boolean,
+): WorkspaceEnvironment {
+ return {
+ environmentId: environmentId as EnvironmentId,
+ environmentLabel,
+ displayUrl: "",
+ isRelayManaged: false,
+ isEnabled,
+ connectionState: isEnabled ? "connected" : "available",
+ connectionError: null,
+ connectionErrorTraceId: null,
+ };
+}
+
+it("offers only switched-on environments, sorted by label", () => {
+ expect(
+ homeListFilterEnvironments([
+ environment("env-studio", "Studio", true),
+ environment("env-laptop", "Laptop", false),
+ environment("env-desk", "Desk", true),
+ ]),
+ ).toEqual([
+ { environmentId: "env-desk", label: "Desk", connectionState: "connected" },
+ { environmentId: "env-studio", label: "Studio", connectionState: "connected" },
+ ]);
+});
diff --git a/apps/mobile/src/features/home/home-list-filter-menu.ts b/apps/mobile/src/features/home/home-list-filter-menu.ts
index 617c3fa0988ef..1d6da0e8d765c 100644
--- a/apps/mobile/src/features/home/home-list-filter-menu.ts
+++ b/apps/mobile/src/features/home/home-list-filter-menu.ts
@@ -1,12 +1,28 @@
import type { EnvironmentId } from "@t3tools/contracts";
+import * as Arr from "effect/Array";
+import * as Order from "effect/Order";
import type { AppBarMenuItem } from "../../components/ui/AppBar.types";
+import type { WorkspaceEnvironment } from "../../state/workspaceModel";
export interface HomeListFilterMenuEnvironment {
readonly environmentId: EnvironmentId;
readonly label: string;
}
+export function homeListFilterEnvironments(environments: ReadonlyArray) {
+ return Arr.sort(
+ environments
+ .filter((environment) => environment.isEnabled)
+ .map((environment) => ({
+ environmentId: environment.environmentId,
+ label: environment.environmentLabel,
+ connectionState: environment.connectionState,
+ })),
+ Order.mapInput(Order.String, (environment: { readonly label: string }) => environment.label),
+ );
+}
+
export interface HomeListFilterMenuProject {
readonly key: string;
readonly label: string;
diff --git a/apps/mobile/src/features/home/thread-swipe-actions.tsx b/apps/mobile/src/features/home/thread-swipe-actions.tsx
index 532badd9b35cb..40c7c58f15f31 100644
--- a/apps/mobile/src/features/home/thread-swipe-actions.tsx
+++ b/apps/mobile/src/features/home/thread-swipe-actions.tsx
@@ -52,6 +52,8 @@ const COMPACT_ACTION_CIRCLE_SIZE = 28;
const COMPACT_ACTION_ICON_SIZE = 13;
// At the default app text size, "Unarchive", the longest label, fills its slot at about 1.12x.
const ACTION_LABEL_MAX_FONT_SCALE = 1.1;
+const ACTION_LABEL_MIN_HEIGHT = 14;
+const ACTION_LABEL_OFFSET = 2;
const THREAD_SWIPE_ACTIONS_WIDTH = ACTION_ITEM_WIDTH * 2;
const THREAD_SWIPE_SPRING = {
@@ -82,6 +84,14 @@ function swipeActionsWidth(hasSecondaryAction: boolean) {
return hasSecondaryAction ? THREAD_SWIPE_ACTIONS_WIDTH : ACTION_ITEM_WIDTH;
}
+function fullActionStackHeight(labelLineHeight: number, fontScale: number) {
+ const labelHeight = labelLineHeight * Math.min(fontScale, ACTION_LABEL_MAX_FONT_SCALE);
+ // The offset shifts the label after centering, so it needs room on both sides.
+ return (
+ ACTION_CIRCLE_SIZE + ACTION_LABEL_OFFSET * 2 + Math.max(ACTION_LABEL_MIN_HEIGHT, labelHeight)
+ );
+}
+
function resolveSecondaryAction(input: {
readonly close: () => void;
readonly onDelete: () => void;
@@ -226,6 +236,8 @@ interface ThreadSwipeableProps {
/** Omitted uses Delete only with the built-in Delete secondary action; otherwise it uses primary. */
readonly fullSwipeAction?: "delete" | "primary";
readonly fullSwipeWidth: number;
+ /** The list animates item layout; collapse in one step so its transition moves siblings once. */
+ readonly listAnimatesLayout?: boolean;
readonly onDelete: () => void;
readonly onSwipeableClose?: (methods: SwipeableMethods) => void;
readonly onSwipeableWillOpen?: (methods: SwipeableMethods) => void;
@@ -239,6 +251,8 @@ interface ThreadSwipeableProps {
readonly threadTitle: string;
}
+const COLLAPSED_ROW_STYLE = { height: 0, overflow: "hidden" } as const;
+
export function ThreadSwipeable(props: ThreadSwipeableProps) {
const swipeableRef = useRef(null);
const hasSecondaryAction = props.secondaryAction !== null;
@@ -259,6 +273,7 @@ export function ThreadSwipeable(props: ThreadSwipeableProps) {
);
const contentRef = useRef(content);
const [isDismissing, setIsDismissing] = useState(false);
+ const [collapsedInList, setCollapsedInList] = useState(false);
const dismissing = useSharedValue(false);
const rowHeight = useSharedValue(0);
const rowWidth = useSharedValue(props.fullSwipeWidth);
@@ -268,6 +283,7 @@ export function ThreadSwipeable(props: ThreadSwipeableProps) {
const primaryAction = props.primaryAction;
const onDelete = props.onDelete;
const onSwipeableClose = props.onSwipeableClose;
+ const listAnimatesLayout = props.listAnimatesLayout === true;
const restoreRow = useCallback(() => {
if (!mountedRef.current) return;
@@ -284,6 +300,7 @@ export function ThreadSwipeable(props: ThreadSwipeableProps) {
dismissing.set(false);
})(swipeableRef.current);
setIsDismissing(false);
+ setCollapsedInList(false);
}, [actionOpacity, collapse, dismissing, fallbackTranslation]);
const finishDismiss = useCallback((id?: number) => {
@@ -292,6 +309,14 @@ export function ThreadSwipeable(props: ThreadSwipeableProps) {
pendingDismissRef.current = null;
pending.resolve();
}, []);
+ const collapseInList = useCallback(
+ (id: number) => {
+ if (!mountedRef.current || pendingDismissRef.current?.id !== id) return;
+ setCollapsedInList(true);
+ finishDismiss(id);
+ },
+ [finishDismiss],
+ );
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- cancels the row's Reanimated animations and settles a pending dismissal on unmount
useLayoutEffect(() => {
@@ -336,6 +361,12 @@ export function ThreadSwipeable(props: ThreadSwipeableProps) {
translation.set(
withTiming(Math.min(translation.value, -rowWidth.value), timing, (finished) => {
if (!finished) return;
+ // LegendList re-measures rows only on React commits, so a UI-thread height animation
+ // reaches it in late jumps. Collapse through React and let its transition move rows.
+ if (listAnimatesLayout) {
+ runOnJS(collapseInList)(id);
+ return;
+ }
collapse.set(
withTiming(1, { ...timing, duration: 180 }, (collapsed) => {
if (collapsed) runOnJS(finishDismiss)(id);
@@ -344,7 +375,15 @@ export function ThreadSwipeable(props: ThreadSwipeableProps) {
}),
);
},
- [actionOpacity, collapse, dismissing, finishDismiss, rowWidth],
+ [
+ actionOpacity,
+ collapse,
+ collapseInList,
+ dismissing,
+ finishDismiss,
+ listAnimatesLayout,
+ rowWidth,
+ ],
);
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- registers this row's animated dismissal in the module-level thread dismissal registry
useLayoutEffect(
@@ -422,7 +461,12 @@ export function ThreadSwipeable(props: ThreadSwipeableProps) {
const handleSwipeableClose = useCallback(() => {
if (swipeableRef.current) onSwipeableClose?.(swipeableRef.current);
}, [onSwipeableClose]);
- const compactActions = props.compactActions === true;
+ const { fontScale } = useWindowDimensions();
+ const fullActionsHeight = fullActionStackHeight(useScaledTextRole("micro").lineHeight, fontScale);
+ const [measuredRowHeight, setMeasuredRowHeight] = useState(0);
+ const compactActions =
+ props.compactActions === true ||
+ (measuredRowHeight > 0 && measuredRowHeight < fullActionsHeight);
const { secondaryAction, threadTitle } = props;
// Swipeable calls this on every render; returning the previous element while nothing it shows
// changed keeps a selection change from re-rendering the hidden actions.
@@ -439,6 +483,7 @@ export function ThreadSwipeable(props: ThreadSwipeableProps) {
actionStyle,
backgroundColor,
compactActions,
+ measuredRowHeight,
fullSwipeAction,
fullSwipeThreshold,
handleFullSwipeArmedChange,
@@ -462,6 +507,7 @@ export function ThreadSwipeable(props: ThreadSwipeableProps) {
- {
- rowHeight.set(layout.height);
- rowWidth.set(layout.width);
- }}
- >
-
+
+ {
+ rowHeight.set(layout.height);
+ setMeasuredRowHeight(layout.height);
+ rowWidth.set(layout.width);
+ }}
>
- {
- /* oxlint-disable react/refs -- The render callback receives a close/open handler; only invoking that handler accesses the ref. */
- props.children(close)
- /* oxlint-enable react/refs */
- }
-
-
-
+
+ {
+ /* oxlint-disable react/refs -- The render callback receives a close/open handler; only invoking that handler accesses the ref. */
+ props.children(close)
+ /* oxlint-enable react/refs */
+ }
+
+
+
+
);
}
@@ -536,6 +587,7 @@ function SwipeActionButton(props: {
readonly label: string;
readonly menu?: ThreadSwipeAction["menu"];
readonly onPress: () => void;
+ readonly rowHeight: number;
readonly stretchesOnFullSwipe: boolean;
readonly translation: SharedValue;
}) {
@@ -549,7 +601,13 @@ function SwipeActionButton(props: {
const circleSize = props.compact ? COMPACT_ACTION_CIRCLE_SIZE : ACTION_CIRCLE_SIZE;
const iconSize = props.compact ? COMPACT_ACTION_ICON_SIZE : ACTION_ICON_SIZE;
const { fontScale } = useWindowDimensions();
- const labelLineHeight = useScaledTextRole("micro").lineHeight;
+ // Even compact actions can outgrow a short row at large app text sizes; shrink the label's
+ // leading to the room left under the circle.
+ const labelRoom =
+ props.compact && props.rowHeight > 0
+ ? (props.rowHeight - circleSize) / Math.min(fontScale, ACTION_LABEL_MAX_FONT_SCALE)
+ : Infinity;
+ const labelLineHeight = Math.min(useScaledTextRole("micro").lineHeight, labelRoom);
// Android scales lineHeight by the full font scale, past maxFontSizeMultiplier.
const labelTextStyle = {
lineHeight:
@@ -689,7 +747,11 @@ function SwipeActionButton(props: {
{/* An offset, not padding: padding would grow the box and move the circle at 1x. */}
@@ -741,6 +803,7 @@ function ThreadSwipeActions(props: {
readonly fullSwipeThreshold: number;
readonly onFullSwipeArmedChange: (armed: boolean) => void;
readonly primaryAction: ThreadSwipeAction;
+ readonly rowHeight: number;
readonly secondaryAction: ThreadSwipeSecondaryAction | null;
readonly translation: SharedValue;
}) {
@@ -780,6 +843,7 @@ function ThreadSwipeActions(props: {
icon={props.primaryAction.icon}
label={props.primaryAction.label}
onPress={props.primaryAction.onPress}
+ rowHeight={props.rowHeight}
stretchesOnFullSwipe={fullSwipeIsPrimary}
translation={props.translation}
/>
@@ -795,6 +859,7 @@ function ThreadSwipeActions(props: {
label={secondaryAction.label}
menu={secondaryAction.menu}
onPress={secondaryAction.onPress}
+ rowHeight={props.rowHeight}
stretchesOnFullSwipe={!fullSwipeIsPrimary}
translation={props.translation}
/>
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/keyboard/CommandPalette.tsx b/apps/mobile/src/features/keyboard/CommandPalette.tsx
index 38b83e4c56bad..9b8cd114fc8ba 100644
--- a/apps/mobile/src/features/keyboard/CommandPalette.tsx
+++ b/apps/mobile/src/features/keyboard/CommandPalette.tsx
@@ -9,7 +9,8 @@ import {
type EnvironmentThreadSearchMatch,
type ShownOrder,
} from "@t3tools/client-runtime/state/thread-search";
-import { isListedThreadLineage, THREAD_JUMP_KEYBINDING_COMMANDS } from "@t3tools/contracts";
+import { isShownUnderParent } from "@t3tools/client-runtime/state/threads";
+import { THREAD_JUMP_KEYBINDING_COMMANDS } from "@t3tools/contracts";
import {
foldSearchQuery,
PALETTE_MESSAGE_LIMIT,
@@ -43,6 +44,7 @@ import { scopedProjectKey, scopedThreadKey } from "../../lib/scopedEntities";
import { useNativeLayoutMetrics } from "../../native/native-layout-metrics";
import { T3KeyboardCommands } from "../../native/T3KeyboardCommands";
import {
+ useDelegatedUnderParent,
useProjects,
useServerConfigs,
useThreadShell,
@@ -227,6 +229,7 @@ export function CommandPalette(props: {
const runCommand = props.onCommand;
const projects = useProjects();
const threads = useVisibleThreadShells();
+ const delegatedUnderParent = useDelegatedUnderParent();
const activeThreadRef = parseActiveThreadPath(props.pathname);
const activeThread = useThreadShell(activeThreadRef);
const visitThread = useAtomCommand(threadEnvironment.visit, { reportFailure: false });
@@ -426,7 +429,15 @@ export function CommandPalette(props: {
}),
}));
const threadItems: CommandPaletteItem[] = threads
- .filter((thread) => thread.archivedAt === null && isListedThreadLineage(thread.lineage))
+ .filter(
+ (thread) =>
+ thread.archivedAt === null &&
+ !isShownUnderParent(
+ { environmentId: thread.environmentId, threadId: thread.id },
+ thread.lineage,
+ delegatedUnderParent,
+ ),
+ )
.map((thread) => {
const project = projectByKey.get(scopedProjectKey(thread.environmentId, thread.projectId));
const environment =
@@ -473,6 +484,7 @@ export function CommandPalette(props: {
selectDetail,
startTriage,
threads,
+ delegatedUnderParent,
triageEnvironmentId,
]);
const rankedMessageKeys = useMemo(() => {
diff --git a/apps/mobile/src/features/layout/createWorkspaceStackNavigator.ios.tsx b/apps/mobile/src/features/layout/createWorkspaceStackNavigator.ios.tsx
index bac954d99f118..367942ad43139 100644
--- a/apps/mobile/src/features/layout/createWorkspaceStackNavigator.ios.tsx
+++ b/apps/mobile/src/features/layout/createWorkspaceStackNavigator.ios.tsx
@@ -28,7 +28,13 @@ import {
type ComponentProps,
type ReactNode,
} from "react";
-import { StyleSheet, View } from "react-native";
+import { withKnownPullRequestSummary } from "../../state/use-thread-pr";
+import {
+ currentWorkspaceSelections,
+ workspaceSelectionCheck,
+} from "./workspace/workspace-selection-store";
+import { workspaceTabColumns, workspaceTabPage } from "./workspace/workspace-tab-navigation";
+import { Platform, StyleSheet, View } from "react-native";
import { Split, type SplitHostCommands } from "react-native-screens";
import { SafeAreaView } from "react-native-safe-area-context";
import { GestureHandlerRootView } from "react-native-gesture-handler";
@@ -77,6 +83,7 @@ import {
NativePrimaryColumnContext,
NativeWorkspaceInspectorContext,
NativeWorkspaceModeContext,
+ NativeWorkspaceTabActivityContext,
WorkspaceSlotOptionsContext,
slotScreenOptions,
} from "../../native/v5-workspace-context";
@@ -104,10 +111,14 @@ function ColumnScreen(props: {
readonly screenKey?: string;
readonly primary?: boolean;
readonly attached?: boolean;
+ readonly animatesPush?: boolean;
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;
@@ -135,6 +146,7 @@ function ColumnScreen(props: {
{
props.onDismiss(key, event.nativeEvent.isNativeDismiss);
}}
@@ -152,9 +164,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 } });
+ }}
>
@@ -167,6 +180,7 @@ function ColumnScreen(props: {
/>
() });
+ if (shownPages.headerOnly !== headerOnly)
+ setShownPages({
+ headerOnly,
+ keys: headerOnly ? new Set() : new Set(props.detail.map((route) => route.key)),
+ });
const inspector = use(NativeWorkspaceInspectorContext);
const hideInspector = () => {
if (inspector.visible) toggleAuxiliaryPane();
@@ -307,7 +329,7 @@ function WorkspaceColumns(
}
};
const followCollapsedSplit = (
- type: "willAppear" | "didAppear" | "willDisappear",
+ type: "willAppear" | "didAppear" | "willDisappear" | "didDisappear",
key: string,
) => {
if (!collapsed.current || layout.usesSplitView) return;
@@ -331,6 +353,7 @@ function WorkspaceColumns(
const primary = props.descriptors[props.primary.key];
if (!primary) return null;
+ const primaryColumnWidth = (layout.listPaneWidth ?? 320) + (layout.listPaneGap ?? 0) / 2;
return (
-
+
current.key === route.key)}
+ animatesPush={!shownPages.keys.has(route.key)}
onDismiss={handleNativeDismiss}
onAppearance={followCollapsedSplit}
onCompose={isPullRequestRoute(route) ? undefined : detailCompose}
@@ -533,34 +557,51 @@ function WorkspaceStackView(props: ViewProps & { readonly nativeColumns: boolean
0 &&
!primaryVisible &&
!layout.usesSplitView &&
(metrics?.verticalBarEdge ?? "none") === "none"
}
>
- {props.nativeColumns && !workspacePage ? (
-
- ) : (
-
- )}
+ {(slotWorkspace, headerOnly) => {
+ // A tab not shown yet renders the page opening it shows, under the key it opens with,
+ // so that page is already on screen in the tab when it's selected.
+ const tab = slotWorkspace.settingsOpen ? "settings" : slotWorkspace.state.selectedTab;
+ const page = headerOnly
+ ? (workspaceTabPage(props.state, tab, currentWorkspaceSelections(), {
+ columns: workspaceTabColumns(Platform.OS, tab, layout.usesSplitView),
+ check: workspaceSelectionCheck,
+ seedPullRequest: withKnownPullRequestSummary,
+ }) as Route | undefined)
+ : undefined;
+ const detail = headerOnly ? (page ? [page] : []) : projection.detail;
+ const slotDescriptors =
+ page && !descriptors[page.key]
+ ? { ...descriptors, [page.key]: props.describe(page, true) }
+ : descriptors;
+ return props.nativeColumns &&
+ workspaceUsesColumns(slotWorkspace.state.selectedTab, slotWorkspace.settingsOpen) ? (
+
+ ) : (
+
+ );
+ }}
),
};
diff --git a/apps/mobile/src/features/layout/workspace/WorkspaceNativeTabs.ios.tsx b/apps/mobile/src/features/layout/workspace/WorkspaceNativeTabs.ios.tsx
index 2247ea50c9a4a..9d189ea9589ef 100644
--- a/apps/mobile/src/features/layout/workspace/WorkspaceNativeTabs.ios.tsx
+++ b/apps/mobile/src/features/layout/workspace/WorkspaceNativeTabs.ios.tsx
@@ -3,21 +3,31 @@ import {
NAVIGATION_TAB_ICONS,
useEnabledNavigationTabs,
} from "./navigation-tabs";
-import { useLayoutEffect, useRef, useState, type ReactNode } from "react";
+import {
+ useEffect,
+ useLayoutEffect,
+ useRef,
+ useState,
+ type Dispatch,
+ type ReactNode,
+ type SetStateAction,
+} from "react";
import { View, useWindowDimensions, type NativeSyntheticEvent } from "react-native";
import { Tabs, type TabSelectedEvent, type TabSelectionRejectedEvent } from "react-native-screens";
import { WorkspaceTabsContext, useWorkspaceTabs } from "./WorkspaceTabsContext";
+import type { NavigationTab } from "./navigation-tab-order";
import {
NATIVE_WORKSPACE_TAB_SLOTS,
workspaceTabForNativeSlot,
workspaceUsesColumns,
- type WorkspaceTab,
} from "./workspace-tabs-state";
import {
NativeWorkspaceTabActivityContext,
+ WorkspaceColumnMetricsContext,
WorkspaceSlotOptionsContext,
} from "../../../native/v5-workspace-context";
+import type { NativeLayoutMetrics } from "../../../lib/reserved-regions";
import {
useCompactWorkspaceTabs,
useFloatingWorkspaceTabs,
@@ -33,9 +43,14 @@ const PULL_REQUEST_ICON = require("../../../../assets/icons/pull-request.png");
/** Retain each native controller tree; removing its root can leave RNS's stack empty. */
function RetainedWorkspaceTab(props: {
- readonly tab: WorkspaceTab;
+ readonly slot: string;
+ readonly tab: NavigationTab;
readonly active: boolean;
- readonly children: ReactNode;
+ /** Render a slot that hasn't been shown yet: its header, and the page it opens with. */
+ readonly prewarm: boolean;
+ readonly setMountedSlots: Dispatch>>;
+ readonly setPrewarmRequests: Dispatch>>;
+ readonly children: (workspace: SlotWorkspace, headerOnly: boolean) => ReactNode;
}) {
const workspace = useWorkspaceTabs()!;
// Whether this slot is the visible one, read by cleanups after the switch has committed.
@@ -45,9 +60,30 @@ function RetainedWorkspaceTab(props: {
activeRef.current = props.active;
}, [props.active]);
const isActive = () => activeRef.current;
+ const [content, setContent] = useState(
+ props.active
+ ? { source: workspace, workspace, children: props.children, headerOnly: false }
+ : null,
+ );
+ const stale = content?.source !== workspace || content?.children !== props.children;
+ if (props.active && (content?.headerOnly !== false || stale))
+ setContent({ source: workspace, workspace, children: props.children, headerOnly: false });
+ // A slot not shown yet follows the workspace, so the page it opens with stays current.
+ else if (!props.active && props.prewarm && (content === null || (content.headerOnly && stale)))
+ setContent({
+ source: workspace,
+ workspace: {
+ ...workspace,
+ settingsOpen: props.slot === "settings",
+ state: { ...workspace.state, selectedTab: props.tab },
+ },
+ children: props.children,
+ headerOnly: true,
+ });
const activity = {
active: props.active,
isActive,
+ headerOnly: content?.headerOnly === true,
};
const [optionsByRoute, setOptionsByRoute] = useState>(new Map());
// Stable, so writers and the cleanups that depend on them don't re-run on every write.
@@ -56,22 +92,55 @@ function RetainedWorkspaceTab(props: {
new Map(current).set(routeKey, { ...current.get(routeKey), ...options }),
);
const slotOptions = { byRoute: optionsByRoute, set: setRouteOptions };
- const [content, setContent] = useState(
- props.active ? { workspace, children: props.children } : null,
+ const mounted = content !== null && !content.headerOnly;
+ const headerOnly = content?.headerOnly === true;
+ const { slot, setMountedSlots, setPrewarmRequests } = props;
+ // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- reports the slot's mount to the host, which uncovers the tab then
+ useEffect(() => {
+ if (!mounted) return;
+ // Each header write commits in the render after it; the slot is ready once a frame passes
+ // without one, which is when its native header and content are in place.
+ const frame = requestAnimationFrame(() =>
+ setMountedSlots((current) => (current.has(slot) ? current : new Set(current).add(slot))),
+ );
+ return () => cancelAnimationFrame(frame);
+ // oxlint-disable-next-line react/exhaustive-effect-dependencies -- each header write re-arms the frame
+ }, [mounted, optionsByRoute, slot, setMountedSlots]);
+ // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- a replacement slot (e.g. a re-enabled fourth tab) must report its own mount
+ useEffect(
+ () => () =>
+ setMountedSlots((current) => {
+ if (!current.has(slot)) return current;
+ const next = new Set(current);
+ next.delete(slot);
+ return next;
+ }),
+ [slot, setMountedSlots],
);
- if (props.active && (content?.workspace !== workspace || content?.children !== props.children))
- setContent({ workspace, children: props.children });
+ // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- asks UIKit to prewarm a hidden header after each write, since bar items it rebuilds fade in on their own first entry
+ useEffect(() => {
+ if (!headerOnly || optionsByRoute.size === 0) return;
+ const frame = requestAnimationFrame(() =>
+ setPrewarmRequests((current) => new Map(current).set(slot, (current.get(slot) ?? 0) + 1)),
+ );
+ return () => cancelAnimationFrame(frame);
+ }, [headerOnly, optionsByRoute, slot, setPrewarmRequests]);
return content ? (
- {content.children}
+
+ {content.children(content.workspace, content.headerOnly)}
+
) : null;
}
+type SlotWorkspace = NonNullable>;
+
export function WorkspaceNativeTabs(props: {
- readonly children: ReactNode;
+ /** Renders a slot's tree for its own tab, which can lay out differently from the shown one. */
+ readonly children: (workspace: SlotWorkspace, headerOnly: boolean) => ReactNode;
readonly hidden: boolean;
/** The sidebar column draws the tabs itself, so they leave with it. */
readonly tabsInSidebarColumn?: boolean;
@@ -98,66 +167,101 @@ export function WorkspaceNativeTabs(props: {
const { colors } = useControlTheme();
const selectedTab = workspace.state.selectedTab;
const selectedSlot = workspace.settingsOpen ? -1 : primaryTabs.indexOf(selectedTab);
- const request = {
- selectedScreenKey: selectedSlot === -1 ? "settings" : NATIVE_WORKSPACE_TAB_SLOTS[selectedSlot]!,
- baseProvenance: provenance,
+ const selectedScreenKey =
+ selectedSlot === -1 ? "settings" : NATIVE_WORKSPACE_TAB_SLOTS[selectedSlot]!;
+ // A slot renders its body the first time it's selected. Until it has, UIKit keeps the last
+ // tab's snapshot over it, so the switch never shows a half-built tab.
+ const [mountedSlots, setMountedSlots] = useState>(() => new Set());
+ // Once the first tab is up, the others mount their headers for UIKit to put in the window
+ // once: iOS 26 fades bar items in the first time they enter it, which a first visit would show.
+ const [prewarm, setPrewarm] = useState(false);
+ const [columnMetrics, setColumnMetrics] = useState>(
+ () => new Map(),
+ );
+ const sharedColumnMetrics = {
+ byColumn: columnMetrics,
+ publish: (column: string, metrics: NativeLayoutMetrics) =>
+ setColumnMetrics((current) =>
+ JSON.stringify(current.get(column)) === JSON.stringify(metrics)
+ ? current
+ : new Map(current).set(column, metrics),
+ ),
};
+ const [prewarmRequests, setPrewarmRequests] = useState>(
+ () => new Map(),
+ );
+ const prewarmReady = mountedSlots.size > 0;
+ // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- waits for the JS thread to go idle after the first tab mounts
+ useEffect(() => {
+ if (!prewarmReady || prewarm) return;
+ const handle = requestIdleCallback(() => setPrewarm(true), { timeout: 2_000 });
+ return () => cancelIdleCallback(handle);
+ }, [prewarmReady, prewarm]);
+ const request = { selectedScreenKey, baseProvenance: provenance };
return (
- ) =>
- setProvenance(nativeEvent.provenance)
- }
- onTabSelected={({ nativeEvent }: NativeSyntheticEvent) => {
- setProvenance(nativeEvent.provenance);
- if (nativeEvent.actionOrigin === "programmatic-js") return;
- const tab = workspaceTabForNativeSlot(primaryTabs, nativeEvent.selectedScreenKey);
- if (tab) selectTab(tab);
- }}
- >
- {NATIVE_WORKSPACE_TAB_SLOTS.map((slot, index) => {
- const settings = slot === "settings";
- const tab = settings ? (overflow ?? selectedTab) : primaryTabs[index];
- if (!tab) return null;
- return (
-
-
+ ) =>
+ setProvenance(nativeEvent.provenance)
+ }
+ onTabSelected={({ nativeEvent }: NativeSyntheticEvent) => {
+ setProvenance(nativeEvent.provenance);
+ if (nativeEvent.actionOrigin === "programmatic-js") return;
+ const tab = workspaceTabForNativeSlot(primaryTabs, nativeEvent.selectedScreenKey);
+ if (tab) selectTab(tab);
+ }}
+ >
+ {NATIVE_WORKSPACE_TAB_SLOTS.map((slot, index) => {
+ const settings = slot === "settings";
+ const tab = settings ? (overflow ?? selectedTab) : primaryTabs[index];
+ if (!tab) return null;
+ return (
+
- {props.children}
-
-
- );
- })}
-
+
+ {props.children}
+
+
+ );
+ })}
+
+
{(deviceType === "pad" ||
compactTabs ||
(layout.variant === "medium" &&
diff --git a/apps/mobile/src/features/layout/workspace/WorkspaceRootScreen.tsx b/apps/mobile/src/features/layout/workspace/WorkspaceRootScreen.tsx
index e8e7c0d325983..e96bf422842e7 100644
--- a/apps/mobile/src/features/layout/workspace/WorkspaceRootScreen.tsx
+++ b/apps/mobile/src/features/layout/workspace/WorkspaceRootScreen.tsx
@@ -12,7 +12,10 @@ import { SafeAreaInsetsContext, useSafeAreaInsets } from "react-native-safe-area
import { CompactBrandTitle } from "../../../components/CompactBrandTitle";
import { HeaderItemsWidthContext } from "../../../native/header-items-width";
import { NativeStackScreenOptions } from "../../../native/StackHeader";
-import { NativePrimaryColumnContext } from "../../../native/v5-workspace-context";
+import {
+ NativePrimaryColumnContext,
+ NativeWorkspaceTabActivityContext,
+} from "../../../native/v5-workspace-context";
import { isDuoDevice } from "../../../lib/device-type";
import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../../native/native-glass";
import {
@@ -89,6 +92,7 @@ function WorkspaceRootContent() {
const { state } = workspace;
// Settings is a workspace tab too; its list takes the place of the selected tab's.
const settingsOpen = workspace.settingsOpen;
+ const headerOnly = use(NativeWorkspaceTabActivityContext)?.headerOnly === true;
const renderHeaderTitle = () => (
- {settingsOpen ? (
+ {/* Usage draws its own header, and skips its body itself. */}
+ {headerOnly && (settingsOpen || state.selectedTab !== "usage") ? null : settingsOpen ? (
) : enabled.length === 0 ? (
diff --git a/apps/mobile/src/features/layout/workspace/workspace-tab-navigation.test.ts b/apps/mobile/src/features/layout/workspace/workspace-tab-navigation.test.ts
index 3cd3fe6d0978f..b7ee8cb2f6094 100644
--- a/apps/mobile/src/features/layout/workspace/workspace-tab-navigation.test.ts
+++ b/apps/mobile/src/features/layout/workspace/workspace-tab-navigation.test.ts
@@ -6,6 +6,7 @@ import {
workspaceSelectionsIn,
workspaceTabColumns,
workspaceTabNavigationState,
+ workspaceTabPage,
} from "./workspace-tab-navigation";
const home = { key: "home", name: "Home" };
@@ -118,6 +119,12 @@ describe("opening a workspace tab", () => {
workspaceTabNavigationState(state, "settings", { settings: "SettingsMicrophone" }, columns),
),
).toEqual(["Home", "Settings", "SettingsVoice"]);
+ // A hidden tab renders its page under the key that opening the tab later uses.
+ for (const tab of ["pullRequests", "settings"] as const) {
+ expect(workspaceTabNavigationState(state, tab, selections, columns).routes.at(-1)?.key).toBe(
+ workspaceTabPage(state, tab, selections, columns)?.key,
+ );
+ }
});
it("keeps the route that is already open, so re-selecting a tab doesn't rebuild it", () => {
diff --git a/apps/mobile/src/features/layout/workspace/workspace-tab-navigation.ts b/apps/mobile/src/features/layout/workspace/workspace-tab-navigation.ts
index 6a44e617e53ed..704e47d2b9168 100644
--- a/apps/mobile/src/features/layout/workspace/workspace-tab-navigation.ts
+++ b/apps/mobile/src/features/layout/workspace/workspace-tab-navigation.ts
@@ -146,6 +146,13 @@ function keyed(route: Route): Route & { readonly key: s
return { ...route, key: `${route.name}-workspace-${routeKeys}` };
}
+// A hidden tab renders the page it would open under this key, so opening it reuses that screen.
+function keyedPage(route: Route): Route & { readonly key: string } {
+ return route.key === undefined
+ ? { ...route, key: `${route.name}-workspace-page` }
+ : (route as Route & { readonly key: string });
+}
+
function detailRoute(
state: { readonly routes: readonly RouteLike[] },
tab: "threads" | "pullRequests",
@@ -222,7 +229,12 @@ export function workspaceTabNavigationState<
undefined,
page === selections.settings ? selections.settingsKey : undefined,
);
- const routes = [...settings.routes.map(keyed), ...overlays];
+ const [home, list, current] = settings.routes;
+ const routes = [
+ ...[home!, list!].map(keyed),
+ ...(current ? [keyedPage(current)] : []),
+ ...overlays,
+ ];
return { ...settings, index: routes.length - 1, routes };
}
const home = state.routes.find((route) => route.name === "Home") ?? { name: "Home" };
@@ -230,6 +242,23 @@ export function workspaceTabNavigationState<
options.columns && tab !== "usage"
? detailRoute(state, tab, selections, options.check, options.seedPullRequest)
: undefined;
- const routes = [...[home, ...(detail ? [detail] : [])].map(keyed), ...overlays];
+ const routes = [keyed(home), ...(detail ? [keyedPage(detail)] : []), ...overlays];
return { ...state, index: routes.length - 1, routes };
}
+
+/** The page opening `tab` would show beside its list, which the hidden tab renders ahead. */
+export function workspaceTabPage(
+ state: { readonly routes: readonly RouteLike[] },
+ tab: WorkspaceTab | "settings",
+ selections: WorkspaceSelections,
+ options: {
+ readonly columns: boolean;
+ readonly check: WorkspaceSelectionCheck;
+ readonly seedPullRequest?: (identity: Omit) => object;
+ },
+) {
+ const page = workspaceTabNavigationState(state, tab, selections, options).routes.find(
+ (route) => route.name !== "Home" && route.name !== "Settings",
+ );
+ return page?.key === undefined ? undefined : { ...page, key: page.key };
+}
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/PullRequestRouteScreen.tsx b/apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx
index f3c47e2582858..d72cbe743f23e 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";
@@ -11,12 +12,9 @@ import { pullRequestTabOffset } from "./pullRequestTabScroll";
import { guideFocusedRows, type GuideDiffFocus } from "./guide/guideDiffFocus";
import { PullRequestGuideContent } from "./guide/PullRequestGuideScreen";
import { useReviewGuidesEnabled } from "./guide/useReviewGuide";
-import {
- filterPullRequestActivity,
- DEFAULT_ACTIVITY_FILTER,
- type ActivityFilter,
-} from "./pullRequestActivityFilter";
+import { filterPullRequestActivity, type ActivityFilter } from "./pullRequestActivityFilter";
import { PullRequestActivityFilters } from "./PullRequestActivityFilters";
+import { usePullRequestActivityFilter } from "./usePullRequestActivityFilter";
import type { LegendListRef } from "@legendapp/list/react-native";
import { AnimatedLegendList } from "@legendapp/list/reanimated";
import Animated from "react-native-reanimated";
@@ -142,15 +140,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",
@@ -384,14 +380,8 @@ export function PullRequestRouteScreen({ route }: StaticScreenProps
!guidesEnabled && tab === "guide" ? "overview" : tab;
const section = shown(chosenSection);
- const [activityFilter, setActivityFilter] = useState(() => {
- const kind = parsePullRequestAnchor(params.navigationUrl)?.kind;
- return kind === "timeline"
- ? { ...DEFAULT_ACTIVITY_FILTER, bots: true, resolved: true }
- : kind === "commits"
- ? { ...DEFAULT_ACTIVITY_FILTER, kind: "commits" }
- : DEFAULT_ACTIVITY_FILTER;
- });
+ const activity = usePullRequestActivityFilter(parsePullRequestAnchor(params.navigationUrl)?.kind);
+ const activityFilter = activity.filter;
const activityContent = usePullRequestActivityRows(params, activityFilter);
const scrollOffsets = useRef>({});
// The offset of the tab last shown, and which tab that was: a tab standing in for a hidden guide
@@ -443,10 +433,10 @@ export function PullRequestRouteScreen({ route }: StaticScreenProps ({ ...filter, kind: "all", bots: true, resolved: true }));
+ activity.showTimeline();
} else if (target?.kind === "commits") {
selectSection("activity");
- setActivityFilter((filter) => ({ ...filter, kind: "commits" }));
+ activity.showCommits();
} else if (target?.kind === "checks") {
selectSection("overview");
// Checks head Overview, which a reused screen may have scrolled past.
@@ -832,7 +822,7 @@ export function PullRequestRouteScreen({ route }: StaticScreenProps
) : null}
@@ -1012,6 +1002,7 @@ function PullRequestFileRouteContent({ route }: PullRequestFileRouteProps) {
!staleDiff &&
!detail.isPending &&
!result.isPending &&
+ !result.withheldRefetching &&
!result.error;
const activity = useEnvironmentQuery(composerPullRequests.activity(requestTarget(route.params)));
const baseData = useMemo(() => getCachedNativeReviewDiffData({ parsedDiff: parsed }), [parsed]);
@@ -1074,7 +1065,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
@@ -1331,6 +1330,10 @@ function PullRequestFileRouteContent({ route }: PullRequestFileRouteProps) {
});
else void viewed.toggle(file.path);
}}
+ onPressNotice={(event) => {
+ const file = data.files.find((file) => file.id === event.nativeEvent.fileId);
+ if (file) result.loadWithheldFile(file.path);
+ }}
onToggleComment={(event) => {
const id = event.nativeEvent.commentId;
if (id?.startsWith("discussion:"))
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/pullRequestDiffPages.test.ts b/apps/mobile/src/features/pull-requests/pullRequestDiffPages.test.ts
index 82027addc72cc..b0c91ab3ada9e 100644
--- a/apps/mobile/src/features/pull-requests/pullRequestDiffPages.test.ts
+++ b/apps/mobile/src/features/pull-requests/pullRequestDiffPages.test.ts
@@ -7,6 +7,8 @@ import {
combinePullRequestDiffPages,
getCachedPullRequestDiffPages,
retainPullRequestDiffPage,
+ withWithheldFiles,
+ type WithheldFileLoad,
} from "./pullRequestDiffPages";
const GITHUB = sourceControlClients.get("github").changeRequest;
@@ -156,4 +158,41 @@ describe("paged mobile pull request diffs", () => {
expect(refreshed).toHaveLength(1);
expect(refreshed[0]?.result.patch).toContain("changed.ts");
});
+
+ it("swaps a loaded withheld file in under its id and says what a tap does for the rest", () => {
+ const pages = [{ cursor: null, result: withheldDiff() }];
+ const parsed = combinePullRequestDiffPages(pages, new WeakMap(), "pr", GITHUB);
+ if (parsed.kind !== "files") throw new Error("Expected structured diff");
+ const placeholder = parsed.files[0];
+ let merged: ReviewParsedDiff = parsed;
+ const fileWith = (load: WithheldFileLoad | undefined, canLoad = true) => {
+ merged = withWithheldFiles(
+ parsed,
+ new Map(load === undefined ? [] : [["large.ts", load]]),
+ canLoad,
+ "pr",
+ );
+ return merged.kind === "files" ? merged.files[0] : undefined;
+ };
+ expect(fileWith(undefined)).toMatchObject({
+ notice: "Diff too large to display. Tap to load it.",
+ noticeTone: "warning",
+ noticeActionable: true,
+ });
+ expect(fileWith(undefined, false)).toMatchObject({
+ notice: "Diff too large to display here.",
+ noticeActionable: false,
+ });
+ expect(fileWith({ status: "loading" })).toMatchObject({ noticeActionable: false });
+ expect(fileWith({ status: "error" })).toMatchObject({
+ notice: "Couldn't load this diff. Tap to try again.",
+ noticeActionable: true,
+ });
+ const loaded = fileWith({ status: "loaded", result: diff("large.ts") });
+ expect(loaded).toMatchObject({ id: placeholder?.id, path: "large.ts" });
+ expect(loaded?.notice).toBeUndefined();
+ expect(loaded?.rows.length).toBeGreaterThan(0);
+ // The totals follow the loaded file, which may have changed since the page was read.
+ expect(merged).toMatchObject({ additions: 1, deletions: 1 });
+ });
});
diff --git a/apps/mobile/src/features/pull-requests/pullRequestDiffPages.ts b/apps/mobile/src/features/pull-requests/pullRequestDiffPages.ts
index 9abf7cfc0c074..8ec7cea70bf32 100644
--- a/apps/mobile/src/features/pull-requests/pullRequestDiffPages.ts
+++ b/apps/mobile/src/features/pull-requests/pullRequestDiffPages.ts
@@ -1,6 +1,10 @@
import type { ChangeRequestTerminology } from "@t3tools/client-runtime/source-control-clients";
import type { PullRequestDiffResult } from "@t3tools/contracts";
-import { buildReviewParsedDiff, type ReviewParsedDiff } from "../review/reviewModel";
+import {
+ buildReviewParsedDiff,
+ type ReviewParsedDiff,
+ type ReviewRenderableFile,
+} from "../review/reviewModel";
export interface PullRequestDiffPage {
readonly cursor: string | null;
@@ -61,6 +65,7 @@ export function retainPullRequestDiffPage(
(previous?.patch === result.patch &&
previous.truncated === result.truncated &&
previous.nextCursor === result.nextCursor &&
+ previous.withheldFilesReadable === result.withheldFilesReadable &&
JSON.stringify(previous.omittedFileStats ?? []) ===
JSON.stringify(result.omittedFileStats ?? []))
)
@@ -84,7 +89,13 @@ export function combinePullRequestDiffPages(
);
const files = value.files.map((file) => {
const stat = omittedFileStats.get(file.path);
- return stat ? { ...file, additions: stat.additions, deletions: stat.deletions } : file;
+ if (!stat) return file;
+ return {
+ ...file,
+ additions: stat.additions,
+ deletions: stat.deletions,
+ ...(file.rows.length === 0 ? { withheld: true } : {}),
+ };
});
value = {
...value,
@@ -111,3 +122,63 @@ export function combinePullRequestDiffPages(
: null,
};
}
+
+export type WithheldFileLoad =
+ | { readonly status: "loading" | "error" }
+ | { readonly status: "loaded"; readonly result: PullRequestDiffResult };
+
+const withheldFileParses = new WeakMap();
+
+function parseWithheldFile(result: PullRequestDiffResult, scope: string) {
+ if (withheldFileParses.has(result)) return withheldFileParses.get(result) ?? null;
+ const parsed = buildReviewParsedDiff(result.patch, scope);
+ const file =
+ parsed.kind === "files" ? (parsed.files.find((entry) => entry.rows.length > 0) ?? null) : null;
+ withheldFileParses.set(result, file);
+ return file;
+}
+
+function withheldFileNotice(load: WithheldFileLoad | undefined, canLoad: boolean): string {
+ if (load === undefined) {
+ return canLoad
+ ? "Diff too large to display. Tap to load it."
+ : "Diff too large to display here.";
+ }
+ if (load.status === "loading") return "Loading diff…";
+ if (load.status === "error") return "Couldn't load this diff. Tap to try again.";
+ return "No text diff for this file.";
+}
+
+/**
+ * Puts each loaded withheld file in place of its empty one, under the same id so folds and
+ * targets hold, and gives the rest a notice saying what a tap does.
+ */
+export function withWithheldFiles(
+ parsed: ReviewParsedDiff,
+ loads: ReadonlyMap,
+ canLoad: boolean,
+ scope: string,
+): ReviewParsedDiff {
+ if (parsed.kind !== "files" || !parsed.files.some((file) => file.withheld)) return parsed;
+ const files = parsed.files.map((file): ReviewRenderableFile => {
+ if (!file.withheld) return file;
+ const load = loads.get(file.path);
+ const loaded =
+ load?.status === "loaded"
+ ? parseWithheldFile(load.result, `${scope}:withheld:${file.path}`)
+ : null;
+ if (loaded !== null) return { ...loaded, id: file.id };
+ return {
+ ...file,
+ notice: withheldFileNotice(load, canLoad),
+ noticeTone: "warning",
+ noticeActionable: canLoad && (load === undefined || load.status === "error"),
+ };
+ });
+ return {
+ ...parsed,
+ files,
+ additions: files.reduce((total, file) => total + file.additions, 0),
+ deletions: files.reduce((total, file) => total + file.deletions, 0),
+ };
+}
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/usePullRequestActivityFilter.ts b/apps/mobile/src/features/pull-requests/usePullRequestActivityFilter.ts
new file mode 100644
index 0000000000000..1f2d0d8582de1
--- /dev/null
+++ b/apps/mobile/src/features/pull-requests/usePullRequestActivityFilter.ts
@@ -0,0 +1,52 @@
+import { useAtomSet, useAtomValue } from "@effect/atom-react";
+import { AsyncResult } from "effect/reactivity";
+import { useState } from "react";
+import type { PullRequestActivityVisibility } from "../../persistence/mobile-preferences";
+import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences";
+import { DEFAULT_ACTIVITY_FILTER, type ActivityFilter } from "./pullRequestActivityFilter";
+
+const SHOW_EVERYTHING: PullRequestActivityVisibility = { bots: true, resolved: true };
+
+/**
+ * Bot and resolved visibility is a saved preference. A timeline link shows everything for this
+ * screen only, until the user picks visibility themselves.
+ */
+export function usePullRequestActivityFilter(link: string | undefined) {
+ const preferences = useAtomValue(mobilePreferencesAtom);
+ const savePreferences = useAtomSet(updateMobilePreferencesAtom);
+ const [view, setView] = useState(() => ({
+ kind: link === "commits" ? ("commits" as const) : DEFAULT_ACTIVITY_FILTER.kind,
+ newestFirst: DEFAULT_ACTIVITY_FILTER.newestFirst,
+ linkVisibility: link === "timeline" ? SHOW_EVERYTHING : null,
+ }));
+ const saved = AsyncResult.isSuccess(preferences)
+ ? preferences.value.pullRequestActivityVisibility
+ : undefined;
+ const visibility = view.linkVisibility ?? saved ?? DEFAULT_ACTIVITY_FILTER;
+ const filter: ActivityFilter = {
+ kind: view.kind,
+ newestFirst: view.newestFirst,
+ bots: visibility.bots,
+ resolved: visibility.resolved,
+ };
+ const visibilityChanged = (next: ActivityFilter) =>
+ next.bots !== filter.bots || next.resolved !== filter.resolved;
+ return {
+ filter,
+ setFilter: (next: ActivityFilter) => {
+ if (visibilityChanged(next)) {
+ savePreferences({
+ pullRequestActivityVisibility: { bots: next.bots, resolved: next.resolved },
+ });
+ }
+ setView((current) => ({
+ kind: next.kind,
+ newestFirst: next.newestFirst,
+ linkVisibility: visibilityChanged(next) ? null : current.linkVisibility,
+ }));
+ },
+ showTimeline: () =>
+ setView((current) => ({ ...current, kind: "all", linkVisibility: SHOW_EVERYTHING })),
+ showCommits: () => setView((current) => ({ ...current, kind: "commits" })),
+ };
+}
diff --git a/apps/mobile/src/features/pull-requests/usePullRequestDiff.ts b/apps/mobile/src/features/pull-requests/usePullRequestDiff.ts
index 6e49993a137f3..f091e5b6847d6 100644
--- a/apps/mobile/src/features/pull-requests/usePullRequestDiff.ts
+++ b/apps/mobile/src/features/pull-requests/usePullRequestDiff.ts
@@ -5,8 +5,9 @@ import {
type PullRequestListEntry,
type PullRequestSummary,
} from "@t3tools/contracts";
-import { useAtomRefresh } from "@effect/atom-react";
-import { useLayoutEffect, useMemo, useState } from "react";
+import { RegistryContext, useAtomRefresh, useAtomValue } from "@effect/atom-react";
+import { Atom } from "effect/reactivity";
+import { useContext, useLayoutEffect, useMemo, useState } from "react";
import { composerPullRequests } from "../../state/pull-requests";
import { useEnvironmentQuery } from "../../state/query";
@@ -14,7 +15,9 @@ import { usePullToRefresh } from "../../state/use-pull-to-refresh";
import {
getCachedPullRequestDiffPages,
retainPullRequestDiffPage,
+ withWithheldFiles,
type PullRequestDiffPage,
+ type WithheldFileLoad,
} from "./pullRequestDiffPages";
export type PullRequestParams = {
@@ -43,6 +46,26 @@ export function pullRequestTarget(params: PullRequestParams) {
}
const NO_PAGES: readonly PullRequestDiffPage[] = [];
+const NO_PATHS: readonly string[] = [];
+
+type PullRequestDiffTarget = Parameters[0];
+
+// Keyed by the diff's serialized target, which the hook already holds as its scope.
+const withheldFileDiff = (targetKey: string, path: string) => {
+ const target = JSON.parse(targetKey) as PullRequestDiffTarget;
+ return composerPullRequests.diff({ ...target, input: { ...target.input, path } });
+};
+
+// One read per withheld file the reader asked for, so only that file's diff crosses the wire.
+const withheldFileDiffsAtom = Atom.family((key: string) => {
+ const { targetKey, paths } = JSON.parse(key) as {
+ readonly targetKey: string;
+ readonly paths: readonly string[];
+ };
+ return Atom.make((get) => paths.map((path) => get(withheldFileDiff(targetKey, path)))).pipe(
+ Atom.withLabel(`mobile:pull-request-withheld-file-diffs:${key}`),
+ );
+});
export function usePullRequestDiffEntry(navigation: {
readonly addListener: (
@@ -116,10 +139,46 @@ export function usePullRequestDiff(
}, [cursor, key, query.data, state.key, state.pages]);
if (state.key !== key || state.pages !== pages) setState({ key, cursor, pages });
- const parsed = useMemo(
+ const [withheldLoads, setWithheldLoads] = useState<{
+ readonly key: string;
+ readonly paths: readonly string[];
+ }>({ key: "", paths: NO_PATHS });
+ const withheldPaths = withheldLoads.key === key ? withheldLoads.paths : NO_PATHS;
+ const withheldResults = useAtomValue(
+ withheldFileDiffsAtom(JSON.stringify({ targetKey: key, paths: withheldPaths })),
+ );
+ const registry = useContext(RegistryContext);
+ const refreshWithheldFiles = () => {
+ for (const path of withheldPaths) registry.refresh(withheldFileDiff(key, path));
+ };
+ const loadWithheldFile = (path: string) => {
+ // The read is keyed without the head, so even a first load must not reuse an older one.
+ registry.refresh(withheldFileDiff(key, path));
+ if (!withheldPaths.includes(path)) setWithheldLoads({ key, paths: [...withheldPaths, path] });
+ };
+ // A refetch keeps showing the last patch, whose lines may not exist at the new head.
+ const withheldRefetching = withheldResults.some((result) => result.waiting);
+ const loads = new Map();
+ withheldPaths.forEach((path, index) => {
+ const result = withheldResults[index];
+ if (result === undefined) return;
+ // A failed refetch still carries the last patch; show the failure instead.
+ loads.set(
+ path,
+ result._tag === "Failure"
+ ? { status: "error" }
+ : result._tag === "Success"
+ ? { status: "loaded", result: result.value }
+ : { status: "loading" },
+ );
+ });
+ const pagesParsed = useMemo(
() => getCachedPullRequestDiffPages(pages, key, terminology),
[key, pages, terminology],
);
+ // The server says whether a withheld file can be read alone; GitHub may refuse the whole diff.
+ const withheldFilesReadable = pages[0]?.result.withheldFilesReadable === true;
+ const parsed = withWithheldFiles(pagesParsed, loads, withheldFilesReadable, key);
const patch = useMemo(() => pages.map((page) => page.result.patch).join("\n"), [pages]);
const nextCursor = pages.at(-1)?.result.nextCursor ?? null;
const canLoadMore =
@@ -136,15 +195,19 @@ export function usePullRequestDiff(
}
setState({ key, cursor: null, pages: NO_PAGES });
refreshFirstPage();
+ refreshWithheldFiles();
};
const onPullRefresh = () => {
setState({ key, cursor: null, pages: NO_PAGES });
onRefresh();
+ refreshWithheldFiles();
};
return {
...query,
refresh,
parsed,
+ loadWithheldFile,
+ withheldRefetching,
patch,
nextCursor,
canLoadMore,
diff --git a/apps/mobile/src/features/pull-requests/usePullRequestList.ts b/apps/mobile/src/features/pull-requests/usePullRequestList.ts
index d4fe1ab3461bd..8ba0721fd7fb5 100644
--- a/apps/mobile/src/features/pull-requests/usePullRequestList.ts
+++ b/apps/mobile/src/features/pull-requests/usePullRequestList.ts
@@ -1,3 +1,8 @@
+import {
+ editHeldPullRequestListEntries,
+ pullRequestHostAnswer,
+ pullRequestPendingEditsFor,
+} from "@t3tools/client-runtime/state/pull-requests";
import { RegistryContext, useAtomMount, useAtomSubscribe, useAtomValue } from "@effect/atom-react";
import { executeAtomQuery, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
import type { EnvironmentId, PullRequestDiffStat, PullRequestListInput } from "@t3tools/contracts";
@@ -31,7 +36,10 @@ type Read = (atom: Atom.Atom) => A;
/** The head the list query holds now, cached or answered. */
function currentHead(read: Read, target: ListTarget) {
- return AsyncResult.getOrElse(read(composerPullRequests.list(target)), () => null);
+ return AsyncResult.getOrElse(
+ read(pullRequestHostAnswer(composerPullRequests.list(target))),
+ () => null,
+ );
}
function currentPages(read: Read, target: ListTarget): PullRequestListPages | null {
@@ -44,12 +52,23 @@ function currentPages(read: Read, target: ListTarget): PullRequestListPages | nu
const sourcesFamily = Atom.family((key: string) => {
const targets: readonly ListTarget[] = JSON.parse(key);
return Atom.make((get) =>
- targets.map((target) => ({
- target,
- result: get(composerPullRequests.list(target)),
- pages: currentPages(get, target),
- stats: get(pullRequestListStatsFamily(target.environmentId)),
- })),
+ targets.map((target) => {
+ const pages = currentPages(get, target);
+ return {
+ target,
+ result: get(composerPullRequests.list(target)),
+ pages:
+ pages === null
+ ? null
+ : {
+ ...pages,
+ entries: editHeldPullRequestListEntries(target.input, pages.entries, (entry) =>
+ get(pullRequestPendingEditsFor(target.environmentId, entry)),
+ ),
+ },
+ stats: get(pullRequestListStatsFamily(target.environmentId)),
+ };
+ }),
);
});
@@ -71,7 +90,7 @@ async function loadNextPages(
continuations(registry, targets).map(async ({ target, pages, input }) => {
const response = await executeAtomQuery(
registry,
- composerPullRequests.list({ ...target, input }),
+ pullRequestHostAnswer(composerPullRequests.list({ ...target, input })),
{
signal,
refresh: retry,
@@ -113,11 +132,15 @@ async function refreshHeads(
input: {},
});
if (signal.aborted) return;
- const response = await executeAtomQuery(registry, composerPullRequests.list(target), {
- refresh: true,
- signal,
- reportFailure: false,
- });
+ const response = await executeAtomQuery(
+ registry,
+ pullRequestHostAnswer(composerPullRequests.list(target)),
+ {
+ refresh: true,
+ signal,
+ reportFailure: false,
+ },
+ );
if (signal.aborted) return;
if (response._tag === "Failure") throw squashAtomCommandFailure(response);
registry.set(
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..63372efb661bc 100644
--- a/apps/mobile/src/features/review/nativeReviewDiffAdapter.ts
+++ b/apps/mobile/src/features/review/nativeReviewDiffAdapter.ts
@@ -1,3 +1,4 @@
+import { cutLineNoteStart } from "@t3tools/shared/diffCutLines";
import type { NativeReviewDiffRow, NativeReviewDiffTheme } from "../diffs/nativeReviewDiffSurface";
import type { NativeReviewDiffFile } from "../diffs/nativeReviewDiffTypes";
import * as Arr from "effect/Array";
@@ -44,6 +45,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;
@@ -200,6 +227,8 @@ export function createNativeReviewDiffTheme(
deleteBar: terminalRed ?? "#ff2e3f",
addText: "#5ECC71",
deleteText: "#FF6762",
+ warningText: nativeColor(appTheme["--color-warning-foreground"]),
+ warningBackground: nativeColor(appTheme["--color-warning"]),
};
}
@@ -217,6 +246,8 @@ export function createNativeReviewDiffTheme(
deleteBar: terminalRed ?? "#ff2e3f",
addText: "#199F43",
deleteText: "#D52C36",
+ warningText: nativeColor(appTheme["--color-warning-foreground"]),
+ warningBackground: nativeColor(appTheme["--color-warning"]),
};
}
@@ -244,7 +275,15 @@ function createNoticeRow(fileId: string, suffix: string, text: string): NativeRe
}
function noticeRowsForFile(file: ReviewRenderableFile): ReadonlyArray {
- if (file.notice) return [createNoticeRow(file.id, "loading", file.notice)];
+ if (file.notice) {
+ return [
+ {
+ ...createNoticeRow(file.id, "loading", file.notice),
+ ...(file.noticeTone === undefined ? {} : { tone: file.noticeTone }),
+ ...(file.noticeActionable ? { actionable: true } : {}),
+ },
+ ];
+ }
if (file.rows.length > 0) {
return [];
}
@@ -362,6 +401,7 @@ function mapLineRow(
row: ReviewRenderableLineRow,
rowIndex: number,
): NativeReviewDiffRow {
+ const noteStart = cutLineNoteStart(row.content);
return {
kind: "line",
id: `${file.id}:line:${rowIndex}:${row.id}`,
@@ -370,6 +410,7 @@ function mapLineRow(
change: row.change,
oldLineNumber: row.oldLineNumber,
newLineNumber: row.newLineNumber,
+ ...(noteStart === null ? {} : { noteStart }),
};
}
diff --git a/apps/mobile/src/features/review/reviewModel.ts b/apps/mobile/src/features/review/reviewModel.ts
index df3c7c51324b4..3a1028dbb1730 100644
--- a/apps/mobile/src/features/review/reviewModel.ts
+++ b/apps/mobile/src/features/review/reviewModel.ts
@@ -56,6 +56,11 @@ export interface ReviewRenderableFile {
readonly id: string;
readonly cacheKey: string;
readonly notice?: string;
+ readonly noticeTone?: "warning";
+ /** The notice row reports taps, as for loading a withheld file's diff. */
+ readonly noticeActionable?: boolean;
+ /** The host left out this file's hunks as too large; it can be loaded on its own. */
+ readonly withheld?: boolean;
readonly path: string;
readonly previousPath: string | null;
readonly changeType: ChangeTypes;
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/SettingsAboutRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsAboutRouteScreen.tsx
index 096513c0e0a3c..96f4cedb9bd88 100644
--- a/apps/mobile/src/features/settings/SettingsAboutRouteScreen.tsx
+++ b/apps/mobile/src/features/settings/SettingsAboutRouteScreen.tsx
@@ -1,5 +1,6 @@
import * as Dialog from "../../components/ui/Dialog";
import { ScreenScrollView as ScrollView } from "../../components/ui/ScreenScrollView";
+import * as Application from "expo-application";
import Constants from "expo-constants";
import { settlePromise } from "@t3tools/client-runtime/state/runtime";
import { useRef, useState } from "react";
@@ -53,7 +54,10 @@ function AppSettingsSection() {
// Match app.config.ts's production fallback to avoid mislabeling builds as development.
const variant = (Constants.expoConfig?.extra?.appVariant as string | undefined) ?? "production";
const variantLabel = variant === "production" ? "" : capitalize(variant);
- const versionLabel = variantLabel ? `${version} · ${variantLabel}` : version;
+ // EAS assigns build numbers remotely; only the installed binary knows its own.
+ const build = Application.nativeBuildVersion;
+ const versionWithBuild = build ? `${version} (${build})` : version;
+ const versionLabel = variantLabel ? `${versionWithBuild} · ${variantLabel}` : versionWithBuild;
const updateCheckAvailable = isAppUpdateCheckAvailable();
const busy =
updateState === "checking" || updateState === "downloading" || updateState === "restarting";
diff --git a/apps/mobile/src/features/settings/SettingsClientStorageRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsClientStorageRouteScreen.tsx
index c0f93d2ee324d..1b34022d4cae5 100644
--- a/apps/mobile/src/features/settings/SettingsClientStorageRouteScreen.tsx
+++ b/apps/mobile/src/features/settings/SettingsClientStorageRouteScreen.tsx
@@ -72,10 +72,10 @@ export function SettingsClientStorageRouteScreen() {
{AsyncResult.isFailure(summaryResult) ? (
diff --git a/apps/mobile/src/features/settings/SettingsLanguageRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsLanguageRouteScreen.tsx
index cb0ecbb6d8c01..99c442e144cfb 100644
--- a/apps/mobile/src/features/settings/SettingsLanguageRouteScreen.tsx
+++ b/apps/mobile/src/features/settings/SettingsLanguageRouteScreen.tsx
@@ -8,9 +8,36 @@ import { SYSTEM_LANGUAGE, nativeLanguageName } from "@t3tools/client-runtime/loc
import { SUPPORTED_LOCALES } from "../../i18n/locales";
import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences";
import { ListChoiceRow as SettingsChoiceRow } from "../../components/ui/ListChoiceRow";
+import { SettingsRow } from "./components/SettingsRow";
import { SettingsSection } from "./components/SettingsSection";
import { SettingsScreen } from "./components/SettingsScreen";
+/** General's row that opens the language picker, showing the current choice. */
+export function LanguageSettingsSection() {
+ return (
+
+
+
+ );
+}
+
+function LanguageRow() {
+ const gt = useGT();
+ const language = useLanguagePreference();
+ return (
+
+
+
+ );
+}
+
export function SettingsLanguageRouteScreen() {
return (
diff --git a/apps/mobile/src/features/settings/SettingsProjectGroupingRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsProjectGroupingRouteScreen.tsx
index 9d49650e1a67a..d374727fd4b3a 100644
--- a/apps/mobile/src/features/settings/SettingsProjectGroupingRouteScreen.tsx
+++ b/apps/mobile/src/features/settings/SettingsProjectGroupingRouteScreen.tsx
@@ -12,6 +12,7 @@ import {
import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences";
import { ListChoiceRow as SettingsChoiceRow } from "../../components/ui/ListChoiceRow";
import { SettingsSection } from "./components/SettingsSection";
+import { LanguageSettingsSection } from "./SettingsLanguageRouteScreen";
import { NewThreadSettingsSection, WorkingSectionSettings } from "./ThreadSettingsSections";
const GROUPING_OPTIONS: ReadonlyArray<{
@@ -54,6 +55,7 @@ export function SettingsProjectGroupingRouteScreen() {
contentContainerClassName="gap-3 px-5 pt-4"
contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 18) + 18 }}
>
+
{GROUPING_OPTIONS.map((option, index) => (
group.key === selectedProjectKey);
@@ -273,11 +270,6 @@ function useSettingsIndexSections(): SettingsListSection[] {
rows: [
page("SettingsOrganization", "gearshape", gt("General")),
page("SettingsAppearance", "paintbrush", gt("Appearance")),
- page("SettingsLanguage", "globe", gt("Language"), {
- value: SUPPORTED_LOCALES.includes(language)
- ? nativeLanguageName(language)
- : gt("System default"),
- }),
page("SettingsFollowUp", "bubble.left.and.bubble.right", gt("Chat")),
...(navigationCustomizationAvailable()
? [page("SettingsNavigation", "line.3.horizontal", gt("Navigation tabs"))]
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/settings/settings-search.ts b/apps/mobile/src/features/settings/settings-search.ts
index 49e1a8dbe082e..77fbdfd7be975 100644
--- a/apps/mobile/src/features/settings/settings-search.ts
+++ b/apps/mobile/src/features/settings/settings-search.ts
@@ -33,7 +33,6 @@ const SETTINGS_SEARCH_TERMS = {
"zen",
"final answers only",
],
- SettingsLanguage: ["language", "locale", "translation", "english"],
SettingsNavigation: ["tabs", "tab order", "reorder", "hide tabs"],
SettingsKeyboard: ["return key", "send message", "new line", "hardware keyboard"],
SettingsVoice: [
@@ -53,6 +52,10 @@ const SETTINGS_SEARCH_TERMS = {
SettingsScheduledTasks: ["automations", "schedule", "cron", "recurring", "webhook"],
SettingsProjectOverview: ["project", "overview", "checkouts", "delete project"],
SettingsOrganization: [
+ "language",
+ "locale",
+ "translation",
+ "english",
"project grouping",
"group projects",
"organization",
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..f3ed8b01983ca 100644
--- a/apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx
+++ b/apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx
@@ -2,6 +2,7 @@ import * as Dialog from "../../components/ui/Dialog";
import {
AuthTerminalReadScope,
AuthTerminalOperateScope,
+ chunkTerminalWrite,
DEFAULT_TERMINAL_ID,
EnvironmentId,
ThreadId,
@@ -40,7 +41,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 +64,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 +382,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;
@@ -607,15 +608,21 @@ function ThreadTerminal(props: {
return false;
}
- const result = await writeTerminal({
- environmentId: selectedThread.environmentId,
- input: {
- threadId: selectedThread.id,
- terminalId,
- data,
- },
- });
- return result._tag === "Success";
+ // Android's IME delivers a system paste as one input, which can exceed one write.
+ const isSameShell = pasteSession.liveness();
+ for (const chunk of chunkTerminalWrite(data)) {
+ if (!isSameShell()) return false;
+ const result = await writeTerminal({
+ environmentId: selectedThread.environmentId,
+ input: {
+ threadId: selectedThread.id,
+ terminalId,
+ data: chunk,
+ },
+ });
+ if (result._tag !== "Success") return false;
+ }
+ return true;
};
const pasteText = async (readText: () => Promise) => {
@@ -893,7 +900,7 @@ function ThreadTerminal(props: {
title="No terminal sessions"
detail="Existing terminals will appear here when another client opens one."
/>
- ) : !canOperateTerminal && terminal.error !== null ? (
+ ) : terminal.error !== null && (!canOperateTerminal || terminal.status === "error") ? (
) : (
<>
diff --git a/apps/mobile/src/features/terminal/terminalInput.test.ts b/apps/mobile/src/features/terminal/terminalInput.test.ts
index 17fabe588115c..6e5046dab35c4 100644
--- a/apps/mobile/src/features/terminal/terminalInput.test.ts
+++ b/apps/mobile/src/features/terminal/terminalInput.test.ts
@@ -1,11 +1,6 @@
import { describe, expect, it } from "vite-plus/test";
-import {
- chunkTerminalWrite,
- encodeTerminalPaste,
- resolveModifiedTerminalInput,
- TERMINAL_WRITE_MAX_LENGTH,
-} from "./terminalInput";
+import { encodeTerminalPaste, resolveModifiedTerminalInput } from "./terminalInput";
const byte = (code: number) => String.fromCharCode(code);
const ESC = byte(0x1b);
@@ -78,23 +73,3 @@ describe("encodeTerminalPaste", () => {
expect(encodeTerminalPaste(`safe${ESC}[201~; rm -rf /\n`)).toBe("safe [201~; rm -rf /\r");
});
});
-
-describe("chunkTerminalWrite", () => {
- it("splits oversized writes so every chunk fits the contract", () => {
- const chunks = chunkTerminalWrite("y".repeat(TERMINAL_WRITE_MAX_LENGTH * 2 + 5));
- expect(chunks.map((chunk) => chunk.length)).toEqual([
- TERMINAL_WRITE_MAX_LENGTH,
- TERMINAL_WRITE_MAX_LENGTH,
- 5,
- ]);
- expect(chunks.join("")).toHaveLength(TERMINAL_WRITE_MAX_LENGTH * 2 + 5);
- });
-
- it("does not cut a surrogate pair in half at the boundary", () => {
- const data = `${"z".repeat(TERMINAL_WRITE_MAX_LENGTH - 1)}😀tail`;
- const chunks = chunkTerminalWrite(data);
- expect(chunks[0]).toHaveLength(TERMINAL_WRITE_MAX_LENGTH - 1);
- expect(chunks[1]).toBe("😀tail");
- expect(chunks.join("")).toBe(data);
- });
-});
diff --git a/apps/mobile/src/features/terminal/terminalInput.ts b/apps/mobile/src/features/terminal/terminalInput.ts
index 9c5e05dcc24f0..0f09d109e3634 100644
--- a/apps/mobile/src/features/terminal/terminalInput.ts
+++ b/apps/mobile/src/features/terminal/terminalInput.ts
@@ -3,9 +3,6 @@ import type { ExecutionEnvironmentPlatformOs } from "@t3tools/contracts";
export type PendingModifier = "ctrl" | "meta";
export type HostPlatform = "mac" | "linux" | "windows" | "unknown";
-/** Upper bound of `TerminalWriteInput.data`; longer writes are rejected by the server. */
-export const TERMINAL_WRITE_MAX_LENGTH = 65_536;
-
export type ModifiedTerminalInput =
| { readonly kind: "write"; readonly data: string }
| { readonly kind: "paste" };
@@ -64,21 +61,6 @@ export function encodeTerminalPaste(text: string): string {
return text.replace(UNSAFE_PASTE_BYTES, " ").replace(/\r\n|\n/g, "\r");
}
-export function chunkTerminalWrite(data: string): ReadonlyArray {
- const chunks: string[] = [];
- let start = 0;
- while (start < data.length) {
- let end = Math.min(start + TERMINAL_WRITE_MAX_LENGTH, data.length);
- const last = data.charCodeAt(end - 1);
- if (end < data.length && last >= 0xd800 && last <= 0xdbff) {
- end -= 1;
- }
- chunks.push(data.slice(start, end));
- start = end;
- }
- return chunks;
-}
-
/** Returns null for unknown OSes so callers can try weaker signals. */
export function hostPlatformFromOs(os: ExecutionEnvironmentPlatformOs | null): HostPlatform | null {
if (os === "darwin") return "mac";
diff --git a/apps/mobile/src/features/terminal/terminalPaste.test.ts b/apps/mobile/src/features/terminal/terminalPaste.test.ts
index ec9bd9d74d933..2545085137916 100644
--- a/apps/mobile/src/features/terminal/terminalPaste.test.ts
+++ b/apps/mobile/src/features/terminal/terminalPaste.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vite-plus/test";
-import { TERMINAL_WRITE_MAX_LENGTH } from "./terminalInput";
+import { TERMINAL_WRITE_MAX_LENGTH } from "@t3tools/contracts";
import { createTerminalPasteSession } from "./terminalPaste";
function deferred() {
@@ -34,6 +34,15 @@ describe("terminal paste session", () => {
expect(writes).toEqual([]);
});
+ it("reports a liveness change after capture, including a restart in place", () => {
+ const session = createTerminalPasteSession();
+ session.reset(true);
+ const isSameShell = session.liveness();
+ expect(isSameShell()).toBe(true);
+ session.reset(true);
+ expect(isSameShell()).toBe(false);
+ });
+
it("never overlaps writes from rapid paste requests", async () => {
const session = createTerminalPasteSession();
session.reset(true);
diff --git a/apps/mobile/src/features/terminal/terminalPaste.ts b/apps/mobile/src/features/terminal/terminalPaste.ts
index d070bdc168826..b09e365587d57 100644
--- a/apps/mobile/src/features/terminal/terminalPaste.ts
+++ b/apps/mobile/src/features/terminal/terminalPaste.ts
@@ -1,4 +1,6 @@
-import { chunkTerminalWrite, encodeTerminalPaste } from "./terminalInput";
+import { chunkTerminalWrite } from "@t3tools/contracts";
+
+import { encodeTerminalPaste } from "./terminalInput";
interface TerminalPasteInput {
readonly readText: () => Promise;
@@ -8,6 +10,8 @@ interface TerminalPasteInput {
export interface TerminalPasteSession {
readonly reset: (active: boolean) => void;
+ /** True until the terminal's liveness changes (stop, start or restart) after this call. */
+ readonly liveness: () => () => boolean;
readonly paste: (input: TerminalPasteInput) => Promise;
}
@@ -21,6 +25,11 @@ export function createTerminalPasteSession(): TerminalPasteSession {
liveTarget = active ? {} : null;
},
+ liveness() {
+ const target = liveTarget;
+ return () => liveTarget === target;
+ },
+
async paste({ readText, write, onReadError }) {
const target = liveTarget;
if (target === 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/PendingUserInputCard.tsx b/apps/mobile/src/features/threads/PendingUserInputCard.tsx
index 12640fdb6e7e8..a486948e18f8b 100644
--- a/apps/mobile/src/features/threads/PendingUserInputCard.tsx
+++ b/apps/mobile/src/features/threads/PendingUserInputCard.tsx
@@ -170,6 +170,16 @@ export function PendingUserInputCard(props: PendingUserInputCardProps) {
}));
const overlayHeightStyle = useAnimatedStyle(() => ({ height: maxHeight.value }));
+ const stopButton = props.onStopThread ? (
+
+ ) : null;
const bar = (
- {props.onStopThread ? (
-
- ) : null}
+ {stopButton}
);
const card = (
@@ -221,27 +222,32 @@ export function PendingUserInputCard(props: PendingUserInputCardProps) {
className="overflow-hidden gap-2.5 rounded-[20px] border border-border bg-card-alt p-4"
style={cardAnimatedStyle}
>
-
-
-
- User input needed
-
- Fill in the pending answers
-
-
-
-
-
+
+
+
+
+ User input needed
+
+
+ Fill in the pending answers
+
+
+
+
+
+
+ {stopButton}
+
{
if (
scope.active &&
diff --git a/apps/mobile/src/features/threads/SubagentRow.tsx b/apps/mobile/src/features/threads/SubagentRow.tsx
index 7c71ac2680de1..77097c565aa09 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";
@@ -126,6 +128,9 @@ function SubagentMetadata(props: {
(candidate) => candidate.instanceId === subagent.providerInstanceId,
);
const showBadge = provider !== undefined && shouldShowInstanceBadge(provider, providers);
+ // A remote task's own driver is only a "remote" label.
+ const driver =
+ provider?.driver ?? (subagent.remoteChild === undefined ? subagent.driver : undefined);
const parent = useThreadShell(scopeThreadRef(environmentId, subagent.threadId))?.source;
const child = useThreadShell(
subagent.childThreadId === null ? null : scopeThreadRef(environmentId, subagent.childThreadId),
@@ -156,12 +161,10 @@ function SubagentMetadata(props: {
accentColor={provider.accentColor}
showBadge
/>
+ ) : driver === undefined ? (
+
) : (
-
+
)}
{provider ? `${resolveProviderInstanceDisplayName(provider)} · ` : ""}
diff --git a/apps/mobile/src/features/threads/ThreadComposer.tsx b/apps/mobile/src/features/threads/ThreadComposer.tsx
index e8f3c1152596e..18a63f9e6dc5f 100644
--- a/apps/mobile/src/features/threads/ThreadComposer.tsx
+++ b/apps/mobile/src/features/threads/ThreadComposer.tsx
@@ -15,6 +15,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,
@@ -29,6 +30,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";
@@ -66,6 +68,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";
@@ -78,7 +81,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,
@@ -89,7 +97,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";
@@ -140,7 +148,11 @@ function collapsedEditorInset(text: ScaledTextRole): number {
return Math.max(0, Math.round(COLLAPSED_EDITOR_DEFAULT_INSET - shift));
}
-function useCompactComposerEditor(text: ScaledTextRole, value: string) {
+const EXPANDED_EDITOR_INSET = 14;
+// Room under the expanded editor for the toolbar row.
+const EXPANDED_EDITOR_BOTTOM = 52;
+
+function useCompactComposerEditor(text: ScaledTextRole, value: string, animate: boolean) {
const [contentSize, setContentSize] = useState({ width: 0, height: 0 });
const [compactWidth, setCompactWidth] = useState(0);
const contentHeight = contentSize.height;
@@ -161,25 +173,55 @@ function useCompactComposerEditor(text: ScaledTextRole, value: string) {
(contentHeight > text.lineHeight * 1.5 ||
(compactWidth > 0 && contentSize.width > compactWidth));
const compactRowHeight = Math.max(44, minimum);
+ const compactBottom = (compactRowHeight - minimum) / 2;
const isRTL = I18nManager.isRTL;
- const editorStyle = useAnimatedStyle(() => ({
- position: "absolute",
- overflow: "hidden",
- height,
- ...(isExpanded
- ? { left: 14, right: 14 }
- : compactEditorInsets({
- slotX: editorX.value,
- slotWidth: editorWidth.value,
- rowWidth: rowWidth.value,
- isRTL,
- })),
- // The full-width editor must move above the controls in the same frame it widens.
- bottom: isExpanded ? 52 : (compactRowHeight - minimum) / 2,
+ const expandedRowHeight = height + EXPANDED_EDITOR_BOTTOM;
+ const expansion = useDerivedValue(() => {
+ const target = isExpanded ? 1 : 0;
+ return animate
+ ? withTiming(target, {
+ duration: COMPOSER_TRANSITION_DURATION_MS,
+ reduceMotion: ReduceMotion.System,
+ })
+ : target;
+ });
+ const editorStyle = useAnimatedStyle(() => {
+ const compactInsets = compactEditorInsets({
+ slotX: editorX.value,
+ slotWidth: editorWidth.value,
+ rowWidth: rowWidth.value,
+ isRTL,
+ });
+ const progress = expansion.value;
+ // Hanging from the row top lets the text ride the growing edge and ignore the stale
+ // height measured while it still wrapped in the compact slot. Layout props only:
+ // Reanimated applies transforms frames ahead of layout, which tore the text from its frame.
+ return {
+ position: "absolute",
+ overflow: "hidden",
+ // The compact slot is unknown until its first layout, so the editor would draw over the + button.
+ opacity: isExpanded || editorWidth.value > 0 ? 1 : 0,
+ height,
+ top: compactBottom * (1 - progress),
+ left: compactInsets.left + (EXPANDED_EDITOR_INSET - compactInsets.left) * progress,
+ // Snapping the far edge keeps the line from rewrapping while the near edge moves.
+ right: isExpanded ? EXPANDED_EDITOR_INSET : compactInsets.right,
+ };
+ });
+ const containerStyle = useAnimatedStyle(() => ({
+ height: compactRowHeight + (expandedRowHeight - compactRowHeight) * expansion.value,
}));
return {
isExpanded,
- containerStyle: { height: isExpanded ? height + 52 : compactRowHeight },
+ containerStyle,
+ // The expanded toolbar takes the row the text is leaving; reveal it once the text has lifted.
+ // An entering animation hides it from its first frame, which a shared-value opacity cannot.
+ toolbarControlsEntering:
+ animate && isExpanded
+ ? FadeIn.delay(COMPOSER_TRANSITION_DURATION_MS / 2)
+ .duration(COMPOSER_TRANSITION_DURATION_MS / 2)
+ .reduceMotion(ReduceMotion.System)
+ : undefined,
editorStyle,
onRowLayout: (event: { nativeEvent: { layout: { width: number } } }) => {
rowWidth.set(event.nativeEvent.layout.width);
@@ -217,12 +259,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;
@@ -419,7 +469,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);
@@ -471,6 +521,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" &&
@@ -482,7 +536,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:
@@ -571,6 +628,7 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps
offersUsageLimits: usageLimitsOffered,
onUsageLimits:
usageLimitsOffered && draftAttachments.length === 0 ? openUsageLimits : undefined,
+ onOpenModelPicker: settingsSheetPresentation.open,
modelOptions: mentionModelOptions,
modelProviders: props.serverConfig?.providers,
...(props.onFreshSession === undefined ? {} : { onFreshSession: props.onFreshSession }),
@@ -600,7 +658,12 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps
const surfacePaddingVertical = usesLargeControls ? 9 : floatingSidebarComposer ? 6 : 2;
const [compactRowWidth, setCompactRowWidth] = useState(0);
const compactAttachmentLimit = compactRowWidth >= 500 ? 3 : 1;
- const compactEditor = useCompactComposerEditor(bodyText, draftMessage);
+ // Animate only while typing; a thread switch or restored draft lands in place.
+ const compactEditor = useCompactComposerEditor(
+ bodyText,
+ draftMessage,
+ Platform.OS === "ios" && isFocused,
+ );
const showsCompactDictation = isVoiceInputPresented;
const isToolbarVisible = isVoiceInputPresented;
const hasEditingAttachments =
@@ -816,6 +879,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)}
@@ -1096,7 +1185,14 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps
compactEditor.isExpanded ? { flex: 1, justifyContent: "flex-end" } : undefined
}
>
- {modelControl}
+
+ {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 5e4e90e0b68ae..25b8894cc8040 100644
--- a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx
+++ b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx
@@ -31,13 +31,16 @@ import { queuedRunEditBlockedReason } from "@t3tools/client-runtime/queued-run-e
import {
childThreadInputsTitle,
type CodexFeedbackSubmission,
- type EnvironmentThreadStatus,
} from "@t3tools/client-runtime/state/threads";
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,
@@ -177,8 +180,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";
@@ -198,6 +199,7 @@ import {
COMPOSER_COLLAPSED_CHROME,
THREAD_COMPOSER_BOTTOM_GUTTER,
ThreadComposer,
+ type ThreadComposerProps,
} from "./ThreadComposer";
import { ComposerPopoverHost } from "./ComposerPopoverHost";
import { ThreadFeed, type ThreadFeedHistoryControls } from "./ThreadFeed";
@@ -248,11 +250,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";
@@ -270,7 +268,6 @@ export interface ThreadDetailScreenProps {
readonly respondingUserInputId: RuntimeRequestId | null;
readonly connectionStateLabel: EnvironmentConnectionPhase;
readonly connectionAwaitingApproval?: boolean;
- readonly threadSyncStatus?: EnvironmentThreadStatus;
readonly historyControls?: ThreadFeedHistoryControls;
readonly activeThreadBusy: boolean;
readonly canStopThread: boolean;
@@ -569,20 +566,6 @@ function ThreadDetailBody(
);
const composerKeyboardOffset = composerBottomInset;
const contentPresentationKind = props.contentPresentation.kind;
- const realThreadSyncLabel = (() => {
- switch (props.threadSyncStatus) {
- case "empty":
- case "cached":
- case "synchronizing":
- if (contentPresentationKind === "ready") {
- return "Syncing messages...";
- }
- return contentPresentationKind === "loading" ? "Loading messages..." : null;
- default:
- return null;
- }
- })();
- const threadSyncLabel = useDelayedStatus(selectedThreadKey, realThreadSyncLabel);
const connectionRetrying =
props.connectionStateLabel === "connecting" || props.connectionStateLabel === "reconnecting";
const retryError = connectionRetrying ? props.connectionError : null;
@@ -805,18 +788,13 @@ function ThreadDetailBody(
return null;
}
if (props.creationState?.kind === "preparing") {
- if (props.worktreeSetup) return null;
- return {
- kind: "preparing",
- label: props.creationState.preparingWorktree ? "Setting up worktree…" : "Starting…",
- };
+ // The feed shows worktree setup in place, so only a plain start needs the pill.
+ if (props.worktreeSetup || props.creationState.preparingWorktree) return null;
+ return { kind: "preparing", label: "Starting…" };
}
if (props.creationState?.kind === "failed") {
return null;
}
- if (threadSyncLabel !== null) {
- return { kind: "syncing", label: threadSyncLabel };
- }
const childInput = childThreadInputs[0];
if (childInput && contentPresentationKind === "ready") {
return {
@@ -904,6 +882,11 @@ function ThreadDetailBody(
return null;
})();
const showWorkingControl = floatingStatus !== null;
+ // A pending message holds the pill's row for its Starting/Working pill. Worktree setup reports
+ // progress in the feed instead, so holding the row there only leaves a gap that later closes.
+ const worktreeSetupInFeed =
+ props.worktreeSetup?.snapshot.phase === "running" ||
+ (props.creationState?.kind === "preparing" && props.creationState.preparingWorktree);
const showFloatingStatus =
showWorkingControl ||
queuedCount > 0 ||
@@ -911,10 +894,11 @@ function ThreadDetailBody(
devicePreviews.length > 0 ||
browserTabs.tabs.length > 0 ||
props.connectionStateLabel !== "connected" ||
- props.queuedMessages.length > 0 ||
- props.selectedThreadFeed.some(
- (entry) => "acknowledged" in entry && entry.acknowledged === true,
- );
+ (!worktreeSetupInFeed &&
+ (props.queuedMessages.length > 0 ||
+ props.selectedThreadFeed.some(
+ (entry) => "acknowledged" in entry && entry.acknowledged === true,
+ )));
const selectedThreadFeed = props.selectedThreadFeed;
// A palette message result opens the thread at that message: earlier
// history loads until the message is in the feed, which then scrolls to it.
@@ -1494,6 +1478,11 @@ function ThreadDetailBody(
pendingHandoff={props.pendingHandoff}
worktreeSetup={props.worktreeSetup}
setupWorkingStartedAt={props.setupWorkingStartedAt}
+ preparingWorktree={
+ props.creationState?.kind === "preparing" &&
+ props.creationState.preparingWorktree &&
+ !props.worktreeSetup
+ }
queuedMessages={props.queuedMessages}
dispatchingMessageId={props.dispatchingMessageId}
// A native subagent has no composer to edit a pending message in;
@@ -1525,7 +1514,7 @@ function ThreadDetailBody(
}
contentMaxWidth={contentMaxWidth}
historyControls={props.historyControls}
- contentSideInsets={nativeMetrics?.safeArea}
+ contentSideInsets={deriveContentSideInsets(nativeMetrics)}
layoutVariant={layoutVariant}
usesAutomaticContentInsets={props.usesAutomaticContentInsets}
onHeaderMaterialVisibilityChange={props.onHeaderMaterialVisibilityChange}
@@ -1702,25 +1691,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 cffa9134413e9..d3786eb4932aa 100644
--- a/apps/mobile/src/features/threads/ThreadFeed.tsx
+++ b/apps/mobile/src/features/threads/ThreadFeed.tsx
@@ -2,7 +2,11 @@ import { Button } from "../../components/ui/Button";
import * as Dialog from "../../components/ui/Dialog";
import { useOpenPullRequest } from "../../native/useOpenPullRequest";
import { useWorkspaceSettledContentWidth } from "../layout/workspace-content-width";
-import { ThreadMarkdownVideo, ThreadMediaVisibleContext } from "./ThreadMarkdownVideo";
+import {
+ ThreadMarkdownVideo,
+ ThreadMediaRetainContext,
+ ThreadMediaVisibleContext,
+} from "./ThreadMarkdownVideo";
import { useMarkdownImageSource } from "../../native/useMarkdownImageSource";
import {
enrichedContextLinkCustomization,
@@ -26,6 +30,7 @@ import { LinkRequestCard } from "./LinkRequestCard";
import { SecretRequestCard } from "./SecretRequestCard";
import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";
import {
+ WorktreePreparingHeader,
WorktreeWorkingHeader,
WorktreeSetupCard,
type WorktreeSetupCardProps,
@@ -80,6 +85,7 @@ import { resolveAssetUrl } from "@t3tools/client-runtime/state/assets";
import { formatAttachmentSize } from "@t3tools/client-runtime/state/attachments";
import {
executeAtomQuery,
+ isAtomCommandInterrupted,
settlePromise,
squashAtomCommandFailure,
} from "@t3tools/client-runtime/state/runtime";
@@ -96,7 +102,8 @@ 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 { useFocusEffect, useNavigation } from "@react-navigation/native";
+import { textDirection } from "@t3tools/shared/textDirection";
+import { useFocusEffect, useIsFocused, useNavigation } from "@react-navigation/native";
import { useNativeWorkspaceColumnsSupported } from "../../native/NativeWorkspaceColumns";
import { useDeviceType } from "../../native/native-layout-metrics";
import { isDuoDevice } from "../../lib/device-type";
@@ -112,8 +119,10 @@ import {
useSyncExternalStore,
useId,
type ComponentPropsWithRef,
+ type Dispatch,
type ReactNode,
type RefObject,
+ type SetStateAction,
} from "react";
import {
Image,
@@ -132,9 +141,15 @@ import { useResolveClassNames } from "uniwind";
import { useReduceMotionEnabled } from "../../lib/appState";
import { useFilePreviewGallery, FilePreviewGallery } from "../../components/ui/FilePreviewGallery";
import { assetImageSource } from "../../lib/assetImageSource";
+import { filePreviewSourceIdentifier } from "../../lib/filePreviewGallery";
import { composerImageGallery } from "../../lib/composerImageGallery";
import { isFileBackedComposerAttachment } from "../../lib/composerImages";
import { useLocalAttachmentPreview } from "../../lib/localAttachmentPreview";
+import {
+ rememberSentImage,
+ sentImageHandoff,
+ type SentImageHandoff,
+} from "../../lib/sentImageHandoff";
import { messageImageGallery } from "./messageImageGallery";
import { MARKDOWN_IMAGE_MAX_WIDTH, resolveMarkdownImageDisplaySize } from "./markdownImageSize";
import { FilePreviewModal, type FilePreviewSource } from "../../components/ui/FilePreviewModal";
@@ -287,7 +302,7 @@ import {
import { ZoomableImagePressable } from "./ZoomableImagePressable";
import { openSettings } from "../settings/settings-navigation";
import { useSelectWorkspaceDetail } from "../layout/workspace/useSelectWorkspaceDetail";
-import { formatMessageTimestamp } from "./messageTimestamp";
+import { useMessageTimeFormatter } from "./useMessageTimeFormatter";
const WIDE_MARKDOWN_BLOCK_OPTIONS = {
// iOS blockquotes and selectable text measure separately; definite bubble width matches UIKit's drawing width.
@@ -320,6 +335,7 @@ export interface ThreadFeedProps {
readonly toolCallVisibility?: ToolCallVisibility;
readonly worktreeSetup?: WorktreeSetupCardProps | null;
readonly setupWorkingStartedAt?: string | null;
+ readonly preparingWorktree?: boolean;
readonly queuedMessages: ReadonlyArray;
readonly dispatchingMessageId: MessageId | null;
readonly onEditPendingMessage: ((message: QueuedThreadMessage) => void) | null;
@@ -435,7 +451,14 @@ function AssistantForkButton(props: {
},
})
.then(async (result) => {
- if (result._tag !== "Success") return;
+ if (isAtomCommandInterrupted(result)) return;
+ if (result._tag !== "Success") {
+ Dialog.alert(
+ "Could not confirm fork",
+ "Reconnect and check the thread list before trying again.",
+ );
+ return;
+ }
const targetThreadReady = await waitForThreadShell(
scopeThreadRef(props.environmentId, targetThreadId),
);
@@ -480,12 +503,18 @@ function MessageImage(props: {
readonly maxWidth?: number;
readonly height?: number;
readonly accessibilityLabel: string;
+ readonly handoff?: SentImageHandoff;
readonly onPress: () => void;
- readonly onLoad?: () => void;
+ readonly onLoad?: (size: { readonly width: number; readonly height: number }) => void;
readonly onError?: () => void;
}) {
const imageStyle = useResolveClassNames(props.className);
- const [size, setSize] = useState<{ width: number; height: number } | null>(null);
+ const [loadedSize, setSize] = useState<{ width: number; height: number } | null>(null);
+ // Until it loads, assume a handed-off image is a photo larger than the bubble's caps.
+ const size =
+ loadedSize ??
+ (props.handoff ? { width: props.handoff.aspectRatio * 4096, height: 4096 } : null);
+ const contentFit = props.maxWidth === undefined ? "cover" : "contain";
const displaySize =
props.maxWidth !== undefined && size !== null
? resolveMarkdownImageDisplaySize({
@@ -516,10 +545,12 @@ function MessageImage(props: {
source={props.source}
cachePolicy="memory-disk"
style={{ width: "100%", height: "100%" }}
- contentFit={props.maxWidth === undefined ? "cover" : "contain"}
+ contentFit={contentFit}
+ placeholder={props.handoff ? { uri: props.handoff.uri } : undefined}
+ placeholderContentFit={contentFit}
onLoad={(event) => {
if (props.maxWidth !== undefined) setSize(event.source);
- props.onLoad?.();
+ props.onLoad?.(event.source);
}}
onError={props.onError}
/>
@@ -535,21 +566,34 @@ function MessageAttachmentImage(props: {
readonly className: string;
readonly maxWidth?: number;
readonly height?: number;
+ readonly handoff?: SentImageHandoff;
+ readonly onImageLoad?: (image: SentImageHandoff) => void;
readonly onPressPreview: (source: FilePreviewSource) => void;
}) {
const withGallery = useFilePreviewGallery();
- const sourceIdentifier = useId();
const resource = {
_tag: "attachment" as const,
attachmentId: props.attachmentId,
fileName: props.name,
mimeType: props.mimeType,
};
+ const sourceIdentifier = filePreviewSourceIdentifier({
+ kind: "image",
+ environmentId: props.environmentId,
+ resource,
+ });
const uri = useAssetUrl(props.environmentId, resource);
const refreshAssetUrl = useRefreshAssetUrl(props.environmentId, resource);
const retriedImage = useRef(false);
+ const { handoff } = props;
+ const source =
+ uri !== null
+ ? assetImageSource(props.environmentId, resource, uri)
+ : handoff !== undefined
+ ? { uri: handoff.uri }
+ : null;
- if (uri === null) {
+ if (source === null) {
return (
props.onPressPreview(
withGallery({
@@ -592,8 +637,10 @@ function MessageAttachmentImage(props: {
}),
)
}
- onLoad={() => {
+ onLoad={(size) => {
retriedImage.current = false;
+ if (handoff)
+ props.onImageLoad?.({ uri: handoff.uri, aspectRatio: size.width / size.height });
}}
onError={() => {
if (retriedImage.current) return;
@@ -832,7 +879,10 @@ function MessageAttachmentFile(props: {
);
}
+const handoffProps = (handoff: SentImageHandoff | undefined) => (handoff ? { handoff } : {});
+
function UserMessageMedia(props: {
+ readonly messageId: string;
readonly attachments: ReadonlyArray;
readonly pendingAttachments: QueuedThreadMessage["attachments"];
readonly environmentId: EnvironmentId;
@@ -867,6 +917,8 @@ function UserMessageMedia(props: {
name={attachment.name}
mimeType={attachment.mimeType}
{...imageProps(index)}
+ {...handoffProps(sentImageHandoff(props.messageId, index, attachment.id))}
+ onImageLoad={(loaded) => rememberSentImage(props.messageId, index, loaded)}
onPressPreview={props.onPressPreview}
/>
) : !image && attachment.uploadedAttachmentId ? (
@@ -883,6 +935,8 @@ function UserMessageMedia(props: {
rememberSentImage(props.messageId, index, image)}
onPressPreview={props.onPressPreview}
onPlaybackStart={props.onPlaybackStart}
/>
@@ -899,6 +953,7 @@ function UserMessageMedia(props: {
name={attachment.name}
mimeType={attachment.mimeType}
{...imageProps(props.pendingAttachments.length + index)}
+ {...handoffProps(sentImageHandoff(props.messageId, index))}
onPressPreview={props.onPressPreview}
/>
) : isFileAttachment(attachment) ? (
@@ -965,23 +1020,31 @@ function PendingMessageMedia(props: {
readonly className: string;
readonly maxWidth?: number;
readonly height?: number;
+ readonly handoff?: SentImageHandoff;
+ readonly onImageLoad?: (image: SentImageHandoff) => void;
readonly onPressPreview: (source: FilePreviewSource) => void;
readonly onPlaybackStart: () => void;
}) {
const withGallery = useFilePreviewGallery();
- const { attachment } = props;
+ const { attachment, handoff } = props;
const fileBacked = isFileBackedComposerAttachment(attachment);
const preview = useLocalAttachmentPreview(fileBacked ? attachment : null);
if (isImageAttachment(attachment)) {
- const uri = fileBacked ? preview.uri : (attachment.dataUrl ?? attachment.previewUri);
+ // The composer already showed this image; reuse its pixels and shape instead of a blank box.
+ const uri =
+ handoff?.uri ?? (fileBacked ? preview.uri : (attachment.dataUrl ?? attachment.previewUri));
return (
{
+ if (uri) props.onImageLoad?.({ uri, aspectRatio: size.width / size.height });
+ }}
onPress={() => {
const source = composerImageGallery([attachment])[0];
if (source) props.onPressPreview(withGallery(source));
@@ -1070,12 +1133,26 @@ function ThreadFeedScrollView(props: ComponentPropsWithRef>;
+ readonly children: ReactNode;
+}) {
+ const { rowId, setRetainedRowId } = props;
const [visible, setVisible] = useState(false);
useViewabilityAmount(
useCallback((token) => setVisible(token.sizeVisible > 0), []),
);
- return {props.children};
+ const retain = useCallback(
+ (retained: boolean) =>
+ setRetainedRowId((current) => (retained ? rowId : current === rowId ? null : current)),
+ [rowId, setRetainedRowId],
+ );
+ return (
+
+ {props.children}
+
+ );
}
/** The reply a link sits in; a file it cites may be where the agent worked before writing it. */
@@ -1089,7 +1166,11 @@ interface MarkdownLinkHandlers {
actionId: string,
reply?: MarkdownLinkReply,
) => void;
- readonly onImagePress?: (href: string) => void;
+ /** `withGallery` pages the image through its message's images; the feed's viewer sits outside that scope. */
+ readonly onImagePress?: (
+ href: string,
+ withGallery?: (source: FilePreviewSource) => FilePreviewSource,
+ ) => void;
readonly resolveImageSource?: MarkdownImageSourceResolver;
readonly fileEmbedLabel?: (href: string, standalone: boolean) => string | null;
readonly linkCustomization?: (href: string) => MarkdownLinkCustomization | undefined;
@@ -1124,8 +1205,12 @@ function ArtifactTemplateCard(props: {
readonly template: CodexArtifactTemplate;
readonly onUse?: ((template: CodexArtifactTemplate) => void) | undefined;
}) {
+ const direction = textDirection(props.template.displayName);
return (
-
+
onImagePress(href, withGallery) } : {}),
onLinkPress: (href) => props.linkHandlers.onLinkPress(href, props.reply),
onFileContextMenuAction: (href, actionId) =>
props.linkHandlers.onFileContextMenuAction(href, actionId, props.reply),
@@ -1662,6 +1750,7 @@ function renderFeedEntry(
| "threadId"
| "workspaceRoot"
> & {
+ readonly formatMessageTime: (input: string) => string;
readonly copiedRowId: string | null;
readonly expandedWorkRows: Record;
readonly workRowSizing: ReturnType;
@@ -1907,7 +1996,7 @@ function renderFeedEntry(
const presentation = resolveUserMessagePresentation(message);
const renderedText = renderAssistantCitationsAsText(presentation.text);
const styles = isUser ? markdownStyles.user : markdownStyles.assistant;
- const timestampLabel = formatMessageTimestamp(isUser ? message.createdAt : message.updatedAt);
+ const timestampLabel = props.formatMessageTime(isUser ? message.createdAt : message.updatedAt);
const attachments = message.attachments ?? [];
const hasReviewCommentContext = presentation.text.includes("
(null);
+ const focused = useIsFocused();
+ if (!focused && retainedMediaRowId !== null) setRetainedMediaRowId(null);
const onOpenTurnDiff = useCallback(
(checkpoint: ThreadCheckpointSummary) => {
setReviewSelectedSectionId(
@@ -3000,7 +3095,12 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
};
return lookup().catch(() => relativePath);
};
- const onMarkdownLinkPress = (href: string, imageEmbed = false, reply?: MarkdownLinkReply) => {
+ const onMarkdownLinkPress = (
+ href: string,
+ imageEmbed = false,
+ reply?: MarkdownLinkReply,
+ withGallery?: (source: FilePreviewSource) => FilePreviewSource,
+ ) => {
markdownLinkRequest.current?.abort();
const request = new AbortController();
markdownLinkRequest.current = request;
@@ -3033,7 +3133,9 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
if (request.signal.aborted) return;
openPreview(
scope,
- media.kind === "video" ? { video: media.source } : { file: media.source },
+ media.kind === "video"
+ ? { video: media.source }
+ : { file: withGallery ? withGallery(media.source) : media.source },
);
};
const resource = "resource" in media.source ? media.source.resource : null;
@@ -3108,7 +3210,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
),
onLinkPress: (href, reply) => onMarkdownLinkPress(href, false, reply),
linkCustomization: enrichedThreadLinkCustomization,
- onImagePress: (href) => onMarkdownLinkPress(href, true),
+ onImagePress: (href, withGallery) => onMarkdownLinkPress(href, true, undefined, withGallery),
resolveImageSource,
fileContextMenu: (href) => {
const skill = enrichedSkillReference(href, props.skills);
@@ -3336,8 +3438,10 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
const listAppearanceData = {
disclosureLayout,
reduceMotion,
+ formatMessageTime,
worktreeSetup: props.worktreeSetup,
setupWorkingStartedAt: props.setupWorkingStartedAt,
+ preparingWorktree: props.preparingWorktree,
dispatchingMessageId: props.dispatchingMessageId,
unsettledTurnId,
copiedRowId,
@@ -3361,9 +3465,15 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
headerMaterialVisibleRef.current = visible;
onHeaderMaterialVisibilityChange?.(visible);
};
+ const feedThreadKey = scopedThreadKey(props.environmentId, props.threadId);
+ const [loadedListKey, setLoadedListKey] = useState(null);
+ // LegendList hides rows until it has scrolled to the end, but not its header.
+ const settling = props.feed.length > 0 && loadedListKey !== feedThreadKey;
const handleMetricsChange = () => {
const state = listRef.current?.getState();
- if (state) onIsAtEndChange?.(state.isAtEnd);
+ // Offset 0 before the first positioning, and the gaps while rows measure in, are not the
+ // user leaving the end; only a scroll away stops end following.
+ if (state) onIsAtEndChange?.(settling || state.isAtEnd || state.isFollowingEnd);
};
const handleScroll = (event: NativeSyntheticEvent) => {
reportHeaderMaterialVisibility(
@@ -3378,6 +3488,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
handleMetricsChange();
const stops = [
state.listen("isAtEnd", handleMetricsChange),
+ state.listen("isFollowingEnd", handleMetricsChange),
state.listen("totalSize", handleMetricsChange),
state.listen("footerSize", handleMetricsChange),
state.listen("headerSize", handleMetricsChange),
@@ -3386,7 +3497,6 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
for (const stop of stops) stop();
};
}, [listRef, handleMetricsChange]);
- const feedThreadKey = scopedThreadKey(props.environmentId, props.threadId);
const [workGroupScrollPositions] = useState(
() => new Map(),
);
@@ -3394,7 +3504,6 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
// Opening at a message: once the filled list has loaded, the render that sees
// the jump unfolds a run hiding the message and stops following the end, so
// the committed list holds the target row with end maintenance off.
- const [loadedListKey, setLoadedListKey] = useState(null);
const { jumpToMessageId } = props;
const jumpReady = !!jumpToMessageId && loadedListKey === feedThreadKey;
if (jumpReady && revealedMessageId !== jumpToMessageId) {
@@ -3422,7 +3531,9 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
const groupedFeed = groupFeed(presentedFeed, {
workflowOpeningMessageId: workflowOpening?.messageId,
setupAnchorIndex:
- props.worktreeSetup || props.setupWorkingStartedAt ? setupAnchorIndex : undefined,
+ props.worktreeSetup || props.setupWorkingStartedAt || props.preparingWorktree
+ ? setupAnchorIndex
+ : undefined,
});
const { contentInsetEndAdjustment } = props;
const attachList = (list: LegendListRef | null) => {
@@ -3724,7 +3835,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
threadId={props.threadId}
workspaceRoot={props.workspaceRoot}
>
-
+
{info.item.type === "message" &&
info.item.message.projectedItem?.item.type === "user_message" &&
info.item.message.projectedItem.item.freshContext ? (
@@ -3746,6 +3857,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
) : null}
{renderFeedEntry(info, {
userMessageGrouping: info.item.userMessageGrouping,
+ formatMessageTime,
environmentId: props.environmentId,
dispatchingMessageId: props.dispatchingMessageId,
onEditPendingMessage: props.onEditPendingMessage,
@@ -3791,6 +3903,8 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
) : props.setupWorkingStartedAt && info.index === setupAnchorIndex ? (
+ ) : props.preparingWorktree && info.index === setupAnchorIndex ? (
+
) : null}
@@ -3799,13 +3913,15 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
if (props.contentPresentation.kind === "unavailable" && props.queuedMessages.length === 0) {
return (
-
+
+
+
);
}
@@ -3858,6 +3974,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
}}
getFixedItemSize={getFixedItemSize}
drawDistance={500}
+ {...(retainedMediaRowId ? { alwaysRender: { keys: [retainedMediaRowId] } } : {})}
keyboardShouldPersistTaps="always"
keyboardDismissMode="none"
// Android scrolls a tapped selectable message into view when it takes focus, which reads
@@ -3881,15 +3998,17 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
onScroll={handleScroll}
scrollEventThrottle={16}
ListHeaderComponent={
- <>
+
{usesNativeAutomaticInsets ? null : }
{setupAnchorIndex < 0 && props.worktreeSetup ? (
+ ) : setupAnchorIndex < 0 && props.preparingWorktree ? (
+
) : null}
{props.historyControls ? (
) : null}
- >
+
}
ListFooterComponent={
props.pendingHandoff ? (
diff --git a/apps/mobile/src/features/threads/ThreadInlineFilePreview.tsx b/apps/mobile/src/features/threads/ThreadInlineFilePreview.tsx
index e44a422212712..b73f6f458edc5 100644
--- a/apps/mobile/src/features/threads/ThreadInlineFilePreview.tsx
+++ b/apps/mobile/src/features/threads/ThreadInlineFilePreview.tsx
@@ -10,7 +10,7 @@ import { AppText as Text } from "../../components/ui/AppText";
import { SymbolView } from "../../components/ui/AppSymbol";
import { useFullscreenVideoOpen, useMediaAudioSessionHold } from "../../lib/videoAudioSession";
import { useRefreshAssetUrl } from "../../state/assets";
-import { ThreadMediaVisibleContext } from "./ThreadMarkdownVideo";
+import { ThreadMediaRetainContext, ThreadMediaVisibleContext } from "./ThreadMarkdownVideo";
import {
acquireAudioSession,
activateAudioSession,
@@ -59,7 +59,13 @@ function timestamp(seconds: number) {
return `${Math.floor(value / 60)}:${String(value % 60).padStart(2, "0")}`;
}
-function InlineAudio(props: PreviewProps & { readonly resolveUri: () => Promise }) {
+function InlineAudio(
+ props: PreviewProps & {
+ readonly resolveUri: () => Promise;
+ readonly onPlaybackActivityChange?: (active: boolean) => void;
+ },
+) {
+ const { onPlaybackActivityChange } = props;
// An empty source keeps native buffering off until the user explicitly plays.
const player = usePlaybackAudioPlayer(null);
const status = useAudioPlayerStatus(player);
@@ -90,8 +96,16 @@ function InlineAudio(props: PreviewProps & { readonly resolveUri: () => Promise<
// oxlint-disable-next-line react/set-state-in-effect -- Native completion and fullscreen takeover invalidate the pending playback request.
requestPlayback(false);
}
+ if (status.didJustFinish || status.error) onPlaybackActivityChange?.(false);
if (fullscreenVideoOpen) pauseAudioPlayer(player);
- }, [fullscreenVideoOpen, status.didJustFinish, status.error, player, requestPlayback]);
+ }, [
+ fullscreenVideoOpen,
+ status.didJustFinish,
+ status.error,
+ player,
+ requestPlayback,
+ onPlaybackActivityChange,
+ ]);
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes to AppState to pause audio in the background and releases the audio session on cleanup
useEffect(() => {
active.current = true;
@@ -131,6 +145,7 @@ function InlineAudio(props: PreviewProps & { readonly resolveUri: () => Promise<
);
if (!isAudioSessionOwner(token)) return;
props.onPlaybackStart?.();
+ onPlaybackActivityChange?.(true);
audioToken.current = token;
requestPlayback(true);
const generation = ++requestGeneration.current;
@@ -149,6 +164,7 @@ function InlineAudio(props: PreviewProps & { readonly resolveUri: () => Promise<
if (!isCurrentRequest() || AppState.currentState !== "active") return;
if (!uri) {
requestPlayback(false);
+ onPlaybackActivityChange?.(false);
setError(true);
return;
}
@@ -163,6 +179,7 @@ function InlineAudio(props: PreviewProps & { readonly resolveUri: () => Promise<
.catch(() => {
if (isCurrentRequest()) {
requestPlayback(false);
+ onPlaybackActivityChange?.(false);
setError(true);
}
})
@@ -221,7 +238,9 @@ function InlineAudio(props: PreviewProps & { readonly resolveUri: () => Promise<
);
}
-function VisibleFilePreview(props: PreviewProps) {
+function VisibleFilePreview(
+ props: PreviewProps & { readonly onPlaybackActivityChange?: (active: boolean) => void },
+) {
// Each mounted preview owns its source; feed streaming must not restart a fetch or player.
const [source] = useState(props.source);
const refresh = useRefreshAssetUrl(
@@ -235,13 +254,27 @@ function VisibleFilePreview(props: PreviewProps) {
export function ThreadInlineFilePreview(props: PreviewProps) {
const visible = useContext(ThreadMediaVisibleContext);
const focused = useIsFocused();
+ const retainRow = useContext(ThreadMediaRetainContext);
+ // Unmounting disposes the native player, so a started player stays mounted off-screen
+ // (and its feed row out of recycling) until it finishes or fails. Leaving the screen
+ // disposes it, so the latch resets too; the feed drops its row pin on blur itself.
+ const [playbackActive, setPlaybackActive] = useState(false);
+ if (!focused && playbackActive) setPlaybackActive(false);
+ const onPlaybackActivityChange = (active: boolean) => {
+ setPlaybackActive(active);
+ retainRow(active);
+ };
return (
- {visible && focused ? (
-
+ {focused && (visible || playbackActive) ? (
+
) : (
<>
diff --git a/apps/mobile/src/features/threads/ThreadMarkdownImage.tsx b/apps/mobile/src/features/threads/ThreadMarkdownImage.tsx
index 90eb97f4e3b8a..7f4d51f19f945 100644
--- a/apps/mobile/src/features/threads/ThreadMarkdownImage.tsx
+++ b/apps/mobile/src/features/threads/ThreadMarkdownImage.tsx
@@ -22,6 +22,7 @@ import { useAssetUrlState } from "../../state/assets";
import { WorkspaceMutationIdContext } from "./workspaceMutationIdContext";
import { ZoomableImagePressable } from "./ZoomableImagePressable";
import { assetImageCacheKey } from "../../lib/assetImageSource";
+import { filePreviewSourceIdentifier } from "../../lib/filePreviewGallery";
import {
MARKDOWN_IMAGE_MAX_WIDTH,
type MarkdownImageDisplaySize,
@@ -91,6 +92,7 @@ const noSvgDocumentAtom = Atom.make(AsyncResult.initial void;
}) {
const withGallery = useFilePreviewGallery();
- const sourceIdentifier = useId();
+ const localSourceIdentifier = useId();
+ const sourceIdentifier = props.sourceIdentifier ?? localSourceIdentifier;
const mediaActions = useMediaActions(props.actionsSource);
const contextWidth = useContext(MarkdownImageAvailableWidthContext);
const [measuredWidth, setMeasuredWidth] = useState(0);
@@ -307,6 +310,11 @@ export function ThreadMarkdownImage(props: {
: undefined
}
sourceKey={sourceKey}
+ sourceIdentifier={filePreviewSourceIdentifier({
+ kind: "image",
+ environmentId: props.environmentId,
+ resource: props.resource,
+ })}
unavailable={assetUrl._tag === "Failure"}
unavailableDetail={
assetUrl._tag === "Failure" && assetUrl.reason === "missing-file-access"
diff --git a/apps/mobile/src/features/threads/ThreadMarkdownVideo.tsx b/apps/mobile/src/features/threads/ThreadMarkdownVideo.tsx
index 5cf1c9b353297..4d6d566f051ac 100644
--- a/apps/mobile/src/features/threads/ThreadMarkdownVideo.tsx
+++ b/apps/mobile/src/features/threads/ThreadMarkdownVideo.tsx
@@ -9,6 +9,8 @@ import {
} from "../../lib/videoPreviewSource";
export const ThreadMediaVisibleContext = createContext(false);
+/** Asks the feed to keep this row out of list recycling while its media holds playback state. */
+export const ThreadMediaRetainContext = createContext<(retained: boolean) => void>(() => {});
export function ThreadMarkdownVideo(props: {
readonly source: MediaVideoPreviewSource;
diff --git a/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx b/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx
index 6aa576f984fce..6de4c54d6d430 100644
--- a/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx
+++ b/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx
@@ -12,7 +12,7 @@ import type {
} from "@t3tools/client-runtime/state/shell";
import { threadSearchMatchKey } from "@t3tools/client-runtime/state/thread-search";
import { AnimatedLegendList } from "@legendapp/list/reanimated";
-import { THREAD_SIDEBAR_ROW_LAYOUT } from "./threadListAnimations";
+import { THREAD_LIST_ROW_LAYOUT } from "./threadListAnimations";
import { useAtomValue } from "@effect/atom-react";
import { useMemo, useRef, useState } from "react";
import { Platform, StyleSheet, View } from "react-native";
@@ -40,11 +40,15 @@ import { useQueuedThreadKeys } from "../../state/use-thread-outbox";
import { useWorkspaceState } from "../../state/workspace";
import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";
import { useThreadListV2 } from "./useThreadListV2";
+import { useSidebarRowThreadKey } from "./useSidebarRowThreadKey";
import { useThreadJumpShortcuts } from "../keyboard/threadKeyboardShortcuts";
import { requestThreadMessageJump } from "./threadMessageJump";
import { useThreadListSearchMatches } from "./useThreadListSearchMatches";
import { useHomeListOptions } from "../home/home-list-options";
-import { buildHomeListFilterMenuItems } from "../home/home-list-filter-menu";
+import {
+ buildHomeListFilterMenuItems,
+ homeListFilterEnvironments,
+} from "../home/home-list-filter-menu";
import {
buildHomeProjectScopes,
resolveHomeProjectFilterScope,
@@ -124,6 +128,7 @@ function ThreadNavigationSidebarPane(props: ThreadNavigationSidebarProps) {
const { fabClearance, fabSize } = useAndroidControlSizing();
const projects = useProjects();
const threads = useAtomValue(steadyNavigationThreadShellsAtom);
+ const selectedThreadKey = useSidebarRowThreadKey(props.selectedThreadKey);
const { environments: workspaceEnvironments, state: catalogState } = useWorkspaceState();
const { savedConnectionsById } = useSavedRemoteConnections();
const openSwipeableRef = useRef(null);
@@ -150,12 +155,7 @@ function ThreadNavigationSidebarPane(props: ThreadNavigationSidebarProps) {
const { confirmDeletePendingTask } = usePendingTaskListActions((params) =>
selectDetail({ name: "Thread", params }),
);
- const environments = Object.values(savedConnectionsById)
- .map((connection) => ({
- environmentId: connection.environmentId,
- label: connection.environmentLabel,
- }))
- .sort((left, right) => left.label.localeCompare(right.label));
+ const environments = homeListFilterEnvironments(workspaceEnvironments);
const availableEnvironmentIds = new Set(
environments.map((environment) => environment.environmentId),
);
@@ -290,7 +290,7 @@ function ThreadNavigationSidebarPane(props: ThreadNavigationSidebarProps) {
workingShelfExpanded,
snoozedShelfExpanded,
settledShelfExpanded,
- selectedThreadKey: props.selectedThreadKey ?? null,
+ selectedThreadKey,
});
const listItems: readonly SidebarListItem[] =
settledShelfExpanded && threadListV2Layout.hiddenSettledCount > 0
@@ -353,7 +353,7 @@ function ThreadNavigationSidebarPane(props: ThreadNavigationSidebarProps) {
// Recycle equality needs project/search data for titles and favicons; keep the minute clock on items to limit updates.
const listExtraData = {
activeNewTask,
- selectedThreadKey: props.selectedThreadKey ?? "",
+ selectedThreadKey: selectedThreadKey ?? "",
projectByKey,
projectTitleByProjectKey,
savedConnectionsById,
@@ -387,10 +387,9 @@ function ThreadNavigationSidebarPane(props: ThreadNavigationSidebarProps) {
scopedThreadKey(
item.pendingTask.environmentId,
item.pendingTask.message.threadId,
- ) === props.selectedThreadKey)
+ ) === selectedThreadKey)
}
project={projectByKey.get(pendingScopeKey) ?? null}
- projectTitle={projectTitleByProjectKey.get(pendingScopeKey)}
environmentLabel={
Object.keys(savedConnectionsById).length > 1
? (savedConnectionsById[item.pendingTask.environmentId]?.environmentLabel ?? null)
@@ -449,7 +448,7 @@ function ThreadNavigationSidebarPane(props: ThreadNavigationSidebarProps) {
pane="sidebar"
selected={
!activeNewTask &&
- scopedThreadKey(thread.environmentId, thread.id) === props.selectedThreadKey
+ scopedThreadKey(thread.environmentId, thread.id) === selectedThreadKey
}
fullSwipeWidth={props.width - 20}
onSelectThread={handleSelectThread}
@@ -606,7 +605,7 @@ function ThreadNavigationSidebarPane(props: ThreadNavigationSidebarProps) {
{/* oxlint-disable-next-line t3code/require-registered-list-scroll -- The Android sidebar has no native header to register with. */}
) {
});
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 8a5651bbe4e84..7e06d38c67993 100644
--- a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx
+++ b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx
@@ -54,6 +54,7 @@ import { vcsEnvironment } from "../../state/vcs";
import { EmptyState } from "../../components/ui/EmptyState";
import { LoadingScreen } from "../../components/LoadingScreen";
import { scopedThreadKey } from "../../lib/scopedEntities";
+import { useDelayedStatus } from "../../lib/useDelayedStatus";
import { scopeThreadRef } from "@t3tools/client-runtime/environment";
import { useThreadShell } from "../../state/entities";
import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass";
@@ -98,7 +99,10 @@ import { resolveLatestMergeBackRun } from "@t3tools/client-runtime/state/thread-
import { threadEnvironment } from "../../state/threads";
import { EMPTY_ENVIRONMENT_THREAD_STATE } from "@t3tools/client-runtime/state/threads";
import { useProjects } from "../../state/entities";
-import { projectThreadContentPresentation } from "./threadContentPresentation";
+import {
+ projectThreadContentPresentation,
+ threadSyncStatusLabel,
+} from "./threadContentPresentation";
import {
Inspector,
useAdaptiveWorkspaceLayout,
@@ -293,8 +297,11 @@ function LiveThreadRouteController(props: ThreadRouteScreenProps) {
}
if (selectedThread !== null && selectedThreadKey === routeThreadKey) {
- return withInspectorHeader(
- ,
+ // ThreadRouteContent draws its own inspector header so it can show the sync status.
+ return (
+
+
+
);
}
@@ -862,7 +869,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",
@@ -950,14 +957,6 @@ function ThreadRouteContent(
serverOwned: false,
};
})();
- if (!environmentId || !threadId) {
- return ;
- }
-
- if (!selectedThread) {
- return ;
- }
-
// Queued creation displays its prompt before server creation; temporary not-found is expected.
const contentPresentation =
creationState !== null
@@ -968,6 +967,30 @@ function ThreadRouteContent(
detailDeleted: selectedThreadDetailState.status === "deleted",
connectionState: routeConnectionState,
});
+ // Shown in the header subtitle so the composer's status slot doesn't jump while history syncs.
+ const threadSyncLabel = useDelayedStatus(
+ selectedThread === null ? "" : scopedThreadKey(selectedThread.environmentId, selectedThread.id),
+ // A thread this client is creating has nothing older to sync.
+ creationState === null
+ ? threadSyncStatusLabel(selectedThreadDetailState.status, contentPresentation.kind)
+ : null,
+ );
+ const inspectorHeader = props.inspectorPresentation ? (
+
+ ) : null;
+ if (!environmentId || !threadId || !selectedThread) {
+ return (
+ <>
+ {inspectorHeader}
+
+ >
+ );
+ }
+
const serverConfig = routeEnvironmentRuntime?.serverConfig ?? null;
const renderThreadRouteBody = () => (
<>
@@ -983,7 +1006,7 @@ function ThreadRouteContent(
props.inspectorPresentation ? null : (
+ {inspectorHeader}
{!props.inspectorPresentation && inspectorContent ? (
setComposerDraftText(draftKey, text)}
reportedModelSelection={reportedModelSelection}
- onSelectModel={(option) => updateModelSelection(withRememberedModelOptions(option.selection))}
+ onSelectModel={(option) =>
+ updateModelSelection(
+ withStoredThreadModelOptions(
+ withRememberedModelOptions(option.selection),
+ selectedThread.modelSelection,
+ ),
+ )
+ }
restoreSelection={withRememberedModelOptions}
optionDescriptors={resolveProviderOptionDescriptors({
capabilities: currentModelOption?.capabilities,
diff --git a/apps/mobile/src/features/threads/checkout-new-task-branch.test.ts b/apps/mobile/src/features/threads/checkout-new-task-branch.test.ts
index bee63a9775a05..328f56bcf0066 100644
--- a/apps/mobile/src/features/threads/checkout-new-task-branch.test.ts
+++ b/apps/mobile/src/features/threads/checkout-new-task-branch.test.ts
@@ -135,12 +135,12 @@ async function addRemote(remoteName: string, sourceRef = branch.name) {
}
describe("new-task branch checkout", () => {
- it("switches to a free branch and clears its historical worktree path", async () => {
+ it("switches to a free branch despite stale current and worktree metadata", async () => {
const previousWorktree = NodePath.join(directory, "previous-worktree");
await git("worktree", "add", previousWorktree, branch.name);
await exec("git", ["-C", previousWorktree, "checkout", "-b", "other-branch"]);
const result = await checkoutNewTaskBranch({
- branch: { ...branch, worktreePath: previousWorktree },
+ branch: { ...branch, current: true, worktreePath: previousWorktree },
project: { environmentId, workspaceRoot: cwd },
workspaceMode: "local",
readRefs,
diff --git a/apps/mobile/src/features/threads/checkout-new-task-branch.ts b/apps/mobile/src/features/threads/checkout-new-task-branch.ts
index fb7920dcdd5f6..a4f3a306b2eb0 100644
--- a/apps/mobile/src/features/threads/checkout-new-task-branch.ts
+++ b/apps/mobile/src/features/threads/checkout-new-task-branch.ts
@@ -34,13 +34,10 @@ export async function checkoutNewTaskBranch(input: {
Cause.fail(new Error("The selected project is unavailable. Reconnect and try again.")),
);
}
- if (input.workspaceMode === "worktree" || input.branch.current) {
- return AsyncResult.success(
- input.branch.current ? { ...input.branch, worktreePath: null } : input.branch,
- );
- }
+ if (input.workspaceMode === "worktree") return AsyncResult.success(input.branch);
- // Remote refs omit local worktrees, and historical thread metadata can be stale.
+ // The picked ref's current flag, remote refs' missing worktrees and historical
+ // thread metadata can all be stale, so Git is asked again before choosing.
const localName = localBranchName(input.branch);
let cursor: number | undefined;
for (;;) {
diff --git a/apps/mobile/src/features/threads/floating-working-control.tsx b/apps/mobile/src/features/threads/floating-working-control.tsx
index 55028a58b7df2..0f83743f99d31 100644
--- a/apps/mobile/src/features/threads/floating-working-control.tsx
+++ b/apps/mobile/src/features/threads/floating-working-control.tsx
@@ -427,21 +427,6 @@ function FloatingStatusLabel(props: {
);
}
- if (props.status.kind === "syncing") {
- return (
-
-
-
- {props.status.label}
-
-
- );
- }
if (props.status.kind === "compacting") {
return ;
}
diff --git a/apps/mobile/src/features/threads/floating-working-status.ts b/apps/mobile/src/features/threads/floating-working-status.ts
index 6beb9cb6cb01a..941a875c9500c 100644
--- a/apps/mobile/src/features/threads/floating-working-status.ts
+++ b/apps/mobile/src/features/threads/floating-working-status.ts
@@ -10,7 +10,6 @@ export interface FloatingStatusAction {
export type FloatingWorkingStatus =
| { readonly kind: "working"; readonly environmentId: EnvironmentId; readonly startedAt: string }
- | { readonly kind: "syncing"; readonly label: string }
| { readonly kind: "compacting" }
| {
readonly kind: "child-input";
diff --git a/apps/mobile/src/features/threads/messageTimestamp.test.ts b/apps/mobile/src/features/threads/messageTimestamp.test.ts
index 94f6010acd4a1..fa1ab4be779b3 100644
--- a/apps/mobile/src/features/threads/messageTimestamp.test.ts
+++ b/apps/mobile/src/features/threads/messageTimestamp.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vite-plus/test";
-import { formatMessageTimestamp } from "./messageTimestamp";
+import { createMessageTimeFormatter, formatMessageTimestamp } from "./messageTimestamp";
describe("formatMessageTimestamp", () => {
const now = new Date(2026, 10, 8, 20, 0).getTime();
@@ -20,3 +20,15 @@ describe("formatMessageTimestamp", () => {
);
});
});
+
+describe("createMessageTimeFormatter", () => {
+ const now = new Date(2026, 0, 1, 20, 0).getTime();
+
+ it("follows the system clock preference over the locale's hour cycle", () => {
+ const format24 = createMessageTimeFormatter(true, "en-US");
+ expect(format24(new Date(2026, 0, 1, 15, 7).toISOString(), now)).toBe("15:07");
+ expect(format24(new Date(2026, 0, 1, 0, 7).toISOString(), now)).toBe("00:07");
+ const format12 = createMessageTimeFormatter(false, "en-GB");
+ expect(format12(new Date(2026, 0, 1, 15, 7).toISOString(), now)).toMatch(/^3:07\spm$/i);
+ });
+});
diff --git a/apps/mobile/src/features/threads/messageTimestamp.ts b/apps/mobile/src/features/threads/messageTimestamp.ts
index 5624b71c0c917..cfae85e092666 100644
--- a/apps/mobile/src/features/threads/messageTimestamp.ts
+++ b/apps/mobile/src/features/threads/messageTimestamp.ts
@@ -7,13 +7,28 @@ const DATE_WITH_YEAR_FORMATTER = new Intl.DateTimeFormat(undefined, {
});
/** Time only for today's messages; older ones lead with the day and month. */
-export function formatMessageTimestamp(input: string, nowMs: number = Date.now()): string {
+export function formatMessageTimestamp(
+ input: string,
+ nowMs: number = Date.now(),
+ timeFormatter: Intl.DateTimeFormat = TIME_FORMATTER,
+): string {
const timestamp = Date.parse(input);
if (Number.isNaN(timestamp)) return "";
const date = new Date(timestamp);
const now = new Date(nowMs);
- const time = TIME_FORMATTER.format(date);
+ const time = timeFormatter.format(date);
if (date.toDateString() === now.toDateString()) return time;
const sameYear = date.getFullYear() === now.getFullYear();
return `${(sameYear ? DATE_FORMATTER : DATE_WITH_YEAR_FORMATTER).format(date)} ${time}`;
}
+
+/** `is24Hour` overrides the locale's hour cycle with the system clock preference when known. */
+export function createMessageTimeFormatter(is24Hour: boolean | undefined, locale?: string) {
+ const timeFormatter = new Intl.DateTimeFormat(locale, {
+ hour: "numeric",
+ minute: "2-digit",
+ ...(is24Hour === undefined ? {} : { hourCycle: is24Hour ? "h23" : "h12" }),
+ });
+ return (input: string, nowMs?: number): string =>
+ formatMessageTimestamp(input, nowMs, timeFormatter);
+}
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-inspector-preview.tsx b/apps/mobile/src/features/threads/thread-inspector-preview.tsx
index d41d1f0c7e9b1..c2d3a96c34ec7 100644
--- a/apps/mobile/src/features/threads/thread-inspector-preview.tsx
+++ b/apps/mobile/src/features/threads/thread-inspector-preview.tsx
@@ -22,12 +22,13 @@ export type ThreadInspectorPresentation =
| { readonly onClose: () => void };
export function ThreadInspectorHeader(
- props: ThreadInspectorPresentation & { readonly title: string },
+ props: ThreadInspectorPresentation & { readonly title: string; readonly subtitle?: string },
) {
if ("onMaximize" in props) {
return (
+
);
}
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 f6d7a80124686..c7943318227b1 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);
@@ -470,7 +470,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}
/>
@@ -603,6 +603,7 @@ export const ThreadListV2PendingRow = memo(function ThreadListV2PendingRow(props
enableTrackpadSwipe
fullSwipeAction="primary"
fullSwipeWidth={props.fullSwipeWidth ?? windowWidth - 32}
+ listAnimatesLayout
onDelete={handleDelete}
onSwipeableClose={props.onSwipeableClose}
onSwipeableWillOpen={props.onSwipeableWillOpen}
@@ -775,7 +776,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;
@@ -785,10 +787,23 @@ 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 markThreadUnread = useAtomCommand(threadEnvironment.markUnread, { reportFailure: false });
const handleAcknowledgeWoke = useCallback(() => {
if (props.wokeAt === null) return;
void visitThread({
@@ -935,6 +950,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
supported: props.titleRegenerationSupported,
isRegenerating: isRegeneratingTitle,
}),
+ { id: "mark-unread", title: "Mark unread", image: "envelope.badge" },
...(canTurnIntoProject
? [
{
@@ -1049,6 +1065,12 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
if (nativeEvent.event === "rename") handleRename();
if (nativeEvent.event === "regenerate-title") handleRegenerateTitle();
if (nativeEvent.event === "turn-into-project") void turnThreadIntoProject(thread);
+ if (nativeEvent.event === "mark-unread") {
+ void markThreadUnread({
+ environmentId: thread.environmentId,
+ input: { threadId: thread.id },
+ });
+ }
if (nativeEvent.event === "copy-thread") {
const target = threadChipCopyTarget(
{ environmentId: thread.environmentId, threadId: thread.id },
@@ -1097,6 +1119,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
handleUnpin,
handleUnsettle,
handleUnsnooze,
+ markThreadUnread,
setCustomSnoozeOpen,
snoozePresets,
props.snoozePresets,
@@ -1301,7 +1324,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
) : null}
- {(status === "failed" || status === "limited") && thread.runtime?.lastError ? (
+ {(rawStatus === "failed" || rawStatus === "limited") && thread.runtime?.lastError ? (
{(close) => (
-
+
+
+ )}
);
}
diff --git a/apps/mobile/src/lib/appearancePreferences.test.ts b/apps/mobile/src/lib/appearancePreferences.test.ts
index 1bfedc7529c7c..5b1e9c33a90e1 100644
--- a/apps/mobile/src/lib/appearancePreferences.test.ts
+++ b/apps/mobile/src/lib/appearancePreferences.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vite-plus/test";
-import { resolveAppearancePreferences } from "./appearancePreferences";
+import { resolveAppearancePreferences, resolveComposerTextRole } from "./appearancePreferences";
describe("appearancePreferences", () => {
it("migrates the legacy markdownFontSize key to baseFontSize", () => {
@@ -9,4 +9,14 @@ describe("appearancePreferences", () => {
resolveAppearancePreferences({ baseFontSize: 16, markdownFontSize: 18 }).baseFontSize,
).toBe(16);
});
+
+ it("scales the iOS composer text with the system text size", () => {
+ const body = { fontSize: 16, lineHeight: 23 };
+ expect(resolveComposerTextRole(body, 1, "ios")).toEqual(body);
+ expect(resolveComposerTextRole(body, 2.643, "ios")).toEqual({
+ fontSize: 16 * 2.643,
+ lineHeight: 23 * 2.643,
+ });
+ expect(resolveComposerTextRole(body, 2.643, "android")).toEqual(body);
+ });
});
diff --git a/apps/mobile/src/lib/appearancePreferences.ts b/apps/mobile/src/lib/appearancePreferences.ts
index 9b0be82b2c03f..6a7485e07c722 100644
--- a/apps/mobile/src/lib/appearancePreferences.ts
+++ b/apps/mobile/src/lib/appearancePreferences.ts
@@ -205,6 +205,17 @@ export function resolveScaledTextRole(role: keyof typeof MOBILE_TYPOGRAPHY, base
};
}
+// React Native text applies the system text size itself, but the iOS composer sets a fixed
+// UIFont, so it needs pre-scaled metrics. Android's editor already sizes text in sp.
+export function resolveComposerTextRole(
+ role: { readonly fontSize: number; readonly lineHeight: number },
+ fontScale: number,
+ os: string,
+) {
+ if (os !== "ios") return role;
+ return { fontSize: role.fontSize * fontScale, lineHeight: role.lineHeight * fontScale };
+}
+
export function resolveNativeMarkdownTypography(baseFontSize: number): NativeMarkdownTypography {
const fontSizes = resolveMarkdownFontSizes(baseFontSize);
return {
diff --git a/apps/mobile/src/lib/composerImages.test.ts b/apps/mobile/src/lib/composerImages.test.ts
index c723293c85270..b5b10ac02c7bb 100644
--- a/apps/mobile/src/lib/composerImages.test.ts
+++ b/apps/mobile/src/lib/composerImages.test.ts
@@ -199,10 +199,13 @@ describe("native pasted image cleanup", () => {
it("converts owned files to data-backed previews and deletes the source", async () => {
const uri =
"file:///private/var/mobile/Containers/Data/Application/app/tmp/t3-composer-paste/id.png";
+ const gif =
+ "file:///private/var/mobile/Containers/Data/Application/app/tmp/t3-composer-paste/anim.gif";
files.set(uri, { base64: "aGVsbG8=", deleted: false });
+ files.set(gif, { base64: "R0lGODlh", deleted: false });
const { attachments } = await convertPastedImagesToAttachments({
- uris: [uri],
+ uris: [uri, gif],
existingCount: 0,
});
@@ -211,8 +214,10 @@ describe("native pasted image cleanup", () => {
dataUrl: "data:image/png;base64,aGVsbG8=",
previewUri: "data:image/png;base64,aGVsbG8=",
}),
+ expect.objectContaining({ mimeType: "image/gif", dataUrl: "data:image/gif;base64,R0lGODlh" }),
]);
expect(files.get(uri)?.deleted).toBe(true);
+ expect(files.get(gif)?.deleted).toBe(true);
});
it("deletes rejected and overflow owned files without deleting user-owned files", async () => {
diff --git a/apps/mobile/src/lib/composerImages.ts b/apps/mobile/src/lib/composerImages.ts
index 7f7718f540ca2..6c19874e1df53 100644
--- a/apps/mobile/src/lib/composerImages.ts
+++ b/apps/mobile/src/lib/composerImages.ts
@@ -561,23 +561,25 @@ function isOwnedPastedImageUri(uri: string): boolean {
return false;
}
const segments = url.pathname.split("/").filter(Boolean);
- return (
- segments.at(-2) === OWNED_PASTED_IMAGE_DIRECTORY && segments.at(-1)?.endsWith(".png") === true
- );
+ return segments.at(-2) === OWNED_PASTED_IMAGE_DIRECTORY;
} catch {
return false;
}
}
+/** Leave out existingCount when the draft store caps after its duplicate check. */
export async function convertPastedImagesToAttachments(input: {
readonly uris: ReadonlyArray;
- readonly existingCount: number;
+ readonly existingCount?: number;
}): Promise<{
readonly attachments: ReadonlyArray;
readonly error: string | null;
}> {
const { File } = await import("expo-file-system");
- const remainingSlots = PROVIDER_SEND_TURN_MAX_ATTACHMENTS - input.existingCount;
+ const remainingSlots =
+ input.existingCount === undefined
+ ? Number.POSITIVE_INFINITY
+ : PROVIDER_SEND_TURN_MAX_ATTACHMENTS - input.existingCount;
const attachments: DraftComposerImageAttachment[] = [];
let error: string | null = null;
diff --git a/apps/mobile/src/lib/enrichedLinkPresentation.test.ts b/apps/mobile/src/lib/enrichedLinkPresentation.test.ts
index 4dd5ecbd08317..771674cc4eff6 100644
--- a/apps/mobile/src/lib/enrichedLinkPresentation.test.ts
+++ b/apps/mobile/src/lib/enrichedLinkPresentation.test.ts
@@ -34,6 +34,8 @@ describe("Enriched link presentation", () => {
"https://example.com/app.tsx",
"x + y",
"README.md",
+ "Dockerfile",
+ "docker/Dockerfiles",
"/app/settings",
]) {
expect(ENRICHED_INLINE_FILE_LINK_REGEX.test(text), text).toBe(false);
diff --git a/apps/mobile/src/lib/enrichedLinkPresentation.ts b/apps/mobile/src/lib/enrichedLinkPresentation.ts
index 5d2e9431339d1..f31d8659b6614 100644
--- a/apps/mobile/src/lib/enrichedLinkPresentation.ts
+++ b/apps/mobile/src/lib/enrichedLinkPresentation.ts
@@ -17,6 +17,7 @@ import {
parseComposerContextHref,
} from "@t3tools/shared/composerContextReferences";
import { hasThreadLinks, parseThreadLinkHref } from "@t3tools/shared/threadLinks";
+import { EXTENSIONLESS_FILE_NAMES } from "@t3tools/shared/markdownLinks";
export function enrichedContextLinkPresentation(
href: string,
@@ -91,8 +92,14 @@ export function enrichedLinkVariantPattern(url: string) {
return `^${url.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}$`;
}
-export const ENRICHED_INLINE_FILE_LINK_REGEX =
- /^(?!\S*:\/\/)(?:(?:\.{1,2}[\\/]|~[\\/]|\/(?:Users|home|tmp|var|etc|opt|mnt|Volumes|private|root|usr|bin|sbin|lib|lib64|srv|dev|proc|sys|run|boot|media|workspace|workspaces)\/|[A-Za-z]:[\\/])[^\s`]+|(?:[\p{L}\p{M}\p{N}._-]+[\\/])+[\p{L}\p{M}\p{N}._-]+\.[A-Za-z0-9_-]+(?::\d+(?::\d+|-\d+)?)?|[\p{L}\p{M}\p{N}._-]+\.[A-Za-z0-9_-]+:\d+(?::\d+|-\d+)?)$/u;
+const EXTENSIONLESS_FILE_NAME_PATTERN = [...EXTENSIONLESS_FILE_NAMES]
+ .map((name) => name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"))
+ .join("|");
+
+export const ENRICHED_INLINE_FILE_LINK_REGEX = new RegExp(
+ String.raw`^(?!\S*:\/\/)(?:(?:\.{1,2}[\\/]|~[\\/]|\/(?:Users|home|tmp|var|etc|opt|mnt|Volumes|private|root|usr|bin|sbin|lib|lib64|srv|dev|proc|sys|run|boot|media|workspace|workspaces)\/|[A-Za-z]:[\\/])[^\s\x60]+|(?:[\p{L}\p{M}\p{N}._-]+[\\/])+(?:[\p{L}\p{M}\p{N}._-]+\.[A-Za-z0-9_-]+|(?:${EXTENSIONLESS_FILE_NAME_PATTERN}))(?::\d+(?::\d+|-\d+)?)?|[\p{L}\p{M}\p{N}._-]+\.[A-Za-z0-9_-]+:\d+(?::\d+|-\d+)?)$`,
+ "u",
+);
export function enrichedSkillLinkRegex(skills?: ReadonlyArray) {
const names = [...new Set(skills?.map((skill) => skill.name) ?? [])].filter(Boolean);
diff --git a/apps/mobile/src/lib/filePreview.test.ts b/apps/mobile/src/lib/filePreview.test.ts
index 8363b0ba5c958..ffea5ab553372 100644
--- a/apps/mobile/src/lib/filePreview.test.ts
+++ b/apps/mobile/src/lib/filePreview.test.ts
@@ -12,6 +12,10 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test"
import { inlineFilePreviewKind, isPdfFile } from "./filePreview";
import { ThreadInlineFilePreview } from "../features/threads/ThreadInlineFilePreview";
+import {
+ ThreadMediaRetainContext,
+ ThreadMediaVisibleContext,
+} from "../features/threads/ThreadMarkdownVideo";
import { AudioFilePreview } from "../features/files/AudioFilePreview";
import { MediaVideoPlayer } from "../components/MediaVideoPlayer";
import { EnvironmentId, MessageId, ThreadId } from "@t3tools/contracts";
@@ -113,6 +117,7 @@ vi.mock("../components/ui/Button", () => ({
createElement("button", { onClick: props.onPress, disabled: props.disabled }, props.label),
}));
vi.mock("expo", () => ({
+ requireNativeModule: () => ({ is24HourFormat: () => true }),
useEvent: (_player: unknown, _event: unknown, initial: unknown) => initial,
useReleasingSharedObjectWithLifecycle: (
lifecycle: {
@@ -240,6 +245,7 @@ vi.mock("../components/ui/Menu", () => ({
}));
vi.mock("../components/ui/FilePreviewGallery", () => ({
FilePreviewGallery: ({ children }: { children?: ReactNode }) => children,
+ useFilePreviewGallery: () => (source: unknown) => source,
}));
vi.mock("../components/ui/FilePreviewModal", () => ({
FilePreviewModal: (props: { source: { name: string } | null }) =>
@@ -1299,6 +1305,59 @@ describe("ThreadInlineFilePreview playback", () => {
expect(audio.player.play).toHaveBeenCalledTimes(isLoaded ? 3 : 2);
},
);
+
+ it("keeps a started inline audio player mounted when its row scrolls out of view", async () => {
+ (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+ audio.status = { ...audio.status, isLoaded: true };
+ const container = document.createElement("div");
+ root = createRoot(container);
+ const retainRow = vi.fn();
+ const render = (visible: boolean) =>
+ root!.render(
+ createElement(
+ ThreadMediaRetainContext,
+ { value: retainRow },
+ createElement(
+ ThreadMediaVisibleContext,
+ { value: visible },
+ createElement(ThreadInlineFilePreview, {
+ source: { kind: "document", name: "sound.mp3", uri: "https://example.com/sound.mp3" },
+ onOpen() {},
+ }),
+ ),
+ ),
+ );
+ await act(async () => render(true));
+ const playButton = () =>
+ container.querySelector('button[aria-label="Play audio"]');
+ const pauseButton = () =>
+ container.querySelector('button[aria-label="Pause audio"]');
+ expect(playButton()).not.toBeNull();
+ // An idle preview still unmounts off-screen, so off-screen rows stay cheap.
+ await act(async () => render(false));
+ expect(playButton()).toBeNull();
+ await act(async () => render(true));
+ await act(async () => playButton()!.click());
+ expect(audio.player.play).toHaveBeenCalledOnce();
+ expect(pauseButton()).not.toBeNull();
+ // The feed list recycles rows beyond its draw distance, so the row itself is pinned too.
+ expect(retainRow).toHaveBeenLastCalledWith(true);
+ audio.player.release.mockClear();
+ audio.player.pause.mockClear();
+ // Scrolling the playing chip out of view (or a new reply pushing it out)
+ // must not unmount it: unmounting disposes the native player mid-playback.
+ await act(async () => render(false));
+ expect(pauseButton()).not.toBeNull();
+ expect(audio.player.release).not.toHaveBeenCalled();
+ expect(audio.player.pause).not.toHaveBeenCalled();
+ // Once playback finishes, the off-screen preview can unmount again.
+ audio.status = { ...audio.status, didJustFinish: true, currentTime: 10 };
+ await act(async () => render(false));
+ expect(pauseButton()).toBeNull();
+ expect(playButton()).toBeNull();
+ expect(audio.player.release).toHaveBeenCalledOnce();
+ expect(retainRow).toHaveBeenLastCalledWith(false);
+ });
});
describe("PDF preview detection", () => {
diff --git a/apps/mobile/src/lib/filePreviewGallery.ts b/apps/mobile/src/lib/filePreviewGallery.ts
index 295f46e861825..e8b2f4e19f838 100644
--- a/apps/mobile/src/lib/filePreviewGallery.ts
+++ b/apps/mobile/src/lib/filePreviewGallery.ts
@@ -12,6 +12,11 @@ export function filePreviewKey(source: FilePreviewItem): string {
return source.uri;
}
+/** The thumbnail a gallery page opens from and closes into, including pages that were not tapped. */
+export function filePreviewSourceIdentifier(source: FilePreviewItem): string {
+ return source.sourceIdentifier ?? `preview:${filePreviewKey(source)}`;
+}
+
export function filePreviewGallery(source: FilePreviewSource, group: readonly FilePreviewItem[]) {
if (source.kind !== "image") return [source];
const selectedKey = filePreviewKey(source);
diff --git a/apps/mobile/src/lib/markdownInlineFileLinks.test.ts b/apps/mobile/src/lib/markdownInlineFileLinks.test.ts
index e2d81cf869561..3de6590dc7a4b 100644
--- a/apps/mobile/src/lib/markdownInlineFileLinks.test.ts
+++ b/apps/mobile/src/lib/markdownInlineFileLinks.test.ts
@@ -93,7 +93,13 @@ describe("inline code that names a file", () => {
expect(rewrite("See `src/math.ts:2` and `./README.md`.")).toBe(
"See [src/math.ts:2]() and [./README.md](<./README.md>).",
);
- for (const path of ["src/數學.ts:2", "數學/math.ts:2", "數學.ts:2", "src/數學.ts:2-4"]) {
+ for (const path of [
+ "src/數學.ts:2",
+ "數學/math.ts:2",
+ "數學.ts:2",
+ "src/數學.ts:2-4",
+ "docker/Dockerfile",
+ ]) {
expect(rewrite(`See \`${path}\`.`), path).toBe(`See [${path}](<${path}>).`);
}
});
diff --git a/apps/mobile/src/lib/modelOptions.test.ts b/apps/mobile/src/lib/modelOptions.test.ts
index 51651dd5250ad..32b50983a8ca7 100644
--- a/apps/mobile/src/lib/modelOptions.test.ts
+++ b/apps/mobile/src/lib/modelOptions.test.ts
@@ -18,6 +18,7 @@ import {
resolveDefaultableModelSelection,
resolveNewTaskModelSelection,
resolveSelectableModelSelection,
+ withStoredThreadModelOptions,
type ModelOption,
} from "./modelOptions";
@@ -232,6 +233,27 @@ describe("mobile model options", () => {
expect(explicitOption?.selection.options).toEqual([{ id: "serviceTier", value: "priority" }]);
});
+ it("carries a thread's stored options onto an optionless pick of its own model", () => {
+ const claude = ProviderInstanceId.make("claudeAgent");
+ const stored: ModelSelection = {
+ instanceId: claude,
+ model: "claude-opus-5-5",
+ options: [{ id: "effort", value: "high" }],
+ };
+ expect(
+ withStoredThreadModelOptions({ instanceId: claude, model: stored.model }, stored),
+ ).toEqual(stored);
+ const remembered: ModelSelection = { ...stored, options: [{ id: "effort", value: "low" }] };
+ expect(withStoredThreadModelOptions(remembered, stored)).toBe(remembered);
+ const otherInstance: ModelSelection = {
+ instanceId: ProviderInstanceId.make("claude_work"),
+ model: stored.model,
+ };
+ expect(withStoredThreadModelOptions(otherInstance, stored)).toBe(otherInstance);
+ const otherModel: ModelSelection = { instanceId: claude, model: "claude-sonnet-5-5" };
+ expect(withStoredThreadModelOptions(otherModel, stored)).toBe(otherModel);
+ });
+
it("limits existing threads to their provider while new tasks keep every provider", () => {
const providers = ["codex", "claudeAgent"].map((instanceId) => ({
instanceId,
diff --git a/apps/mobile/src/lib/modelOptions.ts b/apps/mobile/src/lib/modelOptions.ts
index 5d7c9d1443d33..f9c6d02b8dd77 100644
--- a/apps/mobile/src/lib/modelOptions.ts
+++ b/apps/mobile/src/lib/modelOptions.ts
@@ -288,6 +288,22 @@ export function resolveNewTaskModelSelection(input: {
);
}
+// Rows built after a pick on another instance carry no options for the thread's own model.
+export function withStoredThreadModelOptions(
+ selection: ModelSelection,
+ stored: ModelSelection,
+): ModelSelection {
+ if (
+ (selection.options?.length ?? 0) > 0 ||
+ !stored.options?.length ||
+ selection.instanceId !== stored.instanceId ||
+ selection.model !== stored.model
+ ) {
+ return selection;
+ }
+ return { ...selection, options: stored.options };
+}
+
export function buildModelOptions(
config: T3ServerConfig | null | undefined,
fallbackModelSelection: ModelSelection | null,
diff --git a/apps/mobile/src/lib/reserved-regions.test.ts b/apps/mobile/src/lib/reserved-regions.test.ts
index c5faebc31653c..60dd501ae37a4 100644
--- a/apps/mobile/src/lib/reserved-regions.test.ts
+++ b/apps/mobile/src/lib/reserved-regions.test.ts
@@ -1,5 +1,9 @@
import { describe, expect, it } from "vite-plus/test";
-import { deriveBottomControlInsets, type NativeLayoutMetrics } from "./reserved-regions";
+import {
+ deriveBottomControlInsets,
+ deriveContentSideInsets,
+ type NativeLayoutMetrics,
+} from "./reserved-regions";
import { deriveLayout, deriveWorkspacePaneLayout } from "./layout";
const innerDisplay: NativeLayoutMetrics = {
@@ -21,26 +25,27 @@ describe("bottom controls around reserved regions", () => {
expect(innerDisplay.width - insets.left - insets.right).toBeGreaterThan(320);
});
- it("does not reserve a hinge twice when a native column starts at the division", () => {
+ it("starts the editor after a fold that covers a native column's leading edge", () => {
expect(
deriveBottomControlInsets({
...innerDisplay,
- width: 412,
+ width: 411.33,
+ height: 669,
safeArea: { top: 82, bottom: 34, left: 0, right: 0 },
- reservedRegions: [{ kind: "division", x: 0, y: 0, width: 40, height: 560 }],
+ reservedRegions: [{ kind: "division", x: 0, y: 0, width: 39.83, height: 669 }],
}),
- ).toEqual({ left: 0, right: 0, bottom: 0 });
+ ).toEqual({ left: 39.83, right: 0, bottom: 0 });
});
- it("keeps a native column's trailing division at its existing edge", () => {
+ it("does not reserve a hinge twice when the safe area already covers it", () => {
expect(
deriveBottomControlInsets({
...innerDisplay,
- width: 456,
- safeArea: { top: 82, bottom: 34, left: 0, right: 0 },
- reservedRegions: [{ kind: "division", x: 455.75, y: 0, width: 0.25, height: 560 }],
+ width: 412,
+ safeArea: { top: 82, bottom: 34, left: 40, right: 0 },
+ reservedRegions: [{ kind: "division", x: 0, y: 0, width: 40, height: 560 }],
}),
- ).toEqual({ left: 0, right: 0, bottom: 0 });
+ ).toEqual({ left: 40, right: 0, bottom: 0 });
});
it("keeps controls below a horizontal fold in a hands-free pose", () => {
@@ -65,6 +70,59 @@ describe("bottom controls around reserved regions", () => {
});
});
+describe("content side insets around reserved regions", () => {
+ it("keeps transcript text on the wider side of a book fold", () => {
+ expect(
+ deriveContentSideInsets({
+ ...innerDisplay,
+ reservedRegions: [{ kind: "division", x: 456, y: 0, width: 48, height: 560 }],
+ }),
+ ).toEqual({ left: 8, right: 504 });
+ expect(
+ deriveContentSideInsets({
+ ...innerDisplay,
+ width: 800,
+ reservedRegions: [{ kind: "division", x: 240, y: 0, width: 40, height: 560 }],
+ }),
+ ).toEqual({ left: 280, right: 72 });
+ });
+
+ it("starts transcript text after a fold that covers a native column's leading edge", () => {
+ expect(
+ deriveContentSideInsets({
+ ...innerDisplay,
+ width: 411.33,
+ height: 669,
+ safeArea: { top: 82, bottom: 34, left: 0, right: 0 },
+ reservedRegions: [{ kind: "division", x: 0, y: 0, width: 39.83, height: 669 }],
+ }),
+ ).toEqual({ left: 39.83, right: 0 });
+ });
+
+ it("ends transcript text before a fold at a native column's trailing edge", () => {
+ expect(
+ deriveContentSideInsets({
+ ...innerDisplay,
+ width: 456,
+ safeArea: { top: 82, bottom: 34, left: 0, right: 0 },
+ reservedRegions: [{ kind: "division", x: 416, y: 0, width: 40, height: 560 }],
+ }),
+ ).toEqual({ left: 0, right: 40 });
+ });
+
+ it("ignores a horizontal fold and bottom cameras", () => {
+ expect(
+ deriveContentSideInsets({
+ ...innerDisplay,
+ reservedRegions: [
+ { kind: "division", x: 0, y: 240, width: 960, height: 40 },
+ { kind: "occlusion", x: 8, y: 510, width: 60, height: 50 },
+ ],
+ }),
+ ).toEqual({ left: 8, right: 72 });
+ });
+});
+
describe("Duo workspace sizing", () => {
it("shows both columns on the unfolded inner display in portrait", () => {
// Reported by the iOS 27.1 Duo simulator: no side bar or fold, only the hinge.
diff --git a/apps/mobile/src/lib/reserved-regions.ts b/apps/mobile/src/lib/reserved-regions.ts
index bb8ff981a6de9..a3d8b6c140657 100644
--- a/apps/mobile/src/lib/reserved-regions.ts
+++ b/apps/mobile/src/lib/reserved-regions.ts
@@ -23,6 +23,30 @@ export interface NativeLayoutMetrics {
readonly bottomBarInset?: number;
}
+function isFullHeightDivision(region: ReservedRegion, metrics: NativeLayoutMetrics) {
+ return region.kind === "division" && region.height >= metrics.height / 2;
+}
+
+function sideOfDivision(left: number, right: number, x: number, endX: number) {
+ if (x <= left) return { left: Math.min(right, endX), right };
+ if (endX >= right) return { left, right: Math.max(left, x) };
+ return right - endX >= x - left ? { left: endX, right } : { left, right: x };
+}
+
+export function deriveContentSideInsets(metrics: NativeLayoutMetrics | null) {
+ if (!metrics) return { left: 0, right: 0 };
+ let left = metrics.safeArea.left;
+ let right = metrics.width - metrics.safeArea.right;
+ for (const region of metrics.reservedRegions) {
+ if (!isFullHeightDivision(region, metrics)) continue;
+ const x = Math.max(left, region.x);
+ const endX = Math.min(right, region.x + region.width);
+ if (endX <= x) continue;
+ ({ left, right } = sideOfDivision(left, right, x, endX));
+ }
+ return { left, right: metrics.width - right };
+}
+
export function deriveBottomControlInsets(metrics: NativeLayoutMetrics | null) {
if (!metrics) return { left: 0, right: 0, bottom: 0 };
let left = metrics.safeArea.left;
@@ -34,12 +58,8 @@ export function deriveBottomControlInsets(metrics: NativeLayoutMetrics | null) {
const y = Math.max(0, region.y);
const endY = Math.min(bottom, region.y + region.height);
if (endX <= x || endY <= y) continue;
- if (region.kind === "division" && region.height >= metrics.height / 2) {
- // A native column ending at a division is already split there. Only an
- // interior division needs to move these controls into one side of the view.
- if (x <= left || endX >= right) continue;
- if (right - endX >= x - left) left = endX;
- else right = x;
+ if (isFullHeightDivision(region, metrics)) {
+ ({ left, right } = sideOfDivision(left, right, x, endX));
} else if (endY >= bottom - metrics.safeArea.bottom) {
if (region.width >= right - left) bottom = y;
else if (right - endX >= x - left) left = endX;
diff --git a/apps/mobile/src/lib/sentImageHandoff.ts b/apps/mobile/src/lib/sentImageHandoff.ts
new file mode 100644
index 0000000000000..33a728379cc01
--- /dev/null
+++ b/apps/mobile/src/lib/sentImageHandoff.ts
@@ -0,0 +1,36 @@
+export interface SentImageHandoff {
+ readonly uri: string;
+ readonly aspectRatio: number;
+}
+
+// A sent image's local pixels and shape, so the pending bubble and then the delivered copy open at
+// their final size over pixels already on screen instead of a placeholder that later resizes.
+// The server re-ids attachments into the thread, so delivered images match by message and position.
+const MAX_ENTRIES = 64;
+const images = new Map();
+
+function remember(key: string, image: SentImageHandoff) {
+ if (!Number.isFinite(image.aspectRatio) || image.aspectRatio <= 0) return;
+ images.delete(key);
+ images.set(key, image);
+ if (images.size > MAX_ENTRIES) images.delete(images.keys().next().value!);
+}
+
+export function rememberDraftImage(attachmentId: string, image: SentImageHandoff): void {
+ remember(`draft:${attachmentId}`, image);
+}
+
+export function rememberSentImage(messageId: string, index: number, image: SentImageHandoff): void {
+ remember(`message:${messageId}:${index}`, image);
+}
+
+export function sentImageHandoff(
+ messageId: string,
+ index: number,
+ draftAttachmentId?: string,
+): SentImageHandoff | undefined {
+ return (
+ images.get(`message:${messageId}:${index}`) ??
+ (draftAttachmentId === undefined ? undefined : images.get(`draft:${draftAttachmentId}`))
+ );
+}
diff --git a/apps/mobile/src/lib/time.test.ts b/apps/mobile/src/lib/time.test.ts
index 8881b6bbab8b7..c9c24b9c8f97f 100644
--- a/apps/mobile/src/lib/time.test.ts
+++ b/apps/mobile/src/lib/time.test.ts
@@ -1,9 +1,39 @@
import { describe, expect, it } from "vite-plus/test";
-import { msUntilRelativeTimeChange, relativeTime } from "./time";
+import { byTimestamp, compareTimestamps, msUntilRelativeTimeChange, relativeTime } from "./time";
const at = "2026-10-19T12:00:00.000Z";
const timestamp = Date.parse(at);
+describe("timestamp order", () => {
+ it("orders host timestamps by instant across offsets and fractional seconds, missing ones first", () => {
+ const dates = [
+ "2026-07-05T00:30:00.5Z",
+ "2026-07-05T01:00:00+02:00",
+ "",
+ "2026-07-05T00:30:00Z",
+ ];
+
+ expect(dates.toSorted(compareTimestamps)).toEqual([
+ "",
+ "2026-07-05T01:00:00+02:00",
+ "2026-07-05T00:30:00Z",
+ "2026-07-05T00:30:00.5Z",
+ ]);
+ });
+ it("keeps equal instants in input order whichever way it sorts", () => {
+ const rows = [
+ { id: "comment", date: "2026-07-05T00:30:00Z" },
+ { id: "commit", date: "2026-07-04T20:30:00-04:00" },
+ { id: "older", date: "2026-07-04T00:00:00Z" },
+ ];
+ const ids = (newestFirst: boolean) =>
+ rows.toSorted(byTimestamp(newestFirst)).map((row) => row.id);
+
+ expect(ids(false)).toEqual(["older", "comment", "commit"]);
+ expect(ids(true)).toEqual(["comment", "commit", "older"]);
+ });
+});
+
describe("relative time", () => {
it.each([
[59_999, "<1m", "1m"],
diff --git a/apps/mobile/src/lib/time.ts b/apps/mobile/src/lib/time.ts
index 8635ccb37138b..5a32e16fc75c9 100644
--- a/apps/mobile/src/lib/time.ts
+++ b/apps/mobile/src/lib/time.ts
@@ -1,3 +1,15 @@
+// Host timestamps may carry UTC offsets or mixed fractions, so text order is not time order.
+export function compareTimestamps(left: string, right: string): number {
+ return (Date.parse(left) || 0) - (Date.parse(right) || 0);
+}
+
+export function byTimestamp(newestFirst: boolean) {
+ return (left: { readonly date: string }, right: { readonly date: string }) =>
+ newestFirst
+ ? compareTimestamps(right.date, left.date)
+ : compareTimestamps(left.date, right.date);
+}
+
export function relativeTime(input: string, nowMs: number = Date.now()): string {
const timestamp = Date.parse(input);
if (Number.isNaN(timestamp)) {
diff --git a/apps/mobile/src/lib/videoThumbnails.test.ts b/apps/mobile/src/lib/videoThumbnails.test.ts
index 155a906143a26..a35e62b98ae71 100644
--- a/apps/mobile/src/lib/videoThumbnails.test.ts
+++ b/apps/mobile/src/lib/videoThumbnails.test.ts
@@ -5,11 +5,20 @@ vi.mock("expo-video", () => ({ createVideoPlayer: mocks.createPlayer }));
let thumbnails: typeof import("./videoThumbnails");
const frame = { width: 480, height: 270 };
-const player = () => ({
- replaceAsync: vi.fn(async (): Promise => {}),
- generateThumbnailsAsync: vi.fn(async () => [frame]),
- release: vi.fn(),
-});
+const player = () => {
+ const listeners = new Set<(event: { source: unknown }) => void>();
+ const attach = () => listeners.forEach((listener) => listener({ source: {} }));
+ return {
+ attach,
+ addListener: vi.fn((_event: string, listener: (event: { source: unknown }) => void) => {
+ listeners.add(listener);
+ return { remove: () => listeners.delete(listener) };
+ }),
+ replaceAsync: vi.fn(async (): Promise => queueMicrotask(attach)),
+ generateThumbnailsAsync: vi.fn(async () => [frame]),
+ release: vi.fn(),
+ };
+};
const source = () => ({ uri: "file:///clip.mp4", dispose: vi.fn() });
beforeEach(async () => {
@@ -51,7 +60,7 @@ describe("video thumbnails", () => {
expect(first.release).toHaveBeenCalledTimes(1);
});
- it("releases an active canceled player and ignores late source loading", async () => {
+ it("finishes a started extraction after its reader leaves so a re-signed URL reuses it", async () => {
const started = Promise.withResolvers();
const replaced = Promise.withResolvers();
const first = player();
@@ -62,21 +71,71 @@ describe("video thumbnails", () => {
mocks.createPlayer.mockReturnValueOnce(first);
const file = source();
const controller = new AbortController();
- const request = thumbnails.loadVideoThumbnail("canceled", async () => file, controller.signal);
+ const request = thumbnails.loadVideoThumbnail("video", async () => file, controller.signal);
await started.promise;
controller.abort();
- expect(await request).toBeNull();
+ const resigned = thumbnails.loadVideoThumbnail(
+ "video",
+ async () => source(),
+ new AbortController().signal,
+ );
+ replaced.resolve();
+ first.attach();
+ expect(await request).toBe(frame);
+ expect(await resigned).toBe(frame);
+ expect(mocks.createPlayer).toHaveBeenCalledTimes(1);
expect(first.release).toHaveBeenCalledTimes(1);
expect(file.dispose).toHaveBeenCalledTimes(1);
- replaced.resolve();
- expect(
- await thumbnails.loadVideoThumbnail(
- "next",
- async () => source(),
- new AbortController().signal,
- ),
- ).toBe(frame);
+ });
+
+ it("asks for a frame only once the player has attached the item", async () => {
+ const first = player();
+ let attached = false;
+ // Like iOS: replaceAsync resolves before the item attaches, and until then
+ // generateThumbnailsAsync finds no asset.
+ first.replaceAsync.mockImplementation(async () => {});
+ first.generateThumbnailsAsync.mockImplementation(async () => (attached ? [frame] : []));
+ mocks.createPlayer.mockReturnValueOnce(first);
+ const request = thumbnails.loadVideoThumbnail(
+ "attach",
+ async () => source(),
+ new AbortController().signal,
+ );
+ await vi.waitFor(() => expect(first.replaceAsync).toHaveBeenCalled());
+ await first.replaceAsync.mock.results[0]!.value;
+ attached = true;
+ first.attach();
+ expect(await request).toBe(frame);
+ });
+
+ it("gives up on an item that never attaches without holding up the next request", async () => {
+ vi.useFakeTimers();
+ const first = player();
+ const subscriptions: Array<{ remove: ReturnType }> = [];
+ first.addListener.mockImplementation(() => {
+ const subscription = { remove: vi.fn() };
+ subscriptions.push(subscription);
+ return subscription;
+ });
+ first.replaceAsync.mockImplementation(async () => {});
+ mocks.createPlayer.mockReturnValueOnce(first);
+ const file = source();
+ const stuck = thumbnails.loadVideoThumbnail(
+ "never-attached",
+ async () => file,
+ new AbortController().signal,
+ );
+ const next = thumbnails.loadVideoThumbnail(
+ "next",
+ async () => source(),
+ new AbortController().signal,
+ );
+ await vi.advanceTimersByTimeAsync(15_000);
+ expect(await stuck).toBeNull();
expect(first.generateThumbnailsAsync).not.toHaveBeenCalled();
- expect(thumbnails.cachedVideoThumbnail("canceled")).toBeNull();
+ expect(subscriptions[0]!.remove).toHaveBeenCalledTimes(1);
+ expect(first.release).toHaveBeenCalledTimes(1);
+ expect(file.dispose).toHaveBeenCalledTimes(1);
+ expect(await next).toBe(frame);
});
});
diff --git a/apps/mobile/src/lib/videoThumbnails.ts b/apps/mobile/src/lib/videoThumbnails.ts
index 7606a71457dba..33e4f74e42f63 100644
--- a/apps/mobile/src/lib/videoThumbnails.ts
+++ b/apps/mobile/src/lib/videoThumbnails.ts
@@ -10,35 +10,40 @@ export function cachedVideoThumbnail(key: string): VideoThumbnail | null {
return thumbnails.get(key) ?? null;
}
-async function extractFrame(uri: string, signal: AbortSignal) {
+async function extractFrame(uri: string) {
const { createVideoPlayer } = await import("expo-video");
- if (signal.aborted) return null;
const player = createVideoPlayer(null);
let disposed = false;
- let cancel = () => {};
let timeout: ReturnType | undefined;
+ let attachedSubscription: { remove(): void } | undefined;
try {
// Never play or change audio settings: thumbnails must leave the shared audio session alone.
player.bufferOptions = { preferredForwardBufferDuration: 1 };
- const canceled = new Promise((resolve) => {
- cancel = () => resolve(null);
+ const timedOut = new Promise((resolve) => {
+ timeout = setTimeout(() => resolve(null), 15_000);
+ });
+ // iOS resolves replaceAsync before the main thread attaches the item, and until then
+ // generateThumbnailsAsync finds no asset and returns no frames.
+ const attached = new Promise((resolve) => {
+ attachedSubscription = player.addListener("sourceChange", ({ source }) => {
+ if (source) resolve();
+ });
});
- signal.addEventListener("abort", cancel, { once: true });
- timeout = setTimeout(cancel, 15_000);
const frame = (async () => {
await player.replaceAsync({ uri, contentType: "progressive" });
- if (disposed || signal.aborted) return null;
+ await attached;
+ if (disposed) return null;
const [thumbnail] = await player.generateThumbnailsAsync([0], {
maxWidth: 480,
maxHeight: 480,
});
return thumbnail ?? null;
})();
- return await Promise.race([frame, canceled]);
+ return await Promise.race([frame, timedOut]);
} finally {
disposed = true;
clearTimeout(timeout);
- signal.removeEventListener("abort", cancel);
+ attachedSubscription?.remove();
player.release();
}
}
@@ -62,8 +67,11 @@ export function loadVideoThumbnail(
const source = await resolveSource(signal);
if (!source) return null;
try {
- const thumbnail = await extractFrame(source.uri, signal);
- if (!thumbnail || signal.aborted) return null;
+ if (signal.aborted) return null;
+ // A started extraction finishes even if its reader leaves: its requests are already in
+ // flight, and a re-signed URL for the same video replaces the reader, not the frame.
+ const thumbnail = await extractFrame(source.uri);
+ if (!thumbnail) return null;
thumbnails.set(key, thumbnail);
if (thumbnails.size > MAX_CACHED_THUMBNAILS) {
thumbnails.delete(thumbnails.keys().next().value!);
diff --git a/apps/mobile/src/native/NativeColumnContent.ios.tsx b/apps/mobile/src/native/NativeColumnContent.ios.tsx
index 30350b5117154..48581ad3b09f8 100644
--- a/apps/mobile/src/native/NativeColumnContent.ios.tsx
+++ b/apps/mobile/src/native/NativeColumnContent.ios.tsx
@@ -1,18 +1,34 @@
import { HeaderHeightContext } from "@react-navigation/elements";
-import { useState, type ReactNode } from "react";
+import { use, useState, type ReactNode } from "react";
import { View, type ColorValue } from "react-native";
import { SafeAreaProvider, SafeAreaView } from "react-native-safe-area-context";
import { NativeColumnLayoutMetricsContext } from "./native-layout-metrics";
import type { NativeLayoutMetrics } from "../lib/reserved-regions";
import { NativeLayoutObserver } from "./NativeLayoutObserver";
+import {
+ NativeWorkspaceTabActivityContext,
+ WorkspaceColumnMetricsContext,
+} from "./v5-workspace-context";
export function NativeColumnContent(props: {
readonly children: ReactNode;
readonly primary?: boolean;
readonly insetHorizontally?: boolean;
readonly backgroundColor?: ColorValue;
+ /** Shares this column's metrics across workspace tabs; see `WorkspaceColumnMetricsContext`. */
+ readonly column?: string;
}) {
- const [metrics, setMetrics] = useState(null);
+ const tabActivity = use(NativeWorkspaceTabActivityContext);
+ const shared = use(WorkspaceColumnMetricsContext);
+ const [measured, setMeasured] = useState(null);
+ const onMetrics = (next: NativeLayoutMetrics) => {
+ // A hidden tab's insets lack the bars UIKit lays out only for the selected tab.
+ if (tabActivity && !tabActivity.isActive()) return;
+ setMeasured(next);
+ if (props.column !== undefined) shared?.publish(props.column, next);
+ };
+ const metrics =
+ measured ?? (props.column === undefined ? null : (shared?.byColumn.get(props.column) ?? null));
return (
{/* Observe the inset body. UIKit can reserve other columns in its safe area. */}
-
+
{props.children}
diff --git a/apps/mobile/src/native/StackHeader.tsx b/apps/mobile/src/native/StackHeader.tsx
index 2bff74d28c690..d8a4f5df771e4 100644
--- a/apps/mobile/src/native/StackHeader.tsx
+++ b/apps/mobile/src/native/StackHeader.tsx
@@ -190,7 +190,8 @@ export function NativeStackScreenOptions(props: {
}) {
const navigation = useNativeStackNavigation();
const setOptions = useScreenOptionsWriter();
- const tabActive = use(NativeWorkspaceTabActivityContext)?.active ?? true;
+ const tabActivity = use(NativeWorkspaceTabActivityContext);
+ const tabActive = tabActivity ? tabActivity.active || tabActivity.headerOnly === true : true;
const lastAppliedOptionsSignatureRef = useRef(undefined);
const latestOptionFunctionsRef = useRef(new Map unknown>());
const optionFunctionWrappersRef = useRef(new Map unknown>());
diff --git a/apps/mobile/src/native/T3ComposerEditor.ios.tsx b/apps/mobile/src/native/T3ComposerEditor.ios.tsx
index 437bcda4d012d..56f80be2e7be8 100644
--- a/apps/mobile/src/native/T3ComposerEditor.ios.tsx
+++ b/apps/mobile/src/native/T3ComposerEditor.ios.tsx
@@ -27,7 +27,7 @@ import { contextChipIconUri, modelChipIcon, modelChipIconUri } from "../lib/cont
import { useUniwindTheme } from "../lib/useUniwindTheme";
import { createNativeComposerTheme } from "../lib/nativeComposerTheme";
import { FONT_FAMILIES } from "../lib/fontFamilies";
-import { useScaledTextRole } from "../features/settings/appearance/useScaledTextRole";
+import { useComposerTextRole } from "../features/settings/appearance/useScaledTextRole";
import {
acknowledgeComposerNativeEvent,
assumeComposerControlledState,
@@ -176,7 +176,7 @@ export function ComposerEditor({
});
setConfirmedTokens({ value: props.value, tokens });
}
- const bodyText = useScaledTextRole("body");
+ const bodyText = useComposerTextRole();
const theme = useUniwindTheme();
const fontFamily = FONT_FAMILIES.regular;
diff --git a/apps/mobile/src/native/createV5StackNavigator.ios.test.tsx b/apps/mobile/src/native/createV5StackNavigator.ios.test.tsx
new file mode 100644
index 0000000000000..40f691db4f015
--- /dev/null
+++ b/apps/mobile/src/native/createV5StackNavigator.ios.test.tsx
@@ -0,0 +1,95 @@
+import type { ParamListBase, StackNavigationState } from "@react-navigation/native";
+import { act, createContext, type ComponentProps, type ReactNode } from "react";
+import { createRoot } from "react-dom/client";
+import type { Stack as NativeStack } from "react-native-screens";
+import { expect, it, vi } from "vite-plus/test";
+
+type ScreenProps = ComponentProps;
+const screens = vi.hoisted(() => new Map());
+
+vi.mock("react-native", () => ({
+ StyleSheet: { flatten: (style: unknown) => style },
+ View: ({ children }: { children?: ReactNode }) => children,
+}));
+vi.mock("react-native-screens", () => ({
+ Stack: {
+ Host: ({ children }: { children?: ReactNode }) => children,
+ Screen: (props: ScreenProps) => {
+ screens.set(props.screenKey, props);
+ return null;
+ },
+ },
+}));
+vi.mock("@react-navigation/native", () => ({
+ NavigationContext: createContext(undefined),
+ NavigationRouteContext: createContext(undefined),
+ usePreventRemoveContext: () => ({ preventedRoutes: {} }),
+}));
+vi.mock("@react-navigation/native-stack", () => ({ NativeStackView: () => null }));
+vi.mock("./V5StackHeader.ios", () => ({ V5StackHeader: () => null }));
+vi.mock("./NativeColumnContent.ios", () => ({ NativeColumnContent: () => null }));
+vi.mock("./NativeScrollViewMarker", () => ({
+ NativeScrollEdgeEffectsContext: createContext(undefined),
+}));
+
+import { V5CardStackView, type V5StackViewProps } from "./createV5StackNavigator.ios";
+
+const home = { key: "home", name: "Home" };
+const thread = { key: "thread", name: "Thread" };
+
+function fire(key: string, event: "onWillAppear" | "onWillDisappear" | "onDidDisappear") {
+ const handler = screens.get(key)?.[event] as (() => void) | undefined;
+ if (!handler) throw new Error(`No ${event} for ${key}`);
+ act(() => handler());
+}
+
+it("forgets native Back when a full-screen presentation covers the top card", () => {
+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
+ const state: StackNavigationState = {
+ key: "stack",
+ type: "stack",
+ stale: false,
+ index: 1,
+ routeNames: ["Home", "Thread"],
+ routes: [home, thread],
+ preloadedRoutes: [],
+ };
+ const navigation = { getState: () => state, emit: vi.fn(), dispatch: vi.fn() };
+ const descriptor = (route: typeof home) => ({
+ route,
+ navigation,
+ options: {},
+ render: () => null,
+ });
+ const onNativePopChange = vi.fn();
+ const root = createRoot(document.createElement("div"));
+ try {
+ act(() =>
+ root.render(
+ descriptor(home),
+ } as unknown as V5StackViewProps)}
+ onNativePopChange={onNativePopChange}
+ />,
+ ),
+ );
+
+ // A presentation covers the thread: nothing in the stack appears beneath it.
+ fire("thread", "onWillDisappear");
+ fire("thread", "onDidDisappear");
+ expect(onNativePopChange).toHaveBeenLastCalledWith(null);
+
+ // Native Back reveals Home, so the thread stays the card being popped.
+ fire("thread", "onWillDisappear");
+ fire("home", "onWillAppear");
+ fire("thread", "onDidDisappear");
+ expect(onNativePopChange).toHaveBeenLastCalledWith("thread");
+ } finally {
+ act(() => root.unmount());
+ vi.unstubAllGlobals();
+ }
+});
diff --git a/apps/mobile/src/native/createV5StackNavigator.ios.tsx b/apps/mobile/src/native/createV5StackNavigator.ios.tsx
index 31490b85283f3..c4c4f80837bc6 100644
--- a/apps/mobile/src/native/createV5StackNavigator.ios.tsx
+++ b/apps/mobile/src/native/createV5StackNavigator.ios.tsx
@@ -63,6 +63,8 @@ export function V5CardStackView(
// Options a screen set inside this workspace tab slot, over its route's.
const slot = use(WorkspaceSlotOptionsContext);
const nativePopSource = useRef(null);
+ // Back reveals the card beneath; a full-screen presentation covers the card without revealing one.
+ const cardRevealed = useRef(false);
const { onNativePopChange } = props;
const setNativePopSource = useCallback(
(key: string | null) => {
@@ -175,6 +177,7 @@ export function V5CardStackView(
if (preventedRoutes[route.key]?.preventRemove) descriptor.navigation.goBack();
}}
onWillAppear={() => {
+ cardRevealed.current = true;
if (index === 0) props.onRootVisibilityChange?.(true);
props.navigation.emit({
type: "transitionStart",
@@ -217,6 +220,7 @@ export function V5CardStackView(
const state = props.navigation.getState();
// Only native Back leaves the disappearing card active; JS navigation already changed history.
if (state.index > 0 && state.routes[state.index]?.key === route.key) {
+ cardRevealed.current = false;
setNativePopSource(route.key);
}
props.navigation.emit({
@@ -225,13 +229,16 @@ export function V5CardStackView(
data: { closing: true },
});
}}
- onDidDisappear={() =>
+ onDidDisappear={() => {
+ if (nativePopSource.current === route.key && !cardRevealed.current) {
+ setNativePopSource(null);
+ }
props.navigation.emit({
type: "transitionEnd",
target: route.key,
data: { closing: true },
- })
- }
+ });
+ }}
>
diff --git a/apps/mobile/src/native/v5-workspace-context.tsx b/apps/mobile/src/native/v5-workspace-context.tsx
index 4c4dbf562f0e7..f99c55673a16f 100644
--- a/apps/mobile/src/native/v5-workspace-context.tsx
+++ b/apps/mobile/src/native/v5-workspace-context.tsx
@@ -1,6 +1,7 @@
import { createContext } from "react";
import type { InspectorContent } from "../features/layout/inspector-panes";
+import type { NativeLayoutMetrics } from "../lib/reserved-regions";
export const NativeWorkspaceModeContext = createContext(false);
/**
@@ -28,6 +29,19 @@ export function slotScreenOptions(
export const NativeWorkspaceTabActivityContext = createContext<{
readonly active: boolean;
readonly isActive: () => boolean;
+ /**
+ * A tab not shown yet mounts only its header, so UIKit can put it in the window once before
+ * the first visit; it writes header options while inactive and loads nothing.
+ */
+ readonly headerOnly?: boolean;
+} | null>(null);
+/**
+ * What the shown workspace tab measured per column. UIKit lays out bars and safe areas only for
+ * the selected tab, so a tab that hasn't been shown yet starts from these instead.
+ */
+export const WorkspaceColumnMetricsContext = createContext<{
+ readonly byColumn: ReadonlyMap;
+ readonly publish: (column: string, metrics: NativeLayoutMetrics) => void;
} | null>(null);
export const NativePrimaryColumnContext = createContext<{
readonly presented: boolean;
diff --git a/apps/mobile/src/native/workspace-stack-projection.test.ts b/apps/mobile/src/native/workspace-stack-projection.test.ts
index 023afc637c011..78b5b3d092425 100644
--- a/apps/mobile/src/native/workspace-stack-projection.test.ts
+++ b/apps/mobile/src/native/workspace-stack-projection.test.ts
@@ -246,7 +246,7 @@ describe("collapsed split Back", () => {
routeParamList: {},
routeGetIdList: {},
};
- type Appearance = "willAppear" | "didAppear" | "willDisappear";
+ type Appearance = "willAppear" | "didAppear" | "willDisappear" | "didDisappear";
// UIKit's appearance callbacks for one collapsed transition, against the router at each step.
function replay(
steps: ReadonlyArray]>,
@@ -315,6 +315,30 @@ describe("collapsed split Back", () => {
).toBeNull();
});
+ it("forgets the leaving detail when a full-screen presentation covers it", () => {
+ const state = history([home, thread]);
+ const leavingAfter = (steps: ReadonlyArray) =>
+ steps.reduce(
+ (column, [type, key]) =>
+ collapsedSplitTransition(column, { type, key }, state, home.key).column,
+ { visible: "secondary", leaving: null },
+ ).leaving;
+ expect(
+ leavingAfter([
+ ["willDisappear", thread.key],
+ ["didDisappear", thread.key],
+ ]),
+ ).toBeNull();
+ // Native Back reveals the list before the detail finishes disappearing.
+ expect(
+ leavingAfter([
+ ["willDisappear", thread.key],
+ ["willAppear", home.key],
+ ["didDisappear", thread.key],
+ ]),
+ ).toBe(thread.key);
+ });
+
it("does not mistake JS navigation or a cold link for native Back", () => {
const pushed = history([home, thread, files]);
expect(
diff --git a/apps/mobile/src/native/workspace-stack-projection.ts b/apps/mobile/src/native/workspace-stack-projection.ts
index 281887a391056..73f15add05671 100644
--- a/apps/mobile/src/native/workspace-stack-projection.ts
+++ b/apps/mobile/src/native/workspace-stack-projection.ts
@@ -91,6 +91,8 @@ export function nativeStackPopAction(
export interface CollapsedSplitColumn {
readonly visible: "primary" | "secondary";
readonly leaving: string | null;
+ /** Back reveals another screen; a full-screen presentation covers the detail without one. */
+ readonly revealed?: boolean;
}
/**
@@ -100,7 +102,10 @@ export interface CollapsedSplitColumn {
*/
export function collapsedSplitTransition(
column: CollapsedSplitColumn,
- event: { readonly type: "willAppear" | "didAppear" | "willDisappear"; readonly key: string },
+ event: {
+ readonly type: "willAppear" | "didAppear" | "willDisappear" | "didDisappear";
+ readonly key: string;
+ },
state: Pick,
primaryKey: string,
): {
@@ -113,14 +118,18 @@ export function collapsedSplitTransition(
return {
column:
state.index > 0 && state.routes[state.index]?.key === event.key
- ? { ...column, leaving: event.key }
+ ? { ...column, leaving: event.key, revealed: false }
: column,
pop: null,
};
case "willAppear":
// A cancelled swipe, or an expansion that keeps the detail on screen.
+ if (column.leaving === event.key) return { column: { ...column, leaving: null }, pop: null };
+ return { column: column.leaving ? { ...column, revealed: true } : column, pop: null };
+ case "didDisappear":
return {
- column: column.leaving === event.key ? { ...column, leaving: null } : column,
+ column:
+ column.leaving === event.key && !column.revealed ? { ...column, leaving: null } : column,
pop: null,
};
case "didAppear":
diff --git a/apps/mobile/src/persistence/mobile-preferences.ts b/apps/mobile/src/persistence/mobile-preferences.ts
index f29fbc8c119b4..7a26fc2b8d694 100644
--- a/apps/mobile/src/persistence/mobile-preferences.ts
+++ b/apps/mobile/src/persistence/mobile-preferences.ts
@@ -79,7 +79,14 @@ const WorkspaceSelections = Schema.Struct({
});
export type WorkspaceSelections = typeof WorkspaceSelections.Type;
+const PullRequestActivityVisibility = Schema.Struct({
+ bots: Schema.Boolean,
+ resolved: Schema.Boolean,
+});
+export type PullRequestActivityVisibility = typeof PullRequestActivityVisibility.Type;
+
const isThreadListFilters = Schema.is(ThreadListFilters);
+const isPullRequestActivityVisibility = Schema.is(PullRequestActivityVisibility);
const isWorkspaceSelections = Schema.is(WorkspaceSelections);
const isPullRequestListPreferences = Schema.is(PullRequestListPreferences);
const ThreadProject = Schema.Struct({
@@ -92,6 +99,8 @@ export interface Preferences {
readonly navigationTabOrder?: readonly string[];
readonly hiddenNavigationTabs?: readonly string[];
readonly pullRequestHideTestFiles?: boolean;
+ /** Which hidden-by-default PR activity is shown: bot comments and resolved or dismissed ones. */
+ readonly pullRequestActivityVisibility?: PullRequestActivityVisibility;
readonly pullRequestMergeMethod?: PullRequestMergeMethod;
readonly liveActivitiesEnabled?: boolean;
readonly themeId?: MobileThemeId;
@@ -181,6 +190,7 @@ function sanitizePreferences(parsed: Preferences): Preferences {
navigationTabOrder?: readonly string[];
hiddenNavigationTabs?: readonly string[];
pullRequestHideTestFiles?: boolean;
+ pullRequestActivityVisibility?: PullRequestActivityVisibility;
pullRequestMergeMethod?: PullRequestMergeMethod;
liveActivitiesEnabled?: boolean;
themeId?: MobileThemeId;
@@ -233,6 +243,10 @@ function sanitizePreferences(parsed: Preferences): Preferences {
preferences.pullRequestHideTestFiles = parsed.pullRequestHideTestFiles;
}
+ if (isPullRequestActivityVisibility(parsed.pullRequestActivityVisibility)) {
+ preferences.pullRequestActivityVisibility = parsed.pullRequestActivityVisibility;
+ }
+
if (isPullRequestMergeMethod(parsed.pullRequestMergeMethod)) {
preferences.pullRequestMergeMethod = parsed.pullRequestMergeMethod;
}
diff --git a/apps/mobile/src/state/entities.ts b/apps/mobile/src/state/entities.ts
index c9d1834a78bdb..16bfe0be755ab 100644
--- a/apps/mobile/src/state/entities.ts
+++ b/apps/mobile/src/state/entities.ts
@@ -200,6 +200,11 @@ export function useVisibleThreadShells(): ReadonlyArray
return useAtomValue(environmentThreadShells.visibleThreadShellsAtom);
}
+/** Tasks linked environments run for a listed thread, by thread key; lists show them under it. */
+export function useDelegatedUnderParent(): ReadonlySet {
+ return useAtomValue(environmentThreadShells.delegatedUnderParentAtom);
+}
+
export function useNavigationThreadShells(): ReadonlyArray {
return useAtomValue(environmentThreadShells.navigationThreadShellsAtom);
}
diff --git a/apps/mobile/src/state/pull-requests.ts b/apps/mobile/src/state/pull-requests.ts
index 8ca65760e5913..cb8606b96b5f9 100644
--- a/apps/mobile/src/state/pull-requests.ts
+++ b/apps/mobile/src/state/pull-requests.ts
@@ -1,7 +1,9 @@
import {
createPullRequestEnvironmentAtoms,
+ editHeldPullRequestListEntries,
createPullRequestStackAtomFamily,
patchPullRequestListEntries,
+ pullRequestPendingEditsAtom,
} from "@t3tools/client-runtime/state/pull-requests";
import type { EnvironmentId, PullRequestListInput, PullRequestRef } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
@@ -66,11 +68,30 @@ export const composerPullRequests = createPullRequestEnvironmentAtoms(connection
pages.entries,
target.input,
reply,
+ registry.get(pullRequestPendingEditsAtom(target.environmentId)),
);
return entries === "refresh" || entries === pages.entries ? pages : { ...pages, entries };
});
}
}),
+ acceptedEdit: (target, edit, registry) =>
+ Effect.sync(() => {
+ for (const atom of registry.getNodes().keys()) {
+ const listing =
+ typeof atom === "string" ? undefined : pullRequestListPagesTargets.get(atom);
+ if (listing === undefined || listing[0] !== target.environmentId) continue;
+ registry.update(atom as Atom.Writable, (pages) => {
+ if (pages === null) return pages;
+ const entries = editHeldPullRequestListEntries(
+ listing[1],
+ pages.entries,
+ () => [edit],
+ registry.get(pullRequestPendingEditsAtom(target.environmentId)),
+ );
+ return entries === pages.entries ? pages : { ...pages, entries };
+ });
+ }
+ }),
// A new head can change which files GitHub still counts as viewed, so the viewed-files read is
// refreshed where the new head lands. The detail atom still holds the previous answer here.
detail: (target, value, registry) =>
diff --git a/apps/mobile/src/state/queries.debounce.test.tsx b/apps/mobile/src/state/queries.debounce.test.tsx
index e2eccb4d4125c..8e67b617b6ee2 100644
--- a/apps/mobile/src/state/queries.debounce.test.tsx
+++ b/apps/mobile/src/state/queries.debounce.test.tsx
@@ -8,7 +8,8 @@ import { expect, it, vi } from "vite-plus/test";
const mocks = vi.hoisted(() => ({
sessionAtom: {},
- searchEntries: vi.fn(() => null),
+ searchEntriesAtom: {},
+ searchEntries: vi.fn((): unknown => mocks.searchEntriesAtom),
listRefs: vi.fn(),
refresh: vi.fn(),
}));
@@ -35,7 +36,9 @@ vi.mock("./query", () => ({
data:
atom === mocks.sessionAtom
? { authenticated: true, scopes: [AuthFilesystemReadScope] }
- : null,
+ : atom === mocks.searchEntriesAtom
+ ? { entries: [{ path: "src/only-in-original.ts", kind: "file" }] }
+ : null,
error: null,
isPending: false,
refresh: () => {},
@@ -53,12 +56,16 @@ function setup() {
vi.useFakeTimers();
mocks.searchEntries.mockClear();
const root = createRoot(document.createElement("div"));
+ let latest: ReturnType | null = null;
function Probe({ target }: { readonly target: ComposerPathSearchTarget }) {
- useComposerPathSearch(target);
+ latest = useComposerPathSearch(target);
return null;
}
return {
+ get result() {
+ return latest;
+ },
render(target: ComposerPathSearchTarget) {
act(() => root.render());
},
@@ -128,6 +135,21 @@ it.each([
});
});
+it.each([
+ { field: "environment", changed: { ...target, environmentId: EnvironmentId.make("other") } },
+ { field: "project directory", changed: { ...target, cwd: "/other" } },
+])("reports settled results as pending when the $field changes", ({ changed }) => {
+ using harness = setup();
+ harness.render(target);
+ act(() => vi.advanceTimersByTime(200));
+ expect(harness.result?.isPending).toBe(false);
+ expect(harness.result?.entries).toHaveLength(1);
+
+ harness.render(changed);
+ expect(harness.result?.isPending).toBe(true);
+ expect(harness.result?.entries).toEqual([]);
+});
+
it("keeps compiled branch results stable and resets pagination for a new target or refresh", () => {
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
const registry = AtomRegistry.make();
diff --git a/apps/mobile/src/state/queries.test.ts b/apps/mobile/src/state/queries.test.ts
deleted file mode 100644
index dba11b2e56ea7..0000000000000
--- a/apps/mobile/src/state/queries.test.ts
+++ /dev/null
@@ -1,29 +0,0 @@
-import { threadPullRequestKeyOf } from "@t3tools/client-runtime/thread-pull-requests";
-import { filterComposerPullRequestMatches } from "@t3tools/shared/composerPullRequestMatches";
-import { expect, it } from "@effect/vitest";
-
-it("keeps an older exact PR in the mobile menu ahead of twenty newer substring matches", () => {
- const exact = {
- host: "github.com",
- number: 42,
- projectId: "project",
- repository: "example/repo",
- updatedAt: "2025-01-01",
- };
- const recent = Array.from({ length: 25 }, (_, index) => ({
- ...exact,
- number: 4200 + index,
- updatedAt: "2026-01-01",
- }));
- const matches = filterComposerPullRequestMatches({
- keyOf: threadPullRequestKeyOf,
- entries: [exact, ...recent, exact],
- projectId: exact.projectId,
- repository: exact.repository,
- query: "42",
- limit: 20,
- });
- expect(matches).toHaveLength(20);
- expect(matches[0]).toEqual(exact);
- expect(matches.filter((entry) => entry.number === 42)).toHaveLength(1);
-});
diff --git a/apps/mobile/src/state/queries.ts b/apps/mobile/src/state/queries.ts
index 0fdd2bda84342..3514dc0781b41 100644
--- a/apps/mobile/src/state/queries.ts
+++ b/apps/mobile/src/state/queries.ts
@@ -446,9 +446,13 @@ export function useComposerPathSearch(target: ComposerPathSearchTarget) {
canReadFiles && searchTarget !== null ? projectEnvironment.searchEntries(searchTarget) : null,
);
const hasTarget = searchTarget !== null;
+ const isSameCheckout =
+ normalizedTarget.environmentId === debouncedTarget.environmentId &&
+ normalizedTarget.cwd === debouncedTarget.cwd;
return {
- entries: result.data?.entries ?? [],
+ // Entries from another checkout must not be offered while the new one is debounced.
+ entries: isSameCheckout ? (result.data?.entries ?? []) : [],
error:
!hasTarget || fileAccess.isPending
? null
@@ -456,6 +460,7 @@ export function useComposerPathSearch(target: ComposerPathSearchTarget) {
? result.error
: (fileAccess.error ?? "This connection cannot search host files."),
isPending:
+ !isSameCheckout ||
normalizedTarget.query !== debouncedTarget.query ||
(hasTarget && (fileAccess.isPending || result.isPending)),
refresh: result.refresh,
diff --git a/apps/mobile/src/state/recover-failed-thread-draft.ts b/apps/mobile/src/state/recover-failed-thread-draft.ts
index 5512dccbeb266..25573ee3363c7 100644
--- a/apps/mobile/src/state/recover-failed-thread-draft.ts
+++ b/apps/mobile/src/state/recover-failed-thread-draft.ts
@@ -26,7 +26,7 @@ export async function recoverFailedThreadDraft(message: QueuedThreadMessage): Pr
appendComposerDraftAttachments(
targetKey,
source.attachments.filter((attachment) => !existingIds.has(attachment.id)),
- { allowOverflow: true },
+ { restore: true },
);
// Recovery may exceed caps; preserve every file and leave trimming to the editor.
await flushComposerDrafts();
diff --git a/apps/mobile/src/state/session.ts b/apps/mobile/src/state/session.ts
index 5d6a441e9b9e4..74876954b2716 100644
--- a/apps/mobile/src/state/session.ts
+++ b/apps/mobile/src/state/session.ts
@@ -1,5 +1,8 @@
import { useAtomValue } from "@effect/atom-react";
-import { createEnvironmentSessionAtoms } from "@t3tools/client-runtime/state/session";
+import {
+ createEnvironmentSessionAtoms,
+ sessionDeniesScope,
+} from "@t3tools/client-runtime/state/session";
import {
type AuthEnvironmentScope,
type AuthSessionState,
@@ -25,16 +28,30 @@ export function sessionHasScope(
return result._tag !== "Failure" && session !== null && sessionGrantsScope(session, scope);
}
+function sessionStateAtomFor(environmentId: EnvironmentId | null) {
+ return environmentId === null
+ ? EMPTY_SESSION_STATE_ATOM
+ : environmentSession.sessionStateAtom(environmentId);
+}
+
+// Both hooks select a boolean: every revalidation emits a new result, and most consumers are
+// list rows.
export function useEnvironmentScope(
environmentId: EnvironmentId | null,
scope: AuthEnvironmentScope,
): boolean {
- // Select the grant: every revalidation emits a new result, and most consumers are list rows.
- return useAtomValue(
- environmentId === null
- ? EMPTY_SESSION_STATE_ATOM
- : environmentSession.sessionStateAtom(environmentId),
- (result) => sessionHasScope(result, scope),
+ return useAtomValue(sessionStateAtomFor(environmentId), (result) =>
+ sessionHasScope(result, scope),
+ );
+}
+
+/** Unlike `!useEnvironmentScope`, stays false until the host has answered without the scope. */
+export function useEnvironmentScopeDenied(
+ environmentId: EnvironmentId | null,
+ scope: AuthEnvironmentScope,
+): boolean {
+ return useAtomValue(sessionStateAtomFor(environmentId), (result) =>
+ sessionDeniesScope(result, scope),
);
}
diff --git a/apps/mobile/src/state/thread-pr-presentation.ts b/apps/mobile/src/state/thread-pr-presentation.ts
index a44f410b54ca3..a57d04fb24918 100644
--- a/apps/mobile/src/state/thread-pr-presentation.ts
+++ b/apps/mobile/src/state/thread-pr-presentation.ts
@@ -36,7 +36,7 @@ export interface ThreadPrPresentation {
const PR_STATE_TEXT_CLASS: Record = {
open: "text-adaptive-emerald-600-400",
merged: "text-adaptive-violet-600-400",
- closed: "text-foreground-muted",
+ closed: "text-adaptive-rose-600-400",
};
export function presentThreadPr(
@@ -101,12 +101,7 @@ export function presentThreadLinkedPullRequests(
: linkedCount !== null
? `${linkedCount} linked ${changeRequest.plural}, overall ${badge.state}`
: `#${link.number} ${changeRequest.singular} ${state === null ? "status pending" : isDraft ? "draft" : state}`,
- textClassName:
- state === null || isDraft
- ? "text-foreground-muted"
- : isMultiple && state === "closed"
- ? "text-adaptive-rose-600-400"
- : PR_STATE_TEXT_CLASS[state],
+ textClassName: state === null || isDraft ? "text-foreground-muted" : PR_STATE_TEXT_CLASS[state],
};
}
diff --git a/apps/mobile/src/state/threadOutboxDelivery.ts b/apps/mobile/src/state/threadOutboxDelivery.ts
index 3edb50351da57..250b4984e8d67 100644
--- a/apps/mobile/src/state/threadOutboxDelivery.ts
+++ b/apps/mobile/src/state/threadOutboxDelivery.ts
@@ -375,7 +375,7 @@ export async function recoverEditedCreationAfterDelivery(
appendComposerDraftAttachments(
draftKey,
kept.attachments.filter((attachment) => !existingAttachmentIds.has(attachment.id)),
- { allowOverflow: true },
+ { restore: true },
);
updateComposerDraftSettings(draftKey, {
...(kept.modelSelection !== undefined ? { modelSelection: kept.modelSelection } : {}),
diff --git a/apps/mobile/src/state/usage.ts b/apps/mobile/src/state/usage.ts
index 1f67db82aada7..dae7932d0cf60 100644
--- a/apps/mobile/src/state/usage.ts
+++ b/apps/mobile/src/state/usage.ts
@@ -74,6 +74,19 @@ const usageByWindowAtom = Atom.family((windowKey: string) =>
}).pipe(Atom.withLabel(`mobile-usage:window:${windowKey}`)),
);
+/** Every environment usage can come from, without asking any of them for usage. */
+const usageEnvironmentsAtom = Atom.make((get): readonly EnvironmentUsageStatus[] =>
+ [...get(environmentPresentations.presentationsAtom)].map(([environmentId, presentation]) => ({
+ environmentId,
+ label: presentation.entry.target.label,
+ isPending: true,
+ isConnected: presentation.connection.phase === "connected",
+ canReadDiagnostics: false,
+ error: null,
+ summary: null,
+ })),
+).pipe(Atom.withLabel("mobile-usage:environments"));
+
export interface UsageView {
readonly merged: MergedUsage;
readonly environments: readonly EnvironmentUsageStatus[];
@@ -88,6 +101,8 @@ export interface UsageView {
export function useUsage(
input: UsageSummaryInput,
selectedEnvironmentIds: ReadonlySet | null = null,
+ /** Off, it lists the environments without loading their usage. */
+ load = true,
): UsageView {
const windowKey = useMemo(
() =>
@@ -108,8 +123,7 @@ export function useUsage(
input.untilTime,
],
);
- const atom = usageByWindowAtom(windowKey);
- const environments = useAtomValue(atom);
+ const environments = useAtomValue(load ? usageByWindowAtom(windowKey) : usageEnvironmentsAtom);
const selectedEnvironments = useMemo(
() =>
selectedEnvironmentIds === null
diff --git a/apps/mobile/src/state/use-composer-attachment-actions.ts b/apps/mobile/src/state/use-composer-attachment-actions.ts
index eeb8742010858..2352f3f7848eb 100644
--- a/apps/mobile/src/state/use-composer-attachment-actions.ts
+++ b/apps/mobile/src/state/use-composer-attachment-actions.ts
@@ -101,10 +101,7 @@ export function useComposerAttachmentActions(props: {
const insertion = captureComposerDraftInsertion(key);
await withDraftOperation(key, async (signal) => {
try {
- const result = await convertPastedImagesToAttachments({
- uris,
- existingCount: countComposerDraftAttachmentsAfterSelection(key, insertion),
- });
+ const result = await convertPastedImagesToAttachments({ uris });
report(
"Could not paste images",
result.error,
diff --git a/apps/mobile/src/state/use-composer-drafts.test.ts b/apps/mobile/src/state/use-composer-drafts.test.ts
index 1d50352090673..a85e9f877dbfc 100644
--- a/apps/mobile/src/state/use-composer-drafts.test.ts
+++ b/apps/mobile/src/state/use-composer-drafts.test.ts
@@ -28,6 +28,9 @@ import {
} from "@t3tools/contracts";
import { onTestFinished, vi } from "vite-plus/test";
+import { buildIncomingShareDraft } from "../features/sharing/incoming-share-model";
+import { composerContextSendBlockReason } from "../lib/composerContext";
+
const composerDraftFileMocks = vi.hoisted(() => {
let document = JSON.stringify({ schemaVersion: 1, drafts: {} });
let readError: Error | null = null;
@@ -458,7 +461,7 @@ describe("mobile composer drafts", () => {
const restored = history.restore(text, getComposerDraftSnapshot(key));
setComposerDraftText(key, text);
setComposerDraftContext(key, restored.context);
- appendComposerDraftAttachments(key, restored.attachments, { allowOverflow: true });
+ appendComposerDraftAttachments(key, restored.attachments, { restore: true });
};
try {
changeText("");
@@ -802,6 +805,32 @@ describe("mobile composer drafts", () => {
expect(getComposerDraftSnapshot(key).text).toBe("keep newly typed text pasted");
});
+ it("keeps a pending paste before text typed at its caret, and the caret after that text", async () => {
+ const key = "environment-1:typing-at-paste-point";
+ const image = {
+ id: "image",
+ type: "file" as const,
+ name: "picture.png",
+ mimeType: "text/plain",
+ sizeBytes: 4,
+ fileUri: "file:///picture.png",
+ };
+ setComposerDraftText(key, "Before ");
+ const insertion = captureComposerDraftInsertion(key, { start: 7, end: 7 });
+ const write = Promise.withResolvers();
+ const pending = write.promise.then(() =>
+ appendComposerDraftAttachments(key, [image], { appendReference: true, insertion }),
+ );
+ setComposerDraftText(key, "Before yaz");
+ rememberComposerDraftSelection(key, "Before yaz", { start: 10, end: 10 });
+ write.resolve();
+ expect(await pending).toBe(0);
+ const link = "[picture.png](t3-context://v1/file/image)";
+ expect(getComposerDraftSnapshot(key).text).toBe(`Before ${link} yaz`);
+ const caret = `Before ${link} yaz`.length;
+ expect(captureComposerDraftInsertion(key)).toMatchObject({ start: caret, end: caret });
+ });
+
it.each(["attachment", "context", "imported context"])(
"releases a selected file when replaced by %s",
async (kind) => {
@@ -1054,12 +1083,65 @@ describe("mobile composer drafts", () => {
const overflowRejected = appendComposerDraftAttachments(
draftKey,
[makeAttachment("restored-1")],
- { allowOverflow: true },
+ { restore: true },
);
expect(overflowRejected).toBe(0);
expect(appAtomRegistry.get(composerDraftsAtom)[draftKey]?.attachments).toHaveLength(101);
});
+ it("drops duplicate attachments, releases their files, and keeps them on restore", async () => {
+ const outboxLoad = vi.spyOn(threadOutboxManager, "load").mockResolvedValue(true);
+ onTestFinished(() => outboxLoad.mockRestore());
+ const cleanup = Promise.withResolvers();
+ composerAttachmentCleanupMocks.remove.mockImplementationOnce(async () => {
+ cleanup.resolve();
+ });
+ const makeVideo = (id: string) => ({
+ id,
+ type: "file" as const,
+ name: "clip.mov",
+ mimeType: "video/quicktime",
+ sizeBytes: 42,
+ fileUri: `file:///documents/t3-composer-attachments/${id}.mov`,
+ });
+ const draftKey = "new-task:environment-1:project-duplicates";
+ appAtomRegistry.set(composerDraftsAtom, {
+ [draftKey]: { text: "", attachments: [makeVideo("held")] },
+ });
+
+ expect(
+ appendComposerDraftAttachments(draftKey, [makeVideo("again"), makeVideo("again-2")]),
+ ).toBe(0);
+ expect(appAtomRegistry.get(composerDraftsAtom)[draftKey]?.attachments).toEqual([
+ makeVideo("held"),
+ ]);
+ await cleanup.promise;
+ expect(composerAttachmentCleanupMocks.remove).toHaveBeenCalledWith(makeVideo("again").fileUri);
+
+ appendComposerDraftAttachments(draftKey, [makeVideo("restored")], { restore: true });
+ expect(appAtomRegistry.get(composerDraftsAtom)[draftKey]?.attachments).toHaveLength(2);
+
+ // Every native paste is named pasted-image.png, so only the bytes tell two pastes apart.
+ const makePaste = (id: string, base64: string) => ({
+ id,
+ type: "image" as const,
+ name: "pasted-image.png",
+ mimeType: "image/png",
+ sizeBytes: 3,
+ dataUrl: `data:image/png;base64,${base64}`,
+ previewUri: `data:image/png;base64,${base64}`,
+ });
+ const pasteKey = "new-task:environment-1:project-pastes";
+ appendComposerDraftAttachments(pasteKey, [makePaste("red", "AQID")]);
+ appendComposerDraftAttachments(pasteKey, [
+ makePaste("blue", "BAUG"),
+ makePaste("red-2", "AQID"),
+ ]);
+ expect(
+ appAtomRegistry.get(composerDraftsAtom)[pasteKey]?.attachments.map(({ id }) => id),
+ ).toEqual(["red", "blue"]);
+ });
+
it("keeps shared attachment files until every draft releases them", async () => {
const outboxLoad = vi.spyOn(threadOutboxManager, "load").mockResolvedValue(true);
onTestFinished(() => outboxLoad.mockRestore());
@@ -2228,7 +2310,7 @@ describe("mobile composer drafts", () => {
it("merges shared content into a project draft without duplicating retries", () => {
const draftKey = "new-task:environment-1:project-1";
const sharedAttachment = {
- id: "share-1:image:0",
+ id: "share-1-image-0",
type: "image" as const,
name: "Screenshot.png",
mimeType: "image/png",
@@ -2263,7 +2345,7 @@ describe("mobile composer drafts", () => {
it("shows a shared non-image file as a composer chip", () => {
const draftKey = "new-task:environment-1:project-1";
const sharedFile = {
- id: "share-1:file:0",
+ id: "share-1-file-0",
type: "file" as const,
name: "backup.json",
mimeType: "application/json",
@@ -2298,6 +2380,37 @@ describe("mobile composer drafts", () => {
expect(mergeComposerDraftContentState(once, draftKey, recovered)).toBe(once);
});
+ it("lets a shared file through the send check", async () => {
+ const { attachments } = await buildIncomingShareDraft({
+ id: "share-1",
+ createdAt: "2026-07-15T10:00:00.000Z",
+ payloads: [
+ {
+ shareType: "file",
+ value: "file:///shared/report.xlsx",
+ mimeType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
+ originalName: "report.xlsx",
+ },
+ ],
+ resolvedPayloads: [],
+ fileReader: {
+ readBase64: async () => "",
+ readSize: async () => 42,
+ removeOwnedFile: async () => {},
+ },
+ });
+ const draftKey = "new-task:environment-1:project-1";
+
+ const merged = mergeComposerDraftContentState({}, draftKey, {
+ text: "",
+ attachments,
+ sourceShareId: "share-1",
+ })[draftKey]!;
+
+ expect(merged.context?.records).toHaveLength(1);
+ expect(composerContextSendBlockReason(merged.context)).toBeNull();
+ });
+
it("preserves existing images when shared content exceeds the draft attachment limit", () => {
const draftKey = "new-task:environment-1:project-1";
const image = (id: string) => ({
diff --git a/apps/mobile/src/state/use-composer-drafts.ts b/apps/mobile/src/state/use-composer-drafts.ts
index 6e4099e571cc1..2ebfd03e2e13e 100644
--- a/apps/mobile/src/state/use-composer-drafts.ts
+++ b/apps/mobile/src/state/use-composer-drafts.ts
@@ -195,14 +195,54 @@ export function captureComposerDraftInsertion(
};
}
+function mapCapturedRange(
+ captured: ComposerDraftInsertion,
+ text: string,
+): { start: number; end: number } | null {
+ if (captured.text === text) return captured;
+ // A replaced selection is not safe to delete after edits; only a caret follows them.
+ if (captured.start !== captured.end) return null;
+ const previous = captured.text;
+ const shared = Math.min(previous.length, text.length);
+ let prefix = 0;
+ while (prefix < shared && previous[prefix] === text[prefix]) prefix += 1;
+ let suffix = 0;
+ while (
+ suffix < shared - prefix &&
+ previous[previous.length - 1 - suffix] === text[text.length - 1 - suffix]
+ ) {
+ suffix += 1;
+ }
+ // Text typed at the caret lands after it, so the insertion stays before that text.
+ if (captured.start <= prefix) return captured;
+ if (captured.start < previous.length - suffix) return null;
+ const caret = captured.start + text.length - previous.length;
+ return { start: caret, end: caret };
+}
+
+/** Keep a caret after the insertion where it was, or the next keystroke lands before typed text. */
+function caretAfterInsertion(
+ draftKey: string,
+ previousText: string,
+ range: { start: number; end: number },
+ inserted: number,
+): { start: number; end: number } {
+ const caret = readComposerDraftSelection(draftKey, previousText);
+ if (caret && caret.start > range.end) {
+ const delta = range.start + inserted - range.end;
+ return { start: caret.start + delta, end: caret.end + delta };
+ }
+ return { start: range.start + inserted, end: range.start + inserted };
+}
+
function contextInsertionRange(
draftKey: string,
draft: ComposerDraft,
target?: ComposerDraftInsertion,
) {
const captured = target ?? appAtomRegistry.get(composerDraftSelectionAtom(draftKey));
- // Append after text edits during writes; caret-only moves preserve the captured insertion range.
- const selection = captured?.text === draft.text ? captured : null;
+ // Follow edits made during writes; append when an edit touched the captured range.
+ const selection = captured ? mapCapturedRange(captured, draft.text) : null;
const start = Math.max(0, Math.min(selection?.start ?? draft.text.length, draft.text.length));
return { start, end: Math.max(start, Math.min(selection?.end ?? start, draft.text.length)) };
}
@@ -373,10 +413,11 @@ function draftWithInsertedContext(
for (const record of content.context.records) records.set(record.contextId, record);
const context = referencedComposerContext(text, { version: 1, records: [...records.values()] });
if ((context?.records.length ?? 0) > COMPOSER_CONTEXT_MAX_RECORDS) return null;
- rememberComposerDraftSelection(draftKey, text, {
- start: start + insertion.length,
- end: start + insertion.length,
- });
+ rememberComposerDraftSelection(
+ draftKey,
+ text,
+ caretAfterInsertion(draftKey, draft.text, { start, end }, insertion.length),
+ );
return withReferencedContextFiles(draft, text, context);
}
@@ -1357,11 +1398,9 @@ export function insertComposerDraftText(
const draft = getComposerDraftSnapshot(draftKey);
const { start, end } = contextInsertionRange(draftKey, draft, target);
const text = draft.text.slice(0, start) + value + draft.text.slice(end);
+ const caret = caretAfterInsertion(draftKey, draft.text, { start, end }, value.length);
setComposerDraftText(draftKey, text);
- rememberComposerDraftSelection(draftKey, text, {
- start: start + value.length,
- end: start + value.length,
- });
+ rememberComposerDraftSelection(draftKey, text, caret);
}
export function appendComposerDraftText(draftKey: string, value: string): void {
@@ -1377,28 +1416,51 @@ export function appendComposerDraftText(draftKey: string, value: string): void {
});
}
-/** Restore with allowOverflow to preserve every attachment after failed sends. */
+// Pasted images all share one name, so an image's inline bytes decide whether it is a repeat.
+function isSameAttachment(a: DraftComposerAttachment, b: DraftComposerAttachment): boolean {
+ return (
+ a.mimeType === b.mimeType &&
+ a.sizeBytes === b.sizeBytes &&
+ a.name === b.name &&
+ (a.type !== "image" || b.type !== "image" || a.dataUrl === b.dataUrl)
+ );
+}
+
+/**
+ * Restore puts back attachments after failed sends, so it skips the duplicate check and the caps.
+ * Returns how many attachments the caps rejected.
+ */
export function appendComposerDraftAttachments(
draftKey: string,
- attachments: ReadonlyArray,
+ incoming: ReadonlyArray,
options?: {
- readonly allowOverflow?: boolean;
+ readonly restore?: boolean;
readonly appendReference?: boolean;
readonly insertion?: ComposerDraftInsertion;
readonly maxAttachments?: number;
},
): number {
- if (attachments.length === 0) {
+ if (incoming.length === 0) {
return 0;
}
let rejected: ReadonlyArray = [];
let removed: ReadonlyArray = [];
+ let duplicates: ReadonlyArray = [];
updateComposerDrafts((current) => {
const existing = normalizeDraft(current[draftKey]);
const retained = options?.appendReference
? draftWithoutInsertionSelection(draftKey, existing, options.insertion)
: existing;
- const remaining = options?.allowOverflow
+ const seen = [...retained.attachments];
+ const attachments = options?.restore
+ ? incoming
+ : incoming.filter((attachment) => {
+ if (seen.some((other) => isSameAttachment(other, attachment))) return false;
+ seen.push(attachment);
+ return true;
+ });
+ duplicates = incoming.filter((attachment) => !attachments.includes(attachment));
+ const remaining = options?.restore
? attachments.length
: Math.max(
0,
@@ -1441,7 +1503,7 @@ export function appendComposerDraftAttachments(
[draftKey]: draft,
};
});
- scheduleUnusedComposerAttachmentCleanup([...rejected, ...removed]);
+ scheduleUnusedComposerAttachmentCleanup([...rejected, ...removed, ...duplicates]);
return rejected.length;
}
diff --git a/apps/mobile/src/state/use-remote-environment-registry.ts b/apps/mobile/src/state/use-remote-environment-registry.ts
index a1488220d6952..0b4163aafbd95 100644
--- a/apps/mobile/src/state/use-remote-environment-registry.ts
+++ b/apps/mobile/src/state/use-remote-environment-registry.ts
@@ -9,6 +9,7 @@ import { runAtomCommand } from "@t3tools/client-runtime/state/runtime";
import { hasCloudPublicConfig } from "../features/cloud/publicConfig";
import { useConnectionController } from "../features/connection/useConnectionController";
+import { useRetryEnvironment } from "../features/connection/useRetryEnvironment";
import { environmentPresentations } from "./presentation";
import { useWorkspaceConnectionState, useWorkspaceEnvironments } from "./workspace";
import type { SavedRemoteConnection } from "../lib/connection";
@@ -166,8 +167,7 @@ export function useRemoteConnections() {
const onConnectPress = (pairingUrl?: string, expectedEnvironmentId?: EnvironmentId) =>
pairEnvironment(pairingUrl ?? connectionPairingUrl, expectedEnvironmentId);
- const onReconnectEnvironment = (environmentId: EnvironmentId) =>
- controller.retryEnvironment(environmentId);
+ const onReconnectEnvironment = useRetryEnvironment();
const onSetEnvironmentEnabled = (environmentId: EnvironmentId, enabled: boolean) =>
controller.setEnvironmentEnabled(environmentId, enabled);
const onUpdateEnvironment = (
diff --git a/apps/mobile/src/state/use-thread-composer-state.ts b/apps/mobile/src/state/use-thread-composer-state.ts
index a3a191d54cbd1..5796535029582 100644
--- a/apps/mobile/src/state/use-thread-composer-state.ts
+++ b/apps/mobile/src/state/use-thread-composer-state.ts
@@ -495,6 +495,14 @@ export function useThreadComposerState(input: {
);
return;
}
+ // A queued message stays in its thread, so saving `/side` would send it to main.
+ if (parseSideChatCommand(text)) {
+ Dialog.alert(
+ "Queued message not updated",
+ "A queued message can't move to a side chat. Remove /side or /btw to save it.",
+ );
+ return;
+ }
const finishSave = startQueuedRunEditSave(threadKey);
if (finishSave === null) return;
savingQueuedEditRef.current = true;
@@ -832,7 +840,7 @@ export function useThreadComposerState(input: {
context: draft.context,
attachments: [],
});
- appendComposerDraftAttachments(threadKey, attachments, { allowOverflow: true });
+ appendComposerDraftAttachments(threadKey, attachments, { restore: true });
if (freshContext) setFreshSessionPending(threadKey, true);
setThreadComposerError(
threadKey,
diff --git a/apps/mobile/vite.config.ts b/apps/mobile/vite.config.ts
index 2b688fee30ad2..e9f1260b514c3 100644
--- a/apps/mobile/vite.config.ts
+++ b/apps/mobile/vite.config.ts
@@ -26,6 +26,7 @@ const reactTests = [
"src/features/files/ZipArchiveView.test.tsx",
"src/features/pull-requests/guide/useReviewGuide.test.tsx",
"src/features/settings/SettingsServerControlsRouteScreen.test.tsx",
+ "src/features/settings/SettingsScheduledTasksRouteScreen.test.tsx",
"src/features/settings/components/BranchNamingSettings.test.tsx",
"src/features/settings/components/SettingsDragHandle.test.tsx",
"src/features/threads/ThreadMarkdownImage.test.tsx",
@@ -36,16 +37,20 @@ const reactTests = [
"src/native/NativeHeaderToolbar.test.tsx",
"src/components/ComposerEditor.ios.test.tsx",
"src/native/V5StackHeader.ios.test.tsx",
+ "src/native/createV5StackNavigator.ios.test.tsx",
"src/native/useRetryingImageSource.test.tsx",
"src/state/queries.debounce.test.tsx",
"src/state/use-selected-thread-git-state.test.tsx",
"src/features/terminal/useTerminalExitNavigation.test.tsx",
"src/features/threads/use-thread-list-now.test.tsx",
+ "src/features/threads/use-composer-command-menu.select.test.tsx",
"src/features/threads/useThreadListV2.test.tsx",
"src/features/home/home-list-options.test.tsx",
"src/features/home/home-route-visibility.test.tsx",
"src/features/layout/workspace/useSearchScrollRestoration.test.tsx",
+ "src/features/connection/useRetryEnvironment.test.tsx",
"src/features/connection/ConnectionsNewRouteScreen.test.tsx",
+ "src/features/connection/LinkedEnvironmentsSection.test.tsx",
"src/features/devices/device-stream.browser.test.ts",
"src/features/keyboard/keyboardControllerState.test.tsx",
];
diff --git a/apps/server/graphql.config.ts b/apps/server/graphql.config.ts
index f042d039410db..cc659592f01a2 100644
--- a/apps/server/graphql.config.ts
+++ b/apps/server/graphql.config.ts
@@ -1,13 +1,9 @@
import { defineConfig } from "@effect/graphql-generator/Config";
// `schema/expo.graphql` is api.expo.dev's schema, read by introspection
-// (`vp run generate:expo-schema`). The EAS Simulator operations are the ones
+// (`vp run generate:expo-schema`). The Expo Simulators operations are the ones
// eas-cli's `simulator:*` commands send; Expo does not document them.
export default defineConfig({
schema: "./schema/expo.graphql",
documents: ["src/device/**/*.graphql"],
- scalars: {
- // Feature gates arrive as an object of gate name to boolean.
- JSONObject: "effect/Schema#Json",
- },
});
diff --git a/apps/server/package.json b/apps/server/package.json
index d16b8d4e19f2f..9e05831bee12e 100644
--- a/apps/server/package.json
+++ b/apps/server/package.json
@@ -37,7 +37,7 @@
},
"dependencies": {
"@anthropic-ai/claude-agent-sdk": "^0.3.321",
- "@cursor/sdk": "1.2.0",
+ "@cursor/sdk": "1.3.1",
"@effect/platform-node": "catalog:",
"@effect/platform-node-shared": "catalog:",
"@ff-labs/fff-node": "0.11.0",
diff --git a/apps/server/schema/expo.graphql.ts b/apps/server/schema/expo.graphql.ts
index 4391c22403ec5..de836ebcb615a 100644
--- a/apps/server/schema/expo.graphql.ts
+++ b/apps/server/schema/expo.graphql.ts
@@ -5,9 +5,6 @@ export const Int = Schema.Number.check(Schema.isInt32())
export const ID = Schema.String
-/** The `JSONObject` scalar type represents JSON objects as specified by [ECMA-404](http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf). */
-export const JSONObject = Schema.Json
-
/**
* - `ANDROID`
* - `IOS`
diff --git a/apps/server/scripts/acp-mock-agent.ts b/apps/server/scripts/acp-mock-agent.ts
index a97aab9cdf2b1..a65f4d5473c71 100644
--- a/apps/server/scripts/acp-mock-agent.ts
+++ b/apps/server/scripts/acp-mock-agent.ts
@@ -70,6 +70,9 @@ const failLoadSession = process.env.T3_ACP_FAIL_LOAD_SESSION === "1";
const failLoadSessionAfterConfigReplay =
process.env.T3_ACP_FAIL_LOAD_SESSION_AFTER_CONFIG_REPLAY === "1";
const emitLoadReplay = process.env.T3_ACP_EMIT_LOAD_REPLAY === "1";
+const loadReplyDelayMs = Number(process.env.T3_ACP_LOAD_REPLY_DELAY_MS ?? "0");
+const loadNeverReplies = process.env.T3_ACP_LOAD_NEVER_REPLIES === "1";
+const rejectPromptUntilLoaded = process.env.T3_ACP_REJECT_PROMPT_UNTIL_LOADED === "1";
const failPrompt = process.env.T3_ACP_FAIL_PROMPT === "1";
// JSON for the `data` of an "Internal error" response to `session/new`, as
// Antigravity sends when its runtime cannot reach its local harness.
@@ -122,6 +125,7 @@ let currentAgent = "";
let authenticated = !requiresAuthentication;
let promptCount = 0;
const cancelledSessions = new Set();
+const sessionsLoading = new Set();
let configuredProvider: AcpSchema.ProviderCurrentConfig | null = null;
function promptIdFromRequestMeta(
@@ -687,6 +691,7 @@ const program = Effect.gen(function* () {
yield* agent.handleLoadSession((request) =>
Effect.gen(function* () {
const requestedSessionId = String(request.sessionId ?? sessionId);
+ sessionsLoading.add(requestedSessionId);
if (loadedCommandNames !== undefined) {
yield* agent.client.sessionUpdate({
sessionId: requestedSessionId,
@@ -729,6 +734,13 @@ const program = Effect.gen(function* () {
content: { type: "text", text: "replay" },
},
});
+ if (loadNeverReplies) {
+ return yield* Effect.never;
+ }
+ if (Number.isFinite(loadReplyDelayMs) && loadReplyDelayMs > 0) {
+ yield* Effect.sleep(`${loadReplyDelayMs} millis`);
+ }
+ sessionsLoading.delete(requestedSessionId);
return {
configOptions: configOptions(),
};
@@ -868,6 +880,12 @@ const program = Effect.gen(function* () {
yield* agent.handlePrompt((request) =>
Effect.gen(function* () {
const requestedSessionId = String(request.sessionId ?? sessionId);
+ if (rejectPromptUntilLoaded && sessionsLoading.has(requestedSessionId)) {
+ return yield* new AcpError.AcpRequestError({
+ code: -32002,
+ errorMessage: `Resource not found: ${requestedSessionId}`,
+ });
+ }
beginAcpMockPrompt(cancelledSessions, requestedSessionId);
promptCount += 1;
if (idleError === "grok-background" && promptCount === 1) {
@@ -1396,10 +1414,6 @@ const program = Effect.gen(function* () {
}
}
- if (failPrompt || promptCount === failPromptOrdinal) {
- return yield* AcpError.AcpRequestError.internalError("Mock prompt failure");
- }
-
if (emitTrackedToolCallKindThenHang !== undefined) {
yield* agent.client.sessionUpdate({
sessionId: requestedSessionId,
@@ -1412,7 +1426,11 @@ const program = Effect.gen(function* () {
rawInput: { command: "git status" },
},
});
- return yield* Effect.never;
+ if (!failPrompt && promptCount !== failPromptOrdinal) return yield* Effect.never;
+ }
+
+ if (failPrompt || promptCount === failPromptOrdinal) {
+ return yield* AcpError.AcpRequestError.internalError("Mock prompt failure");
}
if (hangPromptForever || (emitEmptySuccessfulBashThenHang && promptCount === 2)) {
diff --git a/apps/server/scripts/dev-replay-agent.ts b/apps/server/scripts/dev-replay-agent.ts
index b6eea893ad6b7..2aa50e353f57a 100644
--- a/apps/server/scripts/dev-replay-agent.ts
+++ b/apps/server/scripts/dev-replay-agent.ts
@@ -64,6 +64,11 @@ export const SCENARIOS = [
name: "Multi turn",
file: `${FIXTURES}/multi_turn/registry_transcript.ndjson`,
},
+ {
+ id: "command-output",
+ name: "Command output",
+ file: "./dev-replay/command_output_transcript.ndjson",
+ },
] as const;
// Session setup and vendor state stay out: they would replace the replay agent's own models.
diff --git a/apps/server/scripts/dev-replay/command_output_transcript.ndjson b/apps/server/scripts/dev-replay/command_output_transcript.ndjson
new file mode 100644
index 0000000000000..0bda8c67adbf5
--- /dev/null
+++ b/apps/server/scripts/dev-replay/command_output_transcript.ndjson
@@ -0,0 +1,6 @@
+{"type":"transcript_start","provider":"acpRegistry","protocol":"acp.ndjson-jsonrpc","version":"1","scenario":"dev_replay_command_output","metadata":{"generatedBy":"hand-written for the dev replay agent"}}
+{"type":"expect_outbound","frame":{"kind":"request","method":"session/prompt","params":""}}
+{"type":"emit_inbound","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"dev-replay-session","update":{"sessionUpdate":"tool_call","toolCallId":"command-output-json","kind":"execute","title":"node -e 'process.stdout.write(JSON.stringify({stdout:\"line 1\\n行 2 🚀\",stderr:\"é warning\",interrupted:false,requestId:\"keep-me\"})+\"\\n\")'","status":"in_progress","rawInput":{"command":"node -e 'process.stdout.write(JSON.stringify({stdout:\"line 1\\n行 2 🚀\",stderr:\"é warning\",interrupted:false,requestId:\"keep-me\"})+\"\\n\")'"}}}}}
+{"type":"emit_inbound","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"dev-replay-session","update":{"sessionUpdate":"tool_call_update","toolCallId":"command-output-json","status":"completed","rawOutput":"{\"stdout\":\"line 1\\n行 2 🚀\",\"stderr\":\"é warning\",\"interrupted\":false,\"requestId\":\"keep-me\"}\n"}}},"afterMs":300}
+{"type":"emit_inbound","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"dev-replay-session","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"The command printed one JSON line."}}}}}
+{"type":"emit_inbound","frame":{"kind":"response","method":"session/prompt","result":{"stopReason":"end_turn"}}}
diff --git a/apps/server/src/assets/AssetAccess.test.ts b/apps/server/src/assets/AssetAccess.test.ts
index 582e828842ede..d137305317327 100644
--- a/apps/server/src/assets/AssetAccess.test.ts
+++ b/apps/server/src/assets/AssetAccess.test.ts
@@ -525,50 +525,53 @@ describe("AssetAccess", () => {
}).pipe(Effect.provide(layerTest)),
);
- it.effect("resolves home-relative media paths independently of the workspace", () =>
- Effect.gen(function* () {
- const fs = yield* FileSystem.FileSystem;
- const path = yield* Path.Path;
- const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-home-" });
- const home = path.join(directory, "var", "home", "alice");
- const filePath = path.join(home, "Downloads", "repro.mp4");
- yield* fs.makeDirectory(path.dirname(filePath), { recursive: true });
- yield* fs.writeFileString(filePath, "recording bytes");
- const canonicalFile = yield* fs.realPath(filePath);
- yield* Effect.gen(function* () {
- for (const workspaceRoot of [
- path.join(home, "project"),
- path.join(directory, "srv", "project"),
- undefined,
- ]) {
- if (workspaceRoot) yield* fs.makeDirectory(workspaceRoot, { recursive: true });
- for (const requestedPath of ["~/Downloads/repro.mp4", "~\\Downloads/repro.mp4"]) {
- const result = yield* issueAssetUrl({
- resource: {
- _tag: "media-file",
- threadId: ThreadId.make("thread-1"),
- path: requestedPath,
- },
- ...(workspaceRoot ? { workspaceRoot } : {}),
- });
- const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
- const separator = suffix.indexOf("/");
- const asset = yield* resolveAsset(
- suffix.slice(0, separator),
- suffix.slice(separator + 1),
- );
- expect(asset).toMatchObject({
- kind: "file",
- path: canonicalFile,
- mimeType: "video/mp4",
- });
- if (asset?.kind !== "file") throw new Error("Expected a resolved home media file");
- const response = HttpServerResponse.toWeb(yield* assetFileResponse(asset));
- expect(yield* Effect.promise(() => response.text())).toBe("recording bytes");
+ it.effect.each(["media-file", "draft-workspace-file"] as const)(
+ "resolves home-relative %s paths independently of the workspace",
+ (tag) =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-home-" });
+ const home = path.join(directory, "var", "home", "alice");
+ const filePath = path.join(home, "Downloads", "repro.mp4");
+ yield* fs.makeDirectory(path.dirname(filePath), { recursive: true });
+ yield* fs.writeFileString(filePath, "recording bytes");
+ const canonicalFile = yield* fs.realPath(filePath);
+ yield* Effect.gen(function* () {
+ for (const workspaceRoot of [
+ path.join(home, "project"),
+ path.join(directory, "srv", "project"),
+ undefined,
+ ]) {
+ if (workspaceRoot) yield* fs.makeDirectory(workspaceRoot, { recursive: true });
+ for (const requestedPath of ["~/Downloads/repro.mp4", "~\\Downloads/repro.mp4"]) {
+ const result = yield* issueAssetUrl({
+ resource: {
+ ...(tag === "media-file"
+ ? { _tag: tag, threadId: ThreadId.make("thread-1") }
+ : { _tag: tag, cwd: workspaceRoot ?? directory }),
+ path: requestedPath,
+ },
+ ...(workspaceRoot ? { workspaceRoot } : {}),
+ });
+ const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
+ const separator = suffix.indexOf("/");
+ const asset = yield* resolveAsset(
+ suffix.slice(0, separator),
+ suffix.slice(separator + 1),
+ );
+ expect(asset).toMatchObject({
+ kind: "file",
+ path: canonicalFile,
+ mimeType: "video/mp4",
+ });
+ if (asset?.kind !== "file") throw new Error("Expected a resolved home media file");
+ const response = HttpServerResponse.toWeb(yield* assetFileResponse(asset));
+ expect(yield* Effect.promise(() => response.text())).toBe("recording bytes");
+ }
}
- }
- }).pipe(Effect.provideService(HostProcess.HomeDirectory, home));
- }).pipe(Effect.provide(layerTest)),
+ }).pipe(Effect.provideService(HostProcess.HomeDirectory, home));
+ }).pipe(Effect.provide(layerTest)),
);
it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
@@ -1009,6 +1012,15 @@ describe("AssetAccess", () => {
kind: "file",
path: canonicalCssPath,
});
+ yield* fileSystem.makeDirectory(path.join(root, "clips"));
+ for (const mediaName of ["clips/clip.mp4", "clips/clip.webm", "clips/clip.mp3"]) {
+ const mediaPath = path.join(root, mediaName);
+ yield* fileSystem.writeFileString(mediaPath, "media bytes");
+ expect(yield* resolveAsset(token, mediaName)).toMatchObject({
+ kind: "file",
+ path: yield* fileSystem.realPath(mediaPath),
+ });
+ }
for (const extension of ["otf", "ttf", "woff", "woff2"]) {
const fontName = `preview.${extension}`;
const fontPath = path.join(root, fontName);
diff --git a/apps/server/src/assets/AssetAccess.ts b/apps/server/src/assets/AssetAccess.ts
index c841f8eecff2e..5674372bee1a9 100644
--- a/apps/server/src/assets/AssetAccess.ts
+++ b/apps/server/src/assets/AssetAccess.ts
@@ -94,6 +94,18 @@ const PREVIEW_ASSET_EXTENSIONS = new Set([
".png",
".svg",
".webp",
+ ".m4v",
+ ".mp4",
+ ".ogv",
+ ".webm",
+ ".aac",
+ ".flac",
+ ".m4a",
+ ".mp3",
+ ".oga",
+ ".ogg",
+ ".opus",
+ ".wav",
".css",
".js",
".mjs",
@@ -607,9 +619,10 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
}
case "draft-workspace-file": {
const draftWorkspaceRoot = input.workspaceRoot ?? input.resource.cwd;
- const hostPath = input.resource.path.startsWith("~/")
- ? expandHomePath(input.resource.path, yield* HostProcess.HomeDirectory)
- : yield* toWslDrivePath(input.resource.path);
+ const hostPath =
+ input.resource.path.startsWith("~/") || input.resource.path.startsWith("~\\")
+ ? expandHomePath(input.resource.path, yield* HostProcess.HomeDirectory)
+ : yield* toWslDrivePath(input.resource.path);
if (path.isAbsolute(hostPath)) {
const finalized = yield* finalizeAbsoluteMediaFileAsset({
requestedPath: hostPath,
diff --git a/apps/server/src/assets/NativeAppIconResolver.test.ts b/apps/server/src/assets/NativeAppIconResolver.test.ts
index ecfe08788af3b..66a1171c9053c 100644
--- a/apps/server/src/assets/NativeAppIconResolver.test.ts
+++ b/apps/server/src/assets/NativeAppIconResolver.test.ts
@@ -1,6 +1,8 @@
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { expect, it } from "@effect/vitest";
+import * as Digest from "effect/crypto/Digest";
+import * as Hex from "effect/encoding/Hex";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
@@ -28,18 +30,34 @@ it.effect("resolves the exact bundle path without Spotlight and caches the conve
commands.push(command.command);
if (command.command === "/usr/bin/plutil") return "AppIcon";
if (command.command === "/usr/bin/sips") {
+ expect(command.args.slice(0, 3)).toEqual(["-z", "128", "128"]);
yield* fs.writeFileString(String(command.args.at(-1)), "converted icon");
}
return "";
}),
});
yield* Effect.gen(function* () {
+ const config = yield* ServerConfig.ServerConfig;
+ const canonicalBundle = yield* fs.realPath(bundle);
+ const sourceIcon = path.join(canonicalBundle, "Contents", "Resources", "AppIcon.icns");
+ const digest = yield* Digest.Digest;
+ const legacyKey = yield* digest
+ .digest(
+ Digest.sha256,
+ new TextEncoder().encode(`${canonicalBundle}\0AppIcon\0${sourceIcon}`),
+ )
+ .pipe(Effect.map(Hex.encode), Effect.orDie);
+ const cacheDirectory = path.join(config.providerStatusCacheDir, "native-app-icons");
+ yield* fs.makeDirectory(cacheDirectory, { recursive: true });
+ const legacyIcon = path.join(cacheDirectory, `${legacyKey}.png`);
+ yield* fs.writeFileString(legacyIcon, "legacy 64px icon");
const resolver = yield* NativeAppIconResolver.make;
const reference = { _tag: "app-path" as const, path: bundle };
const icon = yield* resolver.resolve(reference);
expect(icon).not.toBeNull();
if (icon === null) return;
expect(yield* fs.readFileString(icon)).toBe("converted icon");
+ expect(icon).not.toBe(legacyIcon);
expect(yield* resolver.resolve(reference)).toBe(icon);
expect(yield* resolver.resolve({ _tag: "app-path", path: "~/Build Output/My App.app" })).toBe(
icon,
diff --git a/apps/server/src/assets/NativeAppIconResolver.ts b/apps/server/src/assets/NativeAppIconResolver.ts
index 0d238effee4cc..e31d7a1d8c30d 100644
--- a/apps/server/src/assets/NativeAppIconResolver.ts
+++ b/apps/server/src/assets/NativeAppIconResolver.ts
@@ -21,7 +21,7 @@ import * as HostProcess from "@t3tools/shared/HostProcess";
import * as ServerConfig from "../config.ts";
-const ICON_SIZE = 64;
+const ICON_SIZE = 128;
const COMMAND_TIMEOUT = "5 seconds";
const RESOLUTION_CACHE_TTL = Duration.hours(1);
const RESOLUTION_CACHE_MAX_ENTRIES = 256;
@@ -189,7 +189,7 @@ const resolveNativeAppIconUncached = Effect.fn("NativeAppIconResolver.resolveUnc
)
.pipe(Effect.map(Hex.encode), Effect.orDie);
const cacheDirectory = path.join(config.providerStatusCacheDir, "native-app-icons");
- const cachePath = path.join(cacheDirectory, `${cacheKey}.png`);
+ const cachePath = path.join(cacheDirectory, `${cacheKey}-${ICON_SIZE}.png`);
if (yield* existingFile(cachePath)) return cachePath;
yield* fileSystem.makeDirectory(cacheDirectory, { recursive: true });
diff --git a/apps/server/src/auth/McpOAuth.test.ts b/apps/server/src/auth/McpOAuth.test.ts
index 4cd276c51133b..d72a716673e66 100644
--- a/apps/server/src/auth/McpOAuth.test.ts
+++ b/apps/server/src/auth/McpOAuth.test.ts
@@ -229,6 +229,46 @@ it.effect("registers loopback and https clients and never redirects for an unver
expect(response.status).toBe(400);
expect(yield* json(response)).toMatchObject({ error: "invalid_redirect_uri" });
}
+ // JSON escaping can inflate the signed client_id past what an authorize URL can carry.
+ const oversized = yield* handler(
+ at("/oauth/mcp/register", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: encodeJson({
+ redirect_uris: Array.from(
+ { length: 10 },
+ (_, index) => `https://bot.example/${index}/${'"'.repeat(480)}`,
+ ),
+ }),
+ }),
+ );
+ expect(oversized.status).toBe(400);
+ const fiveLongCallbacks = yield* handler(
+ at("/oauth/mcp/register", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: encodeJson({
+ client_name: "A".repeat(100),
+ redirect_uris: Array.from(
+ { length: 5 },
+ (_, index) => `https://a.co/${index}/${"界".repeat(497)}`,
+ ),
+ }),
+ }),
+ );
+ expect(fiveLongCallbacks.status).toBe(201);
+
+ for (const malformed of [
+ { client_name: 42, redirect_uris: [REDIRECT] },
+ { redirect_uris: REDIRECT },
+ ]) {
+ const response = yield* handler(postJson("/oauth/mcp/register", malformed));
+ expect(response.status).toBe(400);
+ expect(response.headers.get("content-type")).toMatch(/^application\/json/);
+ expect(yield* json<{ error: string }>(response)).toMatchObject({
+ error: expect.stringMatching(/^invalid_(client_metadata|redirect_uri)$/),
+ });
+ }
const registered = yield* register(handler);
expect(registered.status).toBe(201);
@@ -252,6 +292,17 @@ it.effect("registers loopback and https clients and never redirects for an unver
expect(unregistered.status).toBe(400);
expect(unregistered.headers.get("location")).toBeNull();
+ for (const resource of [`${ORIGIN}/mcp#section`, `${ORIGIN}/mcp#`]) {
+ const wrongTarget = yield* handler(
+ at(
+ `/oauth/mcp/authorize?${new URLSearchParams({ ...authorizeParams(clientId), resource })}`,
+ ),
+ );
+ expect(wrongTarget.status).toBe(302);
+ const location = new URL(wrongTarget.headers.get("location")!, ORIGIN);
+ expect(location.searchParams.get("error"), resource).toBe("invalid_target");
+ }
+
const query = new URLSearchParams(authorizeParams(clientId)).toString();
const handoff = yield* handler(at(`/oauth/mcp/authorize?${query}`));
expect(handoff.status).toBe(302);
@@ -411,6 +462,43 @@ it.live("signs in a hosted agent with an https callback that asked for a client
),
);
+it.live("signs in Gemini, which registers six user-bound redirect URIs for one client", () =>
+ withRoutes((handler, auth) =>
+ Effect.gen(function* () {
+ const redirectUris = Array.from(
+ { length: 6 },
+ (_, index) =>
+ `https://oauth-redirect.googleusercontent.com/r/user_bound_custom-mcp-test${index}`,
+ );
+ const registered = yield* handler(
+ at("/oauth/mcp/register", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: encodeJson({
+ client_name: "Google",
+ redirect_uris: redirectUris,
+ token_endpoint_auth_method: "client_secret_basic",
+ }),
+ }),
+ );
+ const client = (yield* json(registered)) as { client_id: string };
+ expect(client).toMatchObject({ redirect_uris: redirectUris });
+ expect(registered.status).toBe(201);
+
+ const callbackUrl = redirectUris[5]!;
+ const params = authorizeParams(client.client_id, callbackUrl);
+ const pairing = yield* auth.issuePairingCredential();
+ const approved = yield* decide(handler, params, {
+ _tag: "pairing-code",
+ access: "approval-required",
+ code: pairing.credential,
+ });
+ const callback = new URL(approved.redirectTo!);
+ expect(`${callback.origin}${callback.pathname}`).toBe(callbackUrl);
+ }),
+ ),
+);
+
it.live("rejects a wrong PKCE verifier and spends the code", () =>
withRoutes((handler, auth) =>
Effect.gen(function* () {
diff --git a/apps/server/src/auth/McpOAuth.ts b/apps/server/src/auth/McpOAuth.ts
index 426cb2213f3ef..fdb0e4044f1df 100644
--- a/apps/server/src/auth/McpOAuth.ts
+++ b/apps/server/src/auth/McpOAuth.ts
@@ -54,8 +54,12 @@ import { requestUrl } from "../requestUrl.ts";
const SIGNING_SECRET_NAME = "mcp-oauth-signing-key";
const AUTHORIZATION_CODE_TTL_MS = 60_000;
const MAX_CLIENT_NAME_LENGTH = 100;
-const MAX_REDIRECT_URIS = 5;
+const MAX_REDIRECT_URIS = 10;
const MAX_REDIRECT_URI_LENGTH = 512;
+// The client_id rides in the authorize URL. Past the original five-URI limit, cap it to leave room
+// under Node's 16 KB header cap for an encoded redirect_uri and state.
+const MAX_UNBOUNDED_CLIENT_ID_REDIRECT_URIS = 5;
+const MAX_CLIENT_ID_LENGTH = 10_240;
const DEFAULT_CLIENT_NAME = "MCP client";
const LOOPBACK_HOSTNAMES = new Set(["localhost", "127.0.0.1", "[::1]"]);
const CODE_CHALLENGE_PATTERN = /^[A-Za-z0-9_-]{43}$/;
@@ -130,9 +134,11 @@ export const redirectMatches = (registered: string, presented: string): boolean
const sameResource = (urls: McpOAuthUrls, presented: string | undefined): boolean => {
if (presented === undefined) return true;
+ // URL.hash misses empty fragments, which RFC 8707 §2 also forbids.
+ if (presented.includes("#")) return false;
try {
const url = new URL(presented);
- return url.hash === "" && `${url.origin}${url.pathname.replace(/\/+$/u, "")}` === urls.resource;
+ return `${url.origin}${url.pathname.replace(/\/+$/u, "")}` === urls.resource;
} catch {
return false;
}
@@ -348,8 +354,18 @@ const make = Effect.gen(function* () {
"Linked environments is off on that machine. Turn it on in its Settings → Labs.",
});
}
+ const clientId = yield* signClientId(name, redirectUris, peerLink);
+ if (
+ redirectUris.length > MAX_UNBOUNDED_CLIENT_ID_REDIRECT_URIS &&
+ clientId.length > MAX_CLIENT_ID_LENGTH
+ ) {
+ return yield* new AuthMcpRegistrationError({
+ error: "invalid_redirect_uri",
+ error_description: "Redirect URIs are too long to fit in an authorization request.",
+ });
+ }
return {
- clientId: yield* signClientId(name, redirectUris, peerLink),
+ clientId,
name,
redirectUris,
peerLink,
diff --git a/apps/server/src/auth/PairingGrantStore.test.ts b/apps/server/src/auth/PairingGrantStore.test.ts
index 5184beb096807..3f95ce46ec695 100644
--- a/apps/server/src/auth/PairingGrantStore.test.ts
+++ b/apps/server/src/auth/PairingGrantStore.test.ts
@@ -70,6 +70,22 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("PairingGrantStor
),
);
+ it.effect("accepts a one-time token typed in hyphen- or space-separated groups", () =>
+ Effect.gen(function* () {
+ const bootstrapCredentials = yield* PairingGrantStore.PairingGrantStore;
+ const issued = yield* bootstrapCredentials.issueOneTimeToken();
+ const formatted = issued.credential.match(/.{1,4}/g)!.join("-");
+ const consumed = yield* bootstrapCredentials.consume(formatted.toLowerCase());
+ const second = yield* bootstrapCredentials.issueOneTimeToken();
+ const spaced = yield* bootstrapCredentials.consume(
+ second.credential.match(/.{1,4}/g)!.join(" "),
+ );
+
+ expect(consumed.method).toBe("one-time-token");
+ expect(spaced.method).toBe("one-time-token");
+ }).pipe(Effect.provide(layerPairingGrantStore())),
+ );
+
it.effect("atomically consumes a one-time token when multiple requests race", () =>
Effect.gen(function* () {
const bootstrapCredentials = yield* PairingGrantStore.PairingGrantStore;
diff --git a/apps/server/src/auth/PairingGrantStore.ts b/apps/server/src/auth/PairingGrantStore.ts
index f5f558d57526a..62d78d3495013 100644
--- a/apps/server/src/auth/PairingGrantStore.ts
+++ b/apps/server/src/auth/PairingGrantStore.ts
@@ -637,8 +637,10 @@ const make = Effect.gen(function* () {
}
// Only credentials in the issued pairing-code formats are case-insensitive.
- const pairingCredential = PAIRING_TOKEN_PATTERN.test(credential)
- ? credential.toUpperCase()
+ // People type codes in groups such as XXXX-XXXX-XXXX.
+ const compactCredential = credential.replace(/[\s-]/g, "");
+ const pairingCredential = PAIRING_TOKEN_PATTERN.test(compactCredential)
+ ? compactCredential.toUpperCase()
: (parseMcpApprovalCode(credential)?.code ?? credential);
// Check scopes in the UPDATE so rejected requests cannot spend one-time links.
diff --git a/apps/server/src/auth/RpcAuthorization.test.ts b/apps/server/src/auth/RpcAuthorization.test.ts
index 37abf3d1593d3..2302170f99a97 100644
--- a/apps/server/src/auth/RpcAuthorization.test.ts
+++ b/apps/server/src/auth/RpcAuthorization.test.ts
@@ -75,6 +75,10 @@ describe("RPC authorization scopes", () => {
}
});
+ it("still lets readers load settings the way installed Swift clients ask", () => {
+ expect(requiredScopeForRpcMethod("server.getSettings")).toBe(AuthOrchestrationReadScope);
+ });
+
it("rejects unknown RPC method names", () => {
for (const method of ["server.notRegistered", "toString", "constructor"]) {
expect(() => requiredScopeForRpcMethod(method)).toThrow(
diff --git a/apps/server/src/auth/RpcAuthorization.ts b/apps/server/src/auth/RpcAuthorization.ts
index 7823c3a146228..7925fd869799f 100644
--- a/apps/server/src/auth/RpcAuthorization.ts
+++ b/apps/server/src/auth/RpcAuthorization.ts
@@ -90,6 +90,7 @@ export const RPC_REQUIRED_SCOPES = {
[WS_METHODS.serverRemoveKeybinding]: AuthSettingsWriteScope,
[WS_METHODS.serverGetStorageCleanupReport]: AuthOrchestrationReadScope,
[WS_METHODS.serverGetDatabaseStorage]: AuthOrchestrationReadScope,
+ [WS_METHODS.serverGetSettings]: AuthOrchestrationReadScope,
[WS_METHODS.peerLinksList]: AuthAccessReadScope,
[WS_METHODS.serverUpdateSettings]: AuthSettingsWriteScope,
[WS_METHODS.serverSearchAcpRegistry]: AuthOrchestrationReadScope,
diff --git a/apps/server/src/auth/ServerSecretStore.test.ts b/apps/server/src/auth/ServerSecretStore.test.ts
index 08a33e2fde3c5..fa216177f494a 100644
--- a/apps/server/src/auth/ServerSecretStore.test.ts
+++ b/apps/server/src/auth/ServerSecretStore.test.ts
@@ -113,6 +113,55 @@ const layerConcurrentCreateSecretStore = () =>
Layer.provideMerge(layerConcurrentReadMissFileSystem),
);
+// Both callers read the empty secret before either repairs it, and the second removal of the
+// secret file waits until the first caller has returned its key.
+const layerConcurrentEmptyRepairFileSystem = (firstReturned: Deferred.Deferred) =>
+ Layer.effect(
+ FileSystem.FileSystem,
+ Effect.gen(function* () {
+ const fileSystem = yield* FileSystem.FileSystem;
+ const readCountRef = yield* Ref.make(0);
+ const removeCountRef = yield* Ref.make(0);
+ const readBarrier = yield* Deferred.make();
+ const isSecretPath = (path: string) => /[\\/]session-signing-key\.bin$/.test(path);
+
+ return {
+ ...fileSystem,
+ readFile: (path) =>
+ isSecretPath(path)
+ ? Ref.updateAndGet(readCountRef, (count) => count + 1).pipe(
+ Effect.flatMap((count) =>
+ count > 2
+ ? fileSystem.readFile(path)
+ : Effect.gen(function* () {
+ if (count === 2) {
+ yield* Deferred.succeed(readBarrier, void 0);
+ }
+ yield* Deferred.await(readBarrier);
+ return yield* fileSystem.readFile(path);
+ }),
+ ),
+ )
+ : fileSystem.readFile(path),
+ remove: (path, options) =>
+ isSecretPath(path)
+ ? Ref.updateAndGet(removeCountRef, (count) => count + 1).pipe(
+ Effect.flatMap((count) =>
+ count > 1 ? Deferred.await(firstReturned) : Effect.void,
+ ),
+ Effect.flatMap(() => fileSystem.remove(path, options)),
+ )
+ : fileSystem.remove(path, options),
+ } satisfies FileSystem.FileSystem;
+ }),
+ ).pipe(Layer.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)));
+
+const layerConcurrentEmptyRepairSecretStore = (firstReturned: Deferred.Deferred) =>
+ ServerSecretStore.layer.pipe(
+ Layer.provide(layerServerConfig()),
+ Layer.provideMerge(layerConcurrentEmptyRepairFileSystem(firstReturned)),
+ );
+
it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("ServerSecretStore.layer", (it) => {
it.effect("reuses an existing secret instead of regenerating it", () =>
Effect.gen(function* () {
@@ -125,6 +174,40 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("ServerSecretStor
}).pipe(Effect.provide(layerServerSecretStore())),
);
+ it.effect("replaces an empty persisted secret with a fresh random one", () =>
+ Effect.gen(function* () {
+ const secretStore = yield* ServerSecretStore.ServerSecretStore;
+ yield* secretStore.set("session-signing-key", new Uint8Array());
+
+ const secret = yield* secretStore.getOrCreateRandom("session-signing-key", 32);
+ const persisted = yield* secretStore.get("session-signing-key");
+
+ assert.equal(secret.byteLength, 32);
+ assert.deepEqual(Array.from(Option.getOrThrow(persisted)), Array.from(secret));
+ }).pipe(Effect.provide(layerServerSecretStore())),
+ );
+
+ it.effect("keeps the repaired secret when concurrent callers find it empty", () =>
+ Effect.gen(function* () {
+ const firstReturned = yield* Deferred.make();
+ yield* Effect.gen(function* () {
+ const secretStore = yield* ServerSecretStore.ServerSecretStore;
+ yield* secretStore.set("session-signing-key", new Uint8Array());
+ const getOrCreate = secretStore
+ .getOrCreateRandom("session-signing-key", 32)
+ .pipe(Effect.tap(() => Deferred.succeed(firstReturned, void 0)));
+
+ const [first, second] = yield* Effect.all([getOrCreate, getOrCreate], {
+ concurrency: "unbounded",
+ });
+ const persisted = Option.getOrThrow(yield* secretStore.get("session-signing-key"));
+
+ assert.deepEqual(Array.from(first), Array.from(persisted));
+ assert.deepEqual(Array.from(second), Array.from(persisted));
+ }).pipe(Effect.provide(layerConcurrentEmptyRepairSecretStore(firstReturned)));
+ }),
+ );
+
it.effect("returns the persisted secret when concurrent creators race", () =>
Effect.gen(function* () {
const secretStore = yield* ServerSecretStore.ServerSecretStore;
diff --git a/apps/server/src/auth/ServerSecretStore.ts b/apps/server/src/auth/ServerSecretStore.ts
index e950acb38a71d..cabded3d0c7b0 100644
--- a/apps/server/src/auth/ServerSecretStore.ts
+++ b/apps/server/src/auth/ServerSecretStore.ts
@@ -8,6 +8,7 @@ import * as Path from "effect/Path";
import * as Predicate from "effect/Predicate";
import * as PlatformError from "effect/PlatformError";
import * as Schema from "effect/Schema";
+import * as Semaphore from "effect/Semaphore";
import * as ServerConfig from "../config.ts";
@@ -169,6 +170,9 @@ export const make = Effect.gen(function* () {
);
const resolveSecretPath = (name: string) => path.join(serverConfig.secretsDir, `${name}.bin`);
+ const emptySecretRepair = yield* Semaphore.make(1);
+ const isMissingOrNonEmpty = (secret: Option.Option) =>
+ Option.isNone(secret) || secret.value.byteLength > 0;
const get: ServerSecretStore["Service"]["get"] = (name) =>
fileSystem.readFile(resolveSecretPath(name)).pipe(
@@ -263,6 +267,19 @@ export const make = Effect.gen(function* () {
const getOrCreateRandom: ServerSecretStore["Service"]["getOrCreateRandom"] = (name, bytes) =>
get(name).pipe(
+ // Older builds could persist a 0-byte secret, which is never a usable key. Re-read under
+ // the permit, and keep it until an interrupted removal settles, so a caller that saw the
+ // empty file cannot remove a key another caller created.
+ Effect.filterOrElse(isMissingOrNonEmpty, () =>
+ emptySecretRepair.withPermits(1)(
+ get(name).pipe(
+ Effect.filterOrElse(isMissingOrNonEmpty, () =>
+ remove(name).pipe(Effect.as(Option.none())),
+ ),
+ Effect.uninterruptible,
+ ),
+ ),
+ ),
Effect.flatMap(
Option.match({
onSome: Effect.succeed,
diff --git a/apps/server/src/auth/http.test.ts b/apps/server/src/auth/http.test.ts
index 3a27fa9baba6b..28cc45de42c38 100644
--- a/apps/server/src/auth/http.test.ts
+++ b/apps/server/src/auth/http.test.ts
@@ -125,6 +125,18 @@ it.effect("sets the selected browser session cookies through the HTTP route", ()
expect(devCookies).toContainEqual(
expect.stringMatching(/^t3_session_[^=]*=;.*Max-Age=0/),
);
+ expect(devCookies.filter((cookie) => /;\s*Secure/i.test(cookie))).toEqual([]);
+ const httpsResponse = await environmentA.handler(
+ postJson(
+ "/api/auth/browser-session",
+ { credential: DEV_TOKEN },
+ { "x-forwarded-proto": "https" },
+ ),
+ requestContext,
+ );
+ const httpsCookies = httpsResponse.headers.getSetCookie();
+ expect(httpsCookies).toHaveLength(2);
+ for (const cookie of httpsCookies) expect(cookie).toMatch(/;\s*Secure/i);
const devCookieHeader = devCookie?.split(";", 1)[0] ?? "";
const environmentBSession = await environmentB.handler(
new Request("http://127.0.0.1/api/auth/session", {
diff --git a/apps/server/src/auth/http.ts b/apps/server/src/auth/http.ts
index 9c9a05e6b7ce9..b8b49a1d1b347 100644
--- a/apps/server/src/auth/http.ts
+++ b/apps/server/src/auth/http.ts
@@ -26,6 +26,7 @@ import { causeErrorTag } from "@t3tools/shared/observability";
import * as Clock from "effect/Clock";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
+import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as Layer from "effect/Layer";
import * as Cookies from "effect/http/Cookies";
@@ -201,13 +202,24 @@ export const failEnvironmentInternal =
return yield* new EnvironmentInternalError({ code: "internal_error", reason, traceId });
});
-const appendSessionCookie = (cookieName: string, token: string, expiresAt: DateTime.DateTime) =>
+// Plaintext LAN servers still need the cookie; TLS arrives through a proxy that sets X-Forwarded-Proto.
+const sessionCookieOptions = (request: HttpServerRequest.HttpServerRequest) => ({
+ httpOnly: true,
+ path: "/",
+ sameSite: "lax" as const,
+ secure: Option.exists(requestUrl(request), (url) => url.protocol === "https:"),
+});
+
+const appendSessionCookie = (
+ request: HttpServerRequest.HttpServerRequest,
+ cookieName: string,
+ token: string,
+ expiresAt: DateTime.DateTime,
+) =>
Effect.fromResult(
Cookies.set(Cookies.empty, cookieName, token, {
+ ...sessionCookieOptions(request),
expires: DateTime.toDate(expiresAt),
- httpOnly: true,
- path: "/",
- sameSite: "lax",
}),
).pipe(
Effect.catch(() => failEnvironmentInternal("browser_session_cookie_failed")),
@@ -287,7 +299,12 @@ export const layer = HttpApiBuilder.group(
result.sessionMethod === "browser-session-cookie" &&
result.expiresAt
) {
- yield* appendSessionCookie(sessions.cookieName, credential.token, result.expiresAt);
+ yield* appendSessionCookie(
+ request,
+ sessions.cookieName,
+ credential.token,
+ result.expiresAt,
+ );
yield* appendCredentialResponseHeaders;
}
return result;
@@ -319,19 +336,17 @@ export const layer = HttpApiBuilder.group(
const cookieName = result.cookieName ?? sessions.cookieName;
const selectedCookie = yield* Effect.fromResult(
Cookies.set(Cookies.empty, cookieName, result.sessionToken, {
+ ...sessionCookieOptions(request),
expires: DateTime.toDate(result.response.expiresAt),
- httpOnly: true,
- path: "/",
- sameSite: "lax",
}),
).pipe(Effect.catch(() => failEnvironmentInternal("browser_session_cookie_failed")));
const sessionCookies = result.expireNormalCookie
? yield* Effect.fromResult(
- Cookies.expireCookie(selectedCookie, sessions.cookieName, {
- httpOnly: true,
- path: "/",
- sameSite: "lax",
- }),
+ Cookies.expireCookie(
+ selectedCookie,
+ sessions.cookieName,
+ sessionCookieOptions(request),
+ ),
).pipe(Effect.catch(() => failEnvironmentInternal("browser_session_cookie_failed")))
: selectedCookie;
diff --git a/apps/server/src/auth/mcpOAuthHttp.ts b/apps/server/src/auth/mcpOAuthHttp.ts
index a411c635e30e4..6e10362000adf 100644
--- a/apps/server/src/auth/mcpOAuthHttp.ts
+++ b/apps/server/src/auth/mcpOAuthHttp.ts
@@ -2,6 +2,8 @@ import {
AuthMcpApprovalError,
AuthMcpAuthorizationRequest,
AuthMcpClientAccess,
+ AuthMcpClientRegistration,
+ AuthMcpRegistrationError,
EnvironmentHttpApi,
mcpClientScopes,
} from "@t3tools/contracts";
@@ -42,6 +44,10 @@ const noStore = HttpEffect.appendPreResponseHandler((_request, response) =>
const requestUrls = Effect.map(HttpServerRequest.HttpServerRequest, McpOAuth.requestUrls);
const decodeAuthorizationRequest = Schema.decodeEffect(AuthMcpAuthorizationRequest);
+// Decoded by the handler so malformed metadata gets the RFC 7591 error, not HttpApi's empty 400.
+const decodeClientRegistration = Schema.decodeUnknownEffect(
+ Schema.fromJsonString(AuthMcpClientRegistration),
+);
/**
* An unverified client or redirect is reported, never redirected; any other problem goes back to
@@ -100,8 +106,18 @@ export const layer = HttpApiBuilder.group(
.handle("authorizationServer", () =>
requestUrls.pipe(Effect.map(McpOAuth.authorizationServerMetadata)),
)
- .handle("register", ({ payload }) =>
- oauth.register(payload).pipe(
+ .handleRaw("register", ({ request }) =>
+ request.text.pipe(
+ Effect.orDie,
+ Effect.flatMap(decodeClientRegistration),
+ Effect.mapError(
+ (cause) =>
+ new AuthMcpRegistrationError({
+ error: "invalid_client_metadata",
+ error_description: `Invalid client metadata: ${cause.message}`,
+ }),
+ ),
+ Effect.flatMap(oauth.register),
Effect.map((client) => ({
client_id: client.clientId,
client_name: client.name,
diff --git a/apps/server/src/auth/utils.test.ts b/apps/server/src/auth/utils.test.ts
index 07c5759e77e3c..0dc813271caee 100644
--- a/apps/server/src/auth/utils.test.ts
+++ b/apps/server/src/auth/utils.test.ts
@@ -29,6 +29,29 @@ describe("deriveAuthClientMetadata", () => {
});
});
+ it("records the forwarded client address of a request proxied by Tailscale Serve", () => {
+ const metadata = deriveAuthClientMetadata({
+ request: {
+ headers: {
+ "x-forwarded-for": "100.64.0.2",
+ "x-forwarded-host": "host-a.tailnet-name.ts.net",
+ "x-forwarded-proto": "https",
+ },
+ source: { remoteAddress: "127.0.0.1" },
+ } as never,
+ });
+
+ expect(metadata.ipAddress).toBe("100.64.0.2");
+
+ const direct = deriveAuthClientMetadata({
+ request: {
+ headers: { "x-forwarded-for": "100.64.0.2" },
+ source: { remoteAddress: "192.168.1.20" },
+ } as never,
+ });
+ expect(direct.ipAddress).toBe("192.168.1.20");
+ });
+
it.each([
[
"Edge on Android",
diff --git a/apps/server/src/auth/utils.ts b/apps/server/src/auth/utils.ts
index fb7be12a3c43a..429cf69276f30 100644
--- a/apps/server/src/auth/utils.ts
+++ b/apps/server/src/auth/utils.ts
@@ -192,12 +192,25 @@ function readRemoteAddressFromSource(source: unknown): string | undefined {
return normalizeIpAddress(candidate.socket?.remoteAddress ?? candidate.remoteAddress);
}
+const isLoopbackIpAddress = (address: string): boolean =>
+ (NodeNet.isIPv4(address) && address.startsWith("127.")) || address === "::1";
+
+// A loopback peer is a local reverse proxy (Tailscale Serve); trust only the entry it appended.
+function resolveClientIpAddress(request: HttpServerRequest.HttpServerRequest): string | undefined {
+ const peer = readRemoteAddressFromSource(request.source);
+ if (!peer || !isLoopbackIpAddress(peer)) {
+ return peer;
+ }
+ const forwarded = normalizeIpAddress(request.headers["x-forwarded-for"]?.split(",").at(-1));
+ return forwarded && NodeNet.isIP(forwarded) !== 0 ? forwarded : peer;
+}
+
export function deriveAuthClientMetadata(input: {
readonly request: HttpServerRequest.HttpServerRequest;
readonly presented?: AuthClientPresentationMetadata;
}): AuthClientMetadata {
const userAgent = normalizeNonEmptyString(input.request.headers["user-agent"]);
- const ipAddress = readRemoteAddressFromSource(input.request.source);
+ const ipAddress = resolveClientIpAddress(input.request);
const os = input.presented?.os ?? inferOs(userAgent);
const browser = inferBrowser(userAgent);
return {
diff --git a/apps/server/src/binCli.test.ts b/apps/server/src/binCli.test.ts
new file mode 100644
index 0000000000000..964f8c4f23f27
--- /dev/null
+++ b/apps/server/src/binCli.test.ts
@@ -0,0 +1,122 @@
+// @effect-diagnostics nodeBuiltinImport:off -- Exercises the CLI's real stdout and stderr through a subprocess and an HTTP fixture.
+import * as NodeHttp from "node:http";
+import * as NodeURL from "node:url";
+
+import * as NodeServices from "@effect/platform-node/NodeServices";
+import { assert, it } from "@effect/vitest";
+import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
+import * as Effect from "effect/Effect";
+import * as FileSystem from "effect/FileSystem";
+import * as Stream from "effect/Stream";
+import { ChildProcess, ChildProcessSpawner } from "effect/process";
+import * as SqlClient from "effect/sql/SqlClient";
+
+import { migrationManifest, runMigrations } from "./persistence/Migrations.ts";
+import {
+ makePersistedServerRuntimeState,
+ persistServerRuntimeState,
+} from "./serverRuntimeState.ts";
+
+it.live("keeps migration warnings out of JSON thread output", () =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cli-json-" });
+ const stateDir = `${root}/userdata`;
+ yield* fs.makeDirectory(stateDir);
+ yield* Effect.gen(function* () {
+ const sql = yield* SqlClient.SqlClient;
+ yield* runMigrations();
+ const futureId = Math.max(...migrationManifest.map(([id]) => id)) + 1;
+ yield* sql`
+ INSERT INTO effect_sql_migrations (migration_id, name)
+ VALUES (${futureId}, 'FutureMigration')
+ `;
+ }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: `${stateDir}/statev2.sqlite` })));
+
+ const server = yield* Effect.acquireRelease(
+ Effect.promise(async () => {
+ const server = NodeHttp.createServer(async (request, response) => {
+ let body = "";
+ for await (const chunk of request) body += String(chunk);
+ if (request.method === "DELETE") {
+ response.writeHead(204).end();
+ return;
+ }
+ const message = JSON.parse(body) as {
+ id?: string;
+ method: string;
+ params?: { name: string };
+ };
+ if (message.id === undefined) {
+ response.writeHead(202).end();
+ return;
+ }
+ const result =
+ message.method === "initialize"
+ ? { protocolVersion: "2025-06-18" }
+ : {
+ structuredContent:
+ message.params?.name === "t3_project_list"
+ ? {
+ projects: [{ id: "project-1", title: "Test", workspaceRoot: root }],
+ nextCursor: null,
+ }
+ : {
+ projectId: "project-1",
+ currentThreadId: null,
+ threads: [],
+ nextCursor: null,
+ total: 0,
+ },
+ };
+ response.writeHead(200, {
+ "content-type": "application/json",
+ "mcp-session-id": "cli-json-test",
+ });
+ response.end(JSON.stringify({ jsonrpc: "2.0", id: message.id, result }));
+ });
+ await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
+ return server;
+ }),
+ (server) =>
+ Effect.promise(() => new Promise((resolve) => server.close(() => resolve()))),
+ );
+ const address = server.address();
+ assert(address !== null && typeof address !== "string");
+ yield* persistServerRuntimeState({
+ path: `${stateDir}/server-runtime.json`,
+ state: yield* makePersistedServerRuntimeState({
+ config: { host: "127.0.0.1", devUrl: undefined },
+ port: address.port,
+ }),
+ });
+
+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
+ const child = yield* spawner.spawn(
+ ChildProcess.make(
+ process.execPath,
+ [
+ NodeURL.fileURLToPath(new URL("./bin.ts", import.meta.url)),
+ "thread",
+ "list",
+ "--project",
+ "project-1",
+ "--json",
+ "--base-dir",
+ root,
+ ],
+ { env: { T3CODE_HOME: root } },
+ ),
+ );
+ const { stdout, stderr, exitCode } = yield* Effect.all(
+ {
+ stdout: child.stdout.pipe(Stream.decodeText(), Stream.mkString),
+ stderr: child.stderr.pipe(Stream.decodeText(), Stream.mkString),
+ exitCode: child.exitCode,
+ },
+ { concurrency: "unbounded" },
+ );
+ assert.strictEqual(Number(exitCode), 0, stderr);
+ assert.deepStrictEqual(JSON.parse(stdout), []);
+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
+);
diff --git a/apps/server/src/claudeModelOptions.test.ts b/apps/server/src/claudeModelOptions.test.ts
index b69b20db7ec4d..a7513a5931831 100644
--- a/apps/server/src/claudeModelOptions.test.ts
+++ b/apps/server/src/claudeModelOptions.test.ts
@@ -105,14 +105,33 @@ describe("compileClaudeModelSelection", () => {
).toMatchObject({ effort: "high", promptEffort: "ultrathink" });
});
- it("keeps explicit effort for models missing from the local catalog", () => {
+ it("ignores thinking for catalog models without a thinking option", () => {
expect(
- compileClaudeModelSelection(
- selection("claude-pool-model-not-in-catalog", [{ id: "effort", value: "max" }]),
- ).effort,
- ).toBe("max");
- expect(
- compileClaudeModelSelection(selection("claude-pool-model-not-in-catalog", [])).effort,
- ).toBeUndefined();
+ compileClaudeModelSelection(selection("claude-opus-5-5", [{ id: "thinking", value: false }]))
+ .settings,
+ ).not.toHaveProperty("alwaysThinkingEnabled");
});
+
+ it.each(["gateway-route", "gateway-route[1m]"])(
+ "keeps explicit effort and thinking for %s outside the local catalog",
+ (model) => {
+ for (const thinking of [true, false]) {
+ expect(
+ compileClaudeModelSelection(
+ selection(model, [
+ { id: "effort", value: "max" },
+ { id: "thinking", value: thinking },
+ ]),
+ ),
+ ).toMatchObject({
+ apiModelId: model,
+ effort: "max",
+ settings: { alwaysThinkingEnabled: thinking },
+ });
+ }
+ const unconfigured = compileClaudeModelSelection(selection(model, []));
+ expect(unconfigured.effort).toBeUndefined();
+ expect(unconfigured.settings).toEqual({});
+ },
+ );
});
diff --git a/apps/server/src/claudeModelOptions.ts b/apps/server/src/claudeModelOptions.ts
index 12530db50ec5e..c3376ef7ed8dc 100644
--- a/apps/server/src/claudeModelOptions.ts
+++ b/apps/server/src/claudeModelOptions.ts
@@ -12,6 +12,7 @@ import {
normalizeClaudeCatalogEffort,
resolveClaudeCatalogApiModelId,
resolveClaudeCatalogEffort,
+ resolveClaudeCatalogModel,
resolveClaudeModelSlug,
type ClaudeModelCatalog,
} from "./provider/ClaudeModelCatalog.ts";
@@ -45,9 +46,11 @@ export function compileClaudeModelSelection(
const fastMode = supportsBoolean("fastMode")
? (getModelSelectionBooleanOptionValue(selection, "fastMode") ?? false)
: undefined;
- const thinking = supportsBoolean("thinking")
- ? getModelSelectionBooleanOptionValue(selection, "thinking")
- : undefined;
+ const inCatalog = resolveClaudeCatalogModel(catalog, selection.model) !== undefined;
+ const thinking =
+ !inCatalog || supportsBoolean("thinking")
+ ? getModelSelectionBooleanOptionValue(selection, "thinking")
+ : undefined;
const ultracode = descriptors.find((descriptor) => descriptor.id === "ultracode")?.currentValue;
const settings = {
...(typeof thinking === "boolean" ? { alwaysThinkingEnabled: thinking } : {}),
diff --git a/apps/server/src/cli/config.test.ts b/apps/server/src/cli/config.test.ts
index f4971e4d1c16d..d83779f046aa6 100644
--- a/apps/server/src/cli/config.test.ts
+++ b/apps/server/src/cli/config.test.ts
@@ -233,6 +233,59 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
}),
);
+ it.effect("names the pair command for the refused server's home", () =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const child = yield* liveProcess;
+ assert(child.pid !== undefined);
+ for (const source of ["flag", "T3CODE_HOME", "default"] as const) {
+ const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cli-preflight-pair-" });
+ const baseDir = source === "default" ? path.join(home, ".t3") : home;
+ const stateDir = path.join(baseDir, "userdata");
+ yield* fs.makeDirectory(stateDir, { recursive: true });
+ yield* fs.writeFileString(
+ path.join(stateDir, "server-runtime.json"),
+ yield* encodeUnknownJson({
+ version: 1,
+ pid: child.pid,
+ port: 3773,
+ origin: "http://127.0.0.1:3773",
+ startedAt: "2026-10-01T00:00:00.000Z",
+ }),
+ );
+ const error = yield* resolveServerConfig(
+ {
+ ...minimalWebFlags(baseDir),
+ baseDir: source === "flag" ? Option.some(baseDir) : Option.none(),
+ cwd: Option.some(path.join(home, "project")),
+ },
+ Option.none(),
+ { rejectRunningServer: true },
+ ).pipe(
+ Effect.provide(
+ Layer.merge(
+ NetService.layer,
+ ConfigProvider.layer(
+ ConfigProvider.fromEnv({
+ env: source === "T3CODE_HOME" ? { T3CODE_HOME: baseDir } : {},
+ }),
+ ),
+ ),
+ ),
+ Effect.provideService(HostProcess.HomeDirectory, home),
+ Effect.provideService(HostProcess.Platform, "linux"),
+ Effect.flip,
+ );
+ // A temp dir with spaces or backslashes is single-quoted for the shell.
+ const homePattern = baseDir.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+ expect(String(error)).toMatch(
+ new RegExp(`pair --base-dir (${homePattern}|'${homePattern}')`),
+ );
+ }
+ }),
+ );
+
it.effect("enables a trimmed reusable auth token only for web dev mode", () =>
Effect.gen(function* () {
const baseDir = yield* FileSystem.FileSystem.pipe(
diff --git a/apps/server/src/cli/config.ts b/apps/server/src/cli/config.ts
index 0bdc07ab55e11..2169ab7e284e8 100644
--- a/apps/server/src/cli/config.ts
+++ b/apps/server/src/cli/config.ts
@@ -27,6 +27,7 @@ import { resolveServiceLauncherMode } from "../cloud/serviceLauncherClient.ts";
import * as ServerConfig from "../config.ts";
import { expandHomePath, resolveBaseDir } from "../os-jank.ts";
import { isProcessAlive, readPersistedServerRuntimeState } from "../serverRuntimeState.ts";
+import { resolveHostCliCommand } from "./invocation.ts";
const modeFlag = Flag.Literals("mode", ServerConfig.RuntimeMode.literals).pipe(
Flag.withDescription("Runtime mode. `desktop` keeps loopback defaults unless overridden."),
@@ -369,8 +370,13 @@ export const resolveServerConfig = Effect.fn("config.resolveServerConfig")(funct
runtime.value.pid !== process.pid &&
isProcessAlive(runtime.value.pid)
) {
+ // Bare `t3 pair` prefers a linked worktree's `.t3`, so always name this home.
+ const { command: pairCommand } = yield* resolveHostCliCommand("pair", [
+ "--base-dir",
+ baseDir,
+ ]);
return yield* new CliError.UserError({
- cause: `A T3 Code server is already running for ${baseDir} (pid ${runtime.value.pid}, ${runtime.value.origin}). Connect to that server, stop it before starting another, or use a different --base-dir.`,
+ cause: `A T3 Code server is already running for ${baseDir} (pid ${runtime.value.pid}, ${runtime.value.origin}). To open it, run \`${pairCommand}\` and open the pairing URL it prints. To start another server, stop this one first or use a different --base-dir.`,
});
}
}
diff --git a/apps/server/src/cli/connect.test.ts b/apps/server/src/cli/connect.test.ts
index 2a51d059df67f..4fbec456da093 100644
--- a/apps/server/src/cli/connect.test.ts
+++ b/apps/server/src/cli/connect.test.ts
@@ -3,6 +3,7 @@ import * as NodeHttp from "node:http";
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
import * as NodeServices from "@effect/platform-node/NodeServices";
+import * as HostProcess from "@t3tools/shared/HostProcess";
import * as NetService from "@t3tools/shared/Net";
import * as RelayClient from "@t3tools/shared/relayClient";
import { assert, it } from "@effect/vitest";
@@ -22,6 +23,7 @@ import {
persistServerRuntimeState,
} from "../serverRuntimeState.ts";
import { acquireRelayClientForLink } from "./connect.ts";
+import { resolveHostCliCommand } from "./invocation.ts";
const managedExecutable = {
status: "available",
@@ -59,6 +61,40 @@ it.effect("does not install the relay client when the user declines the managed
}),
);
+it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer, NetService.layer))(
+ "t3 connect next steps",
+ (it) => {
+ it.effect.each([
+ { subcommand: "status", hint: "connect link" },
+ { subcommand: "publish", hint: "connect login" },
+ ])("t3 connect $subcommand names `t3 $hint` with --base-dir", ({ subcommand, hint }) =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-connect-hint-test-" });
+
+ yield* Command.runWith(makeCli({ cloudEnabled: true }), { version: "0.0.0" })([
+ "connect",
+ subcommand,
+ "--base-dir",
+ baseDir,
+ ]);
+
+ const { command } = yield* resolveHostCliCommand(hint, ["--base-dir", baseDir]);
+ assert.include((yield* TestConsole.logLines).join("\n"), `\`${command}\``);
+ }).pipe(
+ Effect.scoped,
+ Effect.provideService(HostProcess.Environment, {}),
+ Effect.provide(
+ Layer.mergeAll(
+ ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })),
+ Layer.fresh(TestConsole.layer),
+ ),
+ ),
+ ),
+ );
+ },
+);
+
it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer, NetService.layer))(
"t3 connect unlink and status",
(it) => {
diff --git a/apps/server/src/cli/connect.ts b/apps/server/src/cli/connect.ts
index 8b3a3449dff6f..322b17242d9a9 100644
--- a/apps/server/src/cli/connect.ts
+++ b/apps/server/src/cli/connect.ts
@@ -56,7 +56,7 @@ import {
readPersistedServerRuntimeState,
} from "../serverRuntimeState.ts";
import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
-import { resolveCliCommand } from "./invocation.ts";
+import { resolveHostCliHint } from "./invocation.ts";
import * as CliService from "./service.ts";
const jsonFlag = Flag.Boolean("json").pipe(
@@ -184,7 +184,11 @@ function formatRelayClientStatus(executable: RelayClient.RelayClientStatus): Rea
}
}
-function formatCloudStatus(status: CloudCliStatus, options?: { readonly json?: boolean }): string {
+function formatCloudStatus(
+ status: CloudCliStatus,
+ commands: { readonly link: string; readonly serviceStatus: string },
+ options?: { readonly json?: boolean },
+): string {
if (options?.json) {
return JSON.stringify(status, null, 2);
}
@@ -198,11 +202,11 @@ function formatCloudStatus(status: CloudCliStatus, options?: { readonly json?: b
: "not provisioned";
const publishOnly = status.desired && status.linkMode === "publish_only";
const nextStep = !status.authenticated
- ? "Run `t3 connect link` to authorize and enable T3 Connect."
+ ? `Run \`${commands.link}\` to authorize and enable T3 Connect.`
: status.revoked
- ? "Run `t3 connect link` to link this environment again."
+ ? `Run \`${commands.link}\` to link this environment again.`
: !status.desired
- ? "Run `t3 connect link` to enable T3 Connect."
+ ? `Run \`${commands.link}\` to enable T3 Connect.`
: !status.linked
? publishOnly
? "Start T3 to provision the environment link."
@@ -227,7 +231,7 @@ function formatCloudStatus(status: CloudCliStatus, options?: { readonly json?: b
: status.reachability === null
? [
"",
- "No running server answered, so reachability was not checked. Check the background service with `t3 service status`.",
+ `No running server answered, so reachability was not checked. Check the background service with \`${commands.serviceStatus}\`.`,
]
: status.reachability.status === "reachable"
? [
@@ -667,7 +671,7 @@ const connectLinkCommand = Command.make("link", {
yield* Console.log("T3 Connect\n");
const linked = yield* linkEnvironmentForConnect(flags);
if (linked) {
- const serveCommand = yield* resolveCliCommand("serve");
+ const serveCommand = yield* resolveHostCliHint("serve", flags.baseDir);
yield* Console.log(
flags.publishOnly
? `✓ Authorized${connectedAs(linked.identity)}\n\nNext\n Start T3 to publish agent activity (no managed tunnel).`
@@ -732,7 +736,11 @@ const connectStatusCommand = Command.make("status", {
linkMode,
reachability,
};
- yield* Console.log(formatCloudStatus(status, { json: flags.json }));
+ const commands = {
+ link: yield* resolveHostCliHint("connect link", flags.baseDir),
+ serviceStatus: yield* resolveHostCliHint("service status", flags.baseDir),
+ };
+ yield* Console.log(formatCloudStatus(status, commands, { json: flags.json }));
}),
{
quietLogs: flags.json,
@@ -782,8 +790,9 @@ const connectPublishCommand = Command.make("publish", {
}
if (!(yield* tokens.hasCredential)) {
+ const loginCommand = yield* resolveHostCliHint("connect login", flags.baseDir);
yield* Console.log(
- "Run `t3 connect login` first so this environment can be authorized to publish.",
+ `Run \`${loginCommand}\` first so this environment can be authorized to publish.`,
);
return;
}
diff --git a/apps/server/src/cli/install.test.ts b/apps/server/src/cli/install.test.ts
index 80b3041d24e77..104718a568cd8 100644
--- a/apps/server/src/cli/install.test.ts
+++ b/apps/server/src/cli/install.test.ts
@@ -9,6 +9,7 @@ import * as Path from "effect/Path";
import * as TestClock from "effect/testing/TestClock";
import packageJson from "../../package.json" with { type: "json" };
+import { posixLauncherScript } from "../cloud/pinnedRuntime.ts";
import { installCli, isForegroundProcStat, isForegroundPs, offerCliInstall } from "./install.ts";
const VERSION = packageJson.version;
@@ -47,7 +48,7 @@ const setup = Effect.gen(function* () {
});
it.layer(NodeServices.layer)("t3 install", (it) => {
- it.effect("links the running runtime, records it, and never replaces another t3", () =>
+ it.effect("installs the running runtime, records it, and never replaces another t3", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
@@ -57,7 +58,7 @@ it.layer(NodeServices.layer)("t3 install", (it) => {
yield* fs.makeDirectory(path.dirname(link), { recursive: true });
yield* fs.symlink(older, link);
const installed = yield* provide(installCli());
- assert.equal(yield* fs.readLink(link), executable);
+ assert.equal(yield* fs.readFileString(link), posixLauncherScript(executable));
assert.isFalse(installed.onPath);
assert.include(installed.pathCommand, "$HOME/bin");
@@ -96,30 +97,25 @@ it.layer(NodeServices.layer)("t3 install", (it) => {
yield* fs.remove(link);
yield* fs.symlink(path.join(root, ".t3/bin/t3"), link);
yield* provide(installCli());
- assert.equal(yield* fs.readLink(link), executable);
+ assert.equal(yield* fs.readFileString(link), posixLauncherScript(executable));
- // A failed swap over our own link leaves a staging path it did not create alone.
- yield* fs.remove(link);
- yield* fs.symlink(older, link);
- const staging = `${link}.${process.pid}.tmp`;
- yield* fs.writeFileString(staging, "someone else's\n");
- const linkFailed = yield* provide(installCli()).pipe(Effect.flip);
- assert.include(linkFailed.message, "Could not link");
- assert.equal(yield* fs.readFileString(staging), "someone else's\n");
- yield* fs.remove(staging);
+ // A script an earlier install wrote is ours too.
+ yield* fs.writeFileString(link, posixLauncherScript(older));
+ yield* provide(installCli());
+ assert.equal(yield* fs.readFileString(link), posixLauncherScript(executable));
// An empty spot is created exclusively: a file that appears first is kept.
yield* fs.remove(link);
const racing = installCli().pipe(
Effect.provideService(FileSystem.FileSystem, {
...fs,
- symlink: (target, path) =>
+ link: (from, to) =>
fs
- .writeFileString(path, "#!/bin/sh\necho raced\n")
- .pipe(Effect.andThen(fs.symlink(target, path))),
+ .writeFileString(to, "#!/bin/sh\necho raced\n")
+ .pipe(Effect.andThen(fs.link(from, to))),
}),
);
- assert.include((yield* provide(racing).pipe(Effect.flip)).message, "Could not link");
+ assert.include((yield* provide(racing).pipe(Effect.flip)).message, "Could not write");
assert.equal(yield* fs.readFileString(link), "#!/bin/sh\necho raced\n");
yield* fs.remove(link);
@@ -235,7 +231,7 @@ it.layer(NodeServices.layer)("t3 install", (it) => {
yield* fs.writeFileString(path.join(runtimeDir, "install-prompt-declined"), "0.0\n");
yield* offer(true);
assert.equal(asked, 2);
- assert.equal(yield* fs.readLink(link), executable);
+ assert.equal(yield* fs.readFileString(link), posixLauncherScript(executable));
yield* fs.remove(path.join(runtimeDir, "install-prompt-declined"));
yield* offer(true);
diff --git a/apps/server/src/cli/install.ts b/apps/server/src/cli/install.ts
index 9052cfa9dcffc..0a7bfc3228903 100644
--- a/apps/server/src/cli/install.ts
+++ b/apps/server/src/cli/install.ts
@@ -16,7 +16,9 @@ import packageJson from "../../package.json" with { type: "json" };
import {
generatedWindowsShimTarget,
isVersionExecutable,
+ readPosixLauncherTarget,
recordPinnedRuntimeLauncher,
+ writePosixLauncher,
} from "../cloud/pinnedRuntime.ts";
import { detectCliRunner, resolveCliCommand, resolveEntryPath } from "./invocation.ts";
@@ -42,7 +44,7 @@ const standaloneRuntime = Effect.gen(function* () {
return Option.some({ executable, versionsDir, runtimeDir });
});
-/** Links this runtime as the `t3` command the way the install scripts do, replacing only our own link. */
+/** Installs this runtime as the `t3` command the way the install scripts do, replacing only our own launcher. */
export const installCli = Effect.fn("cli.install.install")(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
@@ -88,7 +90,10 @@ export const installCli = Effect.fn("cli.install.install")(function* () {
Effect.flatMap((target) =>
fs.realPath(link).pipe(Effect.orElseSucceed(() => path.resolve(binDir, target))),
),
+ // Not a link: the script this command and the install scripts write.
+ Effect.catch(() => readPosixLauncherTarget(link)),
Effect.option,
+ Effect.map(Option.filter((target) => target !== undefined)),
);
// A dangling symlink is occupied too: writing the shim would follow it.
const occupied =
@@ -119,22 +124,10 @@ export const installCli = Effect.fn("cli.install.install")(function* () {
yield* fs
.writeFileString(link, `@echo off\r\n"${executable}" %*`, occupied ? {} : { flag: "wx" })
.pipe(Effect.mapError(failed(`Could not write ${link}.`)));
- } else if (!occupied) {
- yield* fs.symlink(executable, link).pipe(Effect.mapError(failed(`Could not link ${link}.`)));
} else {
- // Swap a temporary link into place so a running `t3` never sees the command missing.
- const staging = `${link}.${process.pid}.tmp`;
- // Clean up only a staging link this call made, never a file that was already there.
- yield* fs
- .symlink(executable, staging)
- .pipe(
- Effect.andThen(
- fs
- .rename(staging, link)
- .pipe(Effect.tapError(() => fs.remove(staging, { force: true }).pipe(Effect.ignore))),
- ),
- Effect.mapError(failed(`Could not link ${link}.`)),
- );
+ yield* writePosixLauncher({ launcher: link, executable, exclusive: !occupied }).pipe(
+ Effect.mapError(failed(`Could not write ${link}.`)),
+ );
}
// Pruning keeps what recorded launchers point at; a background service cannot see binDir otherwise.
diff --git a/apps/server/src/cli/invocation.test.ts b/apps/server/src/cli/invocation.test.ts
index 4d41bf40f1a07..8310649aa77cb 100644
--- a/apps/server/src/cli/invocation.test.ts
+++ b/apps/server/src/cli/invocation.test.ts
@@ -6,6 +6,7 @@ import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import packageJson from "../../package.json" with { type: "json" };
+import { posixLauncherScript } from "../cloud/pinnedRuntime.ts";
import {
resolveHostCliCommand,
resolveRootCliCommand,
@@ -291,7 +292,7 @@ it.layer(NodeServices.layer)("manual server installation ownership", (it) => {
}),
);
- it.effect("names the launcher symlink that started a downloaded runtime", () =>
+ it.effect("names the launcher that started a downloaded runtime", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
@@ -310,13 +311,14 @@ it.layer(NodeServices.layer)("manual server installation ownership", (it) => {
yield* fs.makeDirectory(path.join(root, "shadow-dir/t3"), { recursive: true });
yield* fs.makeDirectory(path.join(root, "shadow-file"));
yield* fs.writeFileString(path.join(root, "shadow-file/t3"), "");
- const resolve = (invokedAs: string) =>
+ const resolve = (invokedAs: string, PATH = "shadow-dir:shadow-file:bin") =>
resolveServerInstallation.pipe(
Effect.provideService(HostProcess.ExecutablePath, executable),
Effect.provideService(HostProcess.IsExecutable, true),
Effect.provideService(HostProcess.InvokedAs, invokedAs),
Effect.provideService(HostProcess.WorkingDirectory, root),
- Effect.provideService(HostProcess.Environment, { PATH: "shadow-dir:shadow-file:bin" }),
+ Effect.provideService(HostProcess.Environment, { PATH }),
+ Effect.provideService(HostProcess.HomeDirectory, root),
Effect.provideService(HostProcess.Platform, "linux"),
);
const baseDir = path.join(root, ".t3");
@@ -325,6 +327,19 @@ it.layer(NodeServices.layer)("manual server installation ownership", (it) => {
expect(yield* resolve(launcher)).toEqual({ kind: "t3-launcher", launcher, baseDir });
expect(yield* resolve(executable)).toBeNull();
expect(yield* resolve(copy)).toBeNull();
+
+ // The script launcher execs the runtime by absolute path, so argv0 names the runtime.
+ yield* fs.remove(launcher);
+ yield* fs.writeFileString(
+ launcher,
+ posixLauncherScript(path.join(root, ".t3/runtime/versions/1.0.0/t3")),
+ { mode: 0o755 },
+ );
+ expect(yield* resolve(executable, path.join(root, "bin"))).toEqual({
+ kind: "t3-launcher",
+ launcher,
+ baseDir,
+ });
}),
);
diff --git a/apps/server/src/cli/invocation.ts b/apps/server/src/cli/invocation.ts
index 71738820ccdeb..4804d44f0e324 100644
--- a/apps/server/src/cli/invocation.ts
+++ b/apps/server/src/cli/invocation.ts
@@ -9,7 +9,11 @@ import * as HostProcess from "@t3tools/shared/HostProcess";
import { resolveCommandPath } from "@t3tools/shared/shell";
import packageJson from "../../package.json" with { type: "json" };
-import { resolveLauncherPath } from "../cloud/pinnedRuntime.ts";
+import {
+ findPosixLauncher,
+ readPosixLauncherTarget,
+ resolveLauncherPath,
+} from "../cloud/pinnedRuntime.ts";
const PINNED_RUNTIME_ENTRY = /^(.*)\/runtime\/versions\/[^/]+\/t3$/;
@@ -72,12 +76,23 @@ export const resolveServerInstallation = Effect.gen(function* () {
const entry = yield* fs.realPath(yield* resolveEntryPath);
const runtime = PINNED_RUNTIME_ENTRY.exec(entry);
if (runtime) {
- const launcher = yield* resolveLauncherPath;
+ const launchedAs = yield* resolveLauncherPath;
+ if (launchedAs === undefined) return null;
+ const link = yield* fs.readLink(launchedAs).pipe(Effect.option);
+ // A launcher script execs the runtime itself, so look for the script that runs it.
+ const launcher = Option.isSome(link)
+ ? launchedAs
+ : yield* findPosixLauncher({
+ launchedAs,
+ versionsDir: path.join(runtime[1] || "/", "runtime/versions"),
+ });
+ // None for a runtime started directly, as SSH launches do, or through a copy.
if (launcher === undefined) return null;
- // Fails for a runtime started directly, as SSH launches do, or through a copy.
- const link = yield* fs.readLink(launcher);
- // Keep the home as the link spells it; `t3 update` only repoints links into that spelling.
- const linked = PINNED_RUNTIME_ENTRY.exec(path.resolve(path.dirname(launcher), link));
+ const target = Option.isSome(link)
+ ? path.resolve(path.dirname(launcher), link.value)
+ : yield* readPosixLauncherTarget(launcher);
+ // Keep the home as the launcher spells it; `t3 update` only repoints launchers into that spelling.
+ const linked = target === undefined ? null : PINNED_RUNTIME_ENTRY.exec(target);
if (!linked || (yield* fs.realPath(linked[1] || "/")) !== (runtime[1] || "/")) return null;
return {
kind: "t3-launcher",
@@ -170,7 +185,8 @@ export const resolveHostCliCommand = Effect.fn("invocation.resolveHostCliCommand
) {
const platform = yield* HostProcess.Platform;
const withArgs = (prefix: string) =>
- [prefix, ...args.map((arg) => hostShellWord(platform, arg))].join(" ");
+ // An empty subcommand names the root `t3` command.
+ [prefix.trimEnd(), ...args.map((arg) => hostShellWord(platform, arg))].join(" ");
const command = yield* resolveCliCommand(subcommand);
if (command !== `t3 ${subcommand}`) return { command: withArgs(command), launcher: false };
const onPath = yield* resolveCommandPath("t3");
@@ -200,6 +216,17 @@ export const resolveHostCliCommand = Effect.fn("invocation.resolveHostCliCommand
return { command: withArgs(`${call} ${subcommand}`), launcher: true };
});
+/** A hint's command, run against the caller's `--base-dir` when one was given. */
+export const resolveHostCliHint = (
+ subcommand: string,
+ baseDir: Option.Option,
+ args: ReadonlyArray = [],
+) =>
+ resolveHostCliCommand(subcommand, [
+ ...Option.match(baseDir, { onNone: () => [], onSome: (dir) => ["--base-dir", dir] }),
+ ...args,
+ ]).pipe(Effect.map(({ command }) => command));
+
/**
* `sudo` resets PATH on most distributions, which drops a user-installed Node
* (nvm, fnm, a tarball) and with it `npx` or a global `t3`, so the command
diff --git a/apps/server/src/cli/pair.test.ts b/apps/server/src/cli/pair.test.ts
index d7cf94ebc6449..cd4afef894457 100644
--- a/apps/server/src/cli/pair.test.ts
+++ b/apps/server/src/cli/pair.test.ts
@@ -65,7 +65,7 @@ describe("pair base URL selection", () => {
publicUrl: "https://t3.example.com/",
devUrl: "http://localhost:5733/",
};
- expect(resolveDirectPairingBaseUrl(state)).toBe("https://t3.example.com/");
+ expect(resolveDirectPairingBaseUrl(state, "linux")).toBe("https://t3.example.com/");
});
});
@@ -666,6 +666,72 @@ describe("t3 pair", () => {
assert.include(String(error), "127.0.0.2");
}).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
);
+
+ // regression: #37459 - on Linux without an operator, tailscaled refuses Serve config
+ // from a normal user, and the CLI must say how to fix it.
+ it.effect("explains the operator fix when Tailscale denies the Serve config", () =>
+ Effect.gen(function* () {
+ const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-pair-remote-"));
+ yield* persistServerRuntimeState({
+ path: NodePath.join(baseDir, "userdata", "server-runtime.json"),
+ state: yield* makePersistedServerRuntimeState({
+ config: { host: "127.0.0.1", devUrl: undefined },
+ port: 3773,
+ }),
+ });
+ const spawner = ChildProcessSpawner.make((command) => {
+ const { args } = command as unknown as { readonly args: ReadonlyArray