diff --git a/.github/scripts/pr-limits.cjs b/.github/scripts/pr-limits.cjs
index 77c09785e410..f3eb528a0804 100644
--- a/.github/scripts/pr-limits.cjs
+++ b/.github/scripts/pr-limits.cjs
@@ -100,14 +100,22 @@ function parseExemptions(text) {
}
// VOUCHED.td: one `github:login` per line, `#` comments, and `-github:login reason` to denounce.
-function vouchedLogins(text) {
- const logins = new Set();
+// A login listed both ways is an error: pr-vouch.yml's action reads its first line and
+// issue-vouch.yml its last, so no answer here would agree with both labels.
+function parseVouchList(text) {
+ const vouched = new Set();
+ const denounced = new Set();
for (const raw of text.split("\n")) {
- const entry = raw.trim().split(/\s+/)[0];
- if (entry.startsWith("github:")) logins.add(entry.slice("github:".length).toLowerCase());
+ const match = /^(-?)github:(\S+)/.exec(raw.trim());
+ if (!match) continue;
+ const login = match[2].toLowerCase();
+ const [listed, other] = match[1] ? [denounced, vouched] : [vouched, denounced];
+ if (other.has(login))
+ throw new Error(`${VOUCHED_PATH}: ${login} is both vouched and denounced`);
+ listed.add(login);
}
- if (logins.size === 0) throw new Error(`${VOUCHED_PATH}: no entries`);
- return logins;
+ if (vouched.size === 0) throw new Error(`${VOUCHED_PATH}: no entries`);
+ return { vouched, denounced };
}
function labeledAt(pr, name) {
@@ -278,7 +286,8 @@ async function enforceOpenLimit({ github, context, core, dryRun }) {
// lookups as "not vouched". Every read below throws on failure, and a throw closes nothing.
if (pr.user.type === "Bot") return;
if (parseExemptions(fs.readFileSync(EXEMPTIONS_PATH, "utf8")).has(author.toLowerCase())) return;
- if (vouchedLogins(fs.readFileSync(VOUCHED_PATH, "utf8")).has(author.toLowerCase())) return;
+ const { vouched, denounced } = parseVouchList(fs.readFileSync(VOUCHED_PATH, "utf8"));
+ if (vouched.has(author.toLowerCase())) return;
const { data: access } = await github.rest.repos.getCollaboratorPermissionLevel({
...context.repo,
username: author,
@@ -289,6 +298,21 @@ async function enforceOpenLimit({ github, context, core, dryRun }) {
const reopened = context.payload.action === "reopened";
if (reopened && context.payload.sender.login.toLowerCase() !== author.toLowerCase()) return;
+ if (denounced.has(author.toLowerCase())) {
+ if (dryRun) {
+ core.notice(`Dry run. PR #${pr.number} would close: ${author} is denounced.`);
+ return;
+ }
+ await closeWithComment(
+ github,
+ context,
+ pr.number,
+ `Closing: ${author} is banned from contributing here, so this PR will not be reviewed. See [bans](${guideLink(context, "bans")}).`,
+ );
+ core.info(`PR #${pr.number}: closed, ${author} is denounced.`);
+ return;
+ }
+
const q = `repo:${context.repo.owner}/${context.repo.repo} is:pr is:open author:${author} sort:created-asc`;
const { search } = await read(github, AUTHOR_OPEN_PRS_QUERY, { q });
// A new PR counts only the older ones, so two opened together cannot close each other.
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 63e71dc1e250..0c886bd49338 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -115,6 +115,9 @@ the open PR limit.
- If you make our lives harder as reviewers and maintainers, you will be banned. Examples are repeated
pings, a fight over a closure, and a second account to get around a limit.
+A banned account is denounced in [.github/VOUCHED.td](.github/VOUCHED.td). Any issue or PR it opens
+is closed when it is opened.
+
## When your PR is closed
diff --git a/apps/desktop/src/app/CodexAuthCallback.test.ts b/apps/desktop/src/app/CodexAuthCallback.test.ts
index 6d8a905885ac..8d69dee35850 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 0e7f949bc042..f69bf965d005 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 206a143128a8..207aa17739e5 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 5dfde9103f15..b58b583fd6cd 100644
--- a/apps/desktop/src/app/DesktopConnectionCatalogStore.test.ts
+++ b/apps/desktop/src/app/DesktopConnectionCatalogStore.test.ts
@@ -300,4 +300,66 @@ describe("DesktopConnectionCatalogStore", () => {
assert.deepStrictEqual(yield* store.get, Option.some('{"schemaVersion":1,"targets":[]}'));
}).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);
+
+ yield* store.get;
+ 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 3240df3636e3..5db49e5f9504 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";
@@ -45,6 +46,9 @@ const RuntimeConnectionCatalogDocumentJson = Schema.fromJsonString(
const encodeRuntimeConnectionCatalogDocumentJson = Schema.encodeEffect(
RuntimeConnectionCatalogDocumentJson,
);
+const decodeRuntimeConnectionCatalogDocumentJson = Schema.decodeEffect(
+ RuntimeConnectionCatalogDocumentJson,
+);
const DesktopConnectionCatalogStoreWriteOperation = Schema.Literals([
"create-temporary-file-name",
@@ -52,6 +56,7 @@ const DesktopConnectionCatalogStoreWriteOperation = Schema.Literals([
"create-directory",
"write-temporary-file",
"replace-catalog-file",
+ "keep-unreadable-catalog",
]);
const DesktopConnectionCatalogStoreMigrationOperation = Schema.Literals([
@@ -395,6 +400,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,
) {
@@ -470,26 +526,13 @@ export const make = Effect.gen(function* () {
if (!(yield* encryptionAvailable)) {
return Option.none();
}
- const decrypted = yield* decodeSecretBytes(catalogPath, document.value.encryptedCatalog).pipe(
- Effect.flatMap((encryptedCatalog) =>
- safeStorage.decryptString(encryptedCatalog).pipe(
- Effect.mapError(
- (cause) =>
- new DesktopConnectionCatalogStoreProtectionError({
- operation: "decrypt-catalog",
- catalogPath,
- cause,
- }),
- ),
- ),
- ),
- );
- return Option.some(decrypted);
+ return Option.some(yield* decryptDocument(document.value));
}).pipe(Effect.withSpan("desktop.connectionCatalogStore.get")),
set: Effect.fn("desktop.connectionCatalogStore.set")(function* (catalog) {
if (!(yield* encryptionAvailable)) {
return false;
}
+ yield* keepUnreadableCatalog;
yield* writeCatalog(catalog);
return true;
}),
diff --git a/apps/desktop/src/app/DesktopStartupRecovery.ts b/apps/desktop/src/app/DesktopStartupRecovery.ts
index c8228183aad9..e6c210043cf2 100644
--- a/apps/desktop/src/app/DesktopStartupRecovery.ts
+++ b/apps/desktop/src/app/DesktopStartupRecovery.ts
@@ -217,7 +217,6 @@ export const listen: Effect.Effect<
const download = yield* updates.download;
if (!download.completed) return;
}
- // Waits for a running background check; plain install would refuse.
yield* updates.installPrepared(current.version);
return;
}
diff --git a/apps/desktop/src/app/stdioErrors.test.ts b/apps/desktop/src/app/stdioErrors.test.ts
new file mode 100644
index 000000000000..ccfa3ed95117
--- /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 000000000000..b23c0e89e79a
--- /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 25b30f82951f..ab47026875ab 100644
--- a/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts
+++ b/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts
@@ -422,7 +422,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";
@@ -443,8 +443,8 @@ describe("DesktopBackendConfiguration", () => {
});
return { ok: true, linuxAppRoot };
},
- probeRuntime: (_distro, root) => {
- observedProbeRoots.push(root);
+ probeRuntime: () => {
+ probeCount += 1;
return { ok: true, resolvedPath };
},
ensureNodePty: () => {
@@ -465,7 +465,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"),
@@ -560,10 +560,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(
@@ -575,9 +575,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);
@@ -590,7 +590,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`);
@@ -615,7 +615,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 80050b04ede6..811b25e0ec35 100644
--- a/apps/desktop/src/backend/DesktopBackendConfiguration.ts
+++ b/apps/desktop/src/backend/DesktopBackendConfiguration.ts
@@ -443,7 +443,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 {
@@ -456,7 +456,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 06a1f768f4bd..ff5b7b8c08e4 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 4acaa8a3c18b..8b4f154b5d4d 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 8e9f4320c08c..005a1cde1224 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 d69e1ce1427f..62c811996b1a 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 e82e3afea730..c15ce3932bb8 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 6c7d24623d40..89aa3cd2a678 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 000000000000..b38d7bbb3ae4
--- /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 000000000000..6a7f290d6fd8
--- /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/ipc/DesktopIpcHandlers.ts b/apps/desktop/src/ipc/DesktopIpcHandlers.ts
index a1c041f10c20..7f06ca4b77e9 100644
--- a/apps/desktop/src/ipc/DesktopIpcHandlers.ts
+++ b/apps/desktop/src/ipc/DesktopIpcHandlers.ts
@@ -46,6 +46,7 @@ import {
getWindowFullscreenState,
openExternal,
readMedia,
+ restartAudioService,
openSystemSettings,
checkSystemPermission,
pasteAsText,
@@ -111,6 +112,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 a5b284722f9b..43f2e3b5b615 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,6 +140,8 @@ 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";
// coil: fork-owned update delivery. Distinct from the `desktop:update-*` channels above, which
// belong to upstream's electron-updater surface — the two must never share a channel, or a build
// with both enabled would have each answering the other's messages.
diff --git a/apps/desktop/src/ipc/methods/preview.ts b/apps/desktop/src/ipc/methods/preview.ts
index cc810fee072a..757e1e463f53 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 fbde6a409f3f..d7f432815d2a 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 fbeda6d2f2dc..de202529c411 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 cee92e1ead38..38887ec71d90 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 0bcbadfd8977..22b4a326efe5 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 b233d6638b50..18dc0c373008 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) => {
@@ -431,6 +432,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 92ab35320dab..eb4dd3143eef 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 63fef9fb3c80..91cbfa03aac7 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 20a35752ed97..6ecd546a1ad5 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/DesktopBrowserHost.test.ts b/apps/desktop/src/preview/DesktopBrowserHost.test.ts
index cf6c7736f81d..8e96129293fc 100644
--- a/apps/desktop/src/preview/DesktopBrowserHost.test.ts
+++ b/apps/desktop/src/preview/DesktopBrowserHost.test.ts
@@ -26,6 +26,11 @@ const decodeCdpMessage = Schema.decodeUnknownSync(
),
);
const key = { threadId: "thread-1", tabId: "tab-1" };
+
+/** A host whose client already draws `key` at full detail, so its screenshots go out at once. */
+const makeDrawnHost = Effect.tap(DesktopBrowserHost.make, (host) =>
+ Effect.sync(() => host.setCaptureDrawn(key, true)),
+);
/** Sends a page command whose id the fake debugger records as it receives it. */
const command = (
host: DesktopBrowserHost.DesktopBrowserHost["Service"],
@@ -172,7 +177,7 @@ const watchPainting = (host: DesktopBrowserHost.DesktopBrowserHost["Service"]) =
describe("DesktopBrowserHost", () => {
it.effect("announces tabs already attached to a backend that starts later", () =>
Effect.gen(function* () {
- const host = yield* DesktopBrowserHost.make;
+ const host = yield* makeDrawnHost;
host.attach(key, makeDebuggee().tab);
expect(yield* takeEvents(host, 1)).toEqual([{ type: "attached", ...key }]);
@@ -182,7 +187,7 @@ describe("DesktopBrowserHost", () => {
it.effect("announces a guest still loading its first page only once that page is up", () =>
Effect.gen(function* () {
- const host = yield* DesktopBrowserHost.make;
+ const host = yield* makeDrawnHost;
const loading = makeDebuggee({ loading: true });
const other = { ...key, tabId: "tab-2" };
const reader = yield* takeEvents(host, 3).pipe(Effect.forkScoped);
@@ -205,7 +210,7 @@ describe("DesktopBrowserHost", () => {
"keeps a loading guest unannounced across a replaced navigation and a new backend",
() =>
Effect.gen(function* () {
- const host = yield* DesktopBrowserHost.make;
+ const host = yield* makeDrawnHost;
const loading = makeDebuggee({ loading: true });
const other = { ...key, tabId: "tab-2" };
host.attach(key, loading.tab);
@@ -227,7 +232,7 @@ describe("DesktopBrowserHost", () => {
"announces a first page that never comes up, but never a tab closed or destroyed first",
() =>
Effect.gen(function* () {
- const host = yield* DesktopBrowserHost.make;
+ const host = yield* makeDrawnHost;
const closed = { ...key, tabId: "tab-2" };
const destroyed = { ...key, tabId: "tab-3" };
const destroyedGuest = makeDebuggee({ loading: true });
@@ -247,7 +252,7 @@ describe("DesktopBrowserHost", () => {
it.effect("re-sends shown to a backend that starts later and when a tab attaches again", () =>
Effect.gen(function* () {
- const host = yield* DesktopBrowserHost.make;
+ const host = yield* makeDrawnHost;
host.attach(key, makeDebuggee().tab);
host.setShown(key, true);
const reader = yield* takeEvents(host, 5).pipe(Effect.forkScoped);
@@ -268,7 +273,7 @@ describe("DesktopBrowserHost", () => {
it.effect("replays an explicit hidden report before announcing another tab", () =>
Effect.gen(function* () {
- const host = yield* DesktopBrowserHost.make;
+ const host = yield* makeDrawnHost;
const other = { ...key, tabId: "tab-2" };
host.setShown(key, false);
host.attach(key, makeDebuggee().tab);
@@ -285,7 +290,7 @@ describe("DesktopBrowserHost", () => {
it.effect("drops replies from a relay the server released", () =>
Effect.gen(function* () {
- const host = yield* DesktopBrowserHost.make;
+ const host = yield* makeDrawnHost;
const debuggee = makeDebuggee();
host.attach(key, debuggee.tab);
const reader = yield* takeEvents(host, 2).pipe(Effect.forkScoped);
@@ -313,7 +318,7 @@ describe("DesktopBrowserHost", () => {
it.effect("sends a page one screenshot at a time", () =>
Effect.gen(function* () {
- const host = yield* DesktopBrowserHost.make;
+ const host = yield* makeDrawnHost;
const debuggee = makeDebuggee();
host.attach(key, debuggee.tab);
const replies = yield* watchReplies(host);
@@ -330,9 +335,38 @@ describe("DesktopBrowserHost", () => {
}),
);
+ it.effect(
+ "sends a screenshot once the client draws the guest at full detail, or soon after",
+ () =>
+ Effect.gen(function* () {
+ const host = yield* DesktopBrowserHost.make;
+ const debuggee = makeDebuggee();
+ host.attach(key, debuggee.tab);
+ const replies = yield* watchReplies(host);
+
+ yield* command(host, 1, "Page.captureScreenshot");
+ yield* settle;
+ expect(debuggee.sent).toEqual([]);
+ host.setCaptureDrawn(key, true);
+ yield* settle;
+ expect(debuggee.sent).toEqual([1]);
+ debuggee.releaseFirst();
+ expect(yield* Queue.take(replies)).toBe(1);
+
+ // A client that never draws, such as a hidden window, only delays the capture.
+ host.setCaptureDrawn(key, false);
+ yield* command(host, 2, "Page.captureScreenshot");
+ yield* settle;
+ expect(debuggee.sent).toEqual([1]);
+ yield* TestClock.adjust("1 second");
+ yield* settle;
+ expect(debuggee.sent).toEqual([1, 2]);
+ }).pipe(Effect.scoped),
+ );
+
it.effect("stops waiting on a screenshot the page navigated away from", () =>
Effect.gen(function* () {
- const host = yield* DesktopBrowserHost.make;
+ const host = yield* makeDrawnHost;
const debuggee = makeDebuggee();
host.attach(key, debuggee.tab);
const replies = yield* watchReplies(host);
@@ -357,7 +391,7 @@ describe("DesktopBrowserHost", () => {
it.effect("drops screenshots a released relay left waiting", () =>
Effect.gen(function* () {
- const host = yield* DesktopBrowserHost.make;
+ const host = yield* makeDrawnHost;
const debuggee = makeDebuggee();
host.attach(key, debuggee.tab);
@@ -377,7 +411,7 @@ describe("DesktopBrowserHost", () => {
it.effect("emulates focus while the server drives a guest, then lets a hidden one throttle", () =>
Effect.gen(function* () {
- const host = yield* DesktopBrowserHost.make;
+ const host = yield* makeDrawnHost;
const debuggee = makeDebuggee();
host.attach(key, debuggee.tab);
@@ -408,7 +442,7 @@ describe("DesktopBrowserHost", () => {
it.effect("keeps a guest focused while a command it is running is still pending", () =>
Effect.gen(function* () {
- const host = yield* DesktopBrowserHost.make;
+ const host = yield* makeDrawnHost;
const debuggee = makeDebuggee();
host.attach(key, debuggee.tab);
const replies = yield* watchReplies(host);
@@ -429,7 +463,7 @@ describe("DesktopBrowserHost", () => {
it.effect("lets a guest throttle once Chromium can no longer answer its pending command", () =>
Effect.gen(function* () {
- const host = yield* DesktopBrowserHost.make;
+ const host = yield* makeDrawnHost;
const debuggee = makeDebuggee();
host.attach(key, debuggee.tab);
@@ -451,7 +485,7 @@ describe("DesktopBrowserHost", () => {
it.effect("keeps a guest focused for the screenshot a navigation lets start", () =>
Effect.gen(function* () {
- const host = yield* DesktopBrowserHost.make;
+ const host = yield* makeDrawnHost;
const debuggee = makeDebuggee();
host.attach(key, debuggee.tab);
@@ -467,7 +501,7 @@ describe("DesktopBrowserHost", () => {
it.effect("never sends a screenshot a navigation superseded while focus was changing", () =>
Effect.gen(function* () {
- const host = yield* DesktopBrowserHost.make;
+ const host = yield* makeDrawnHost;
const debuggee = makeDebuggee({ deferFocus: true });
host.attach(key, debuggee.tab);
@@ -484,7 +518,7 @@ describe("DesktopBrowserHost", () => {
it.effect("keeps a guest focused when its turn starts after the agent's first command", () =>
Effect.gen(function* () {
- const host = yield* DesktopBrowserHost.make;
+ const host = yield* makeDrawnHost;
const debuggee = makeDebuggee();
host.attach(key, debuggee.tab);
const turn = (active: boolean) =>
@@ -506,7 +540,7 @@ describe("DesktopBrowserHost", () => {
it.effect("lets a guest throttle through a turn that only sent it housekeeping", () =>
Effect.gen(function* () {
- const host = yield* DesktopBrowserHost.make;
+ const host = yield* makeDrawnHost;
const debuggee = makeDebuggee();
host.attach(key, debuggee.tab);
yield* host.handleCommandLine(
@@ -535,7 +569,7 @@ describe("DesktopBrowserHost", () => {
it.effect("keeps a guest the agent used focused through its turn's pauses", () =>
Effect.gen(function* () {
- const host = yield* DesktopBrowserHost.make;
+ const host = yield* makeDrawnHost;
const debuggee = makeDebuggee();
host.attach(key, debuggee.tab);
const turn = (active: boolean) =>
@@ -563,7 +597,7 @@ describe("DesktopBrowserHost", () => {
"ends a command's hold with the turn that sent it, even if Chromium never answers",
() =>
Effect.gen(function* () {
- const host = yield* DesktopBrowserHost.make;
+ const host = yield* makeDrawnHost;
const debuggee = makeDebuggee();
host.attach(key, debuggee.tab);
yield* host.handleCommandLine(
@@ -584,7 +618,7 @@ describe("DesktopBrowserHost", () => {
it.effect("ends the agent's own session's holds with its turn, but not a viewer's stream", () =>
Effect.gen(function* () {
- const host = yield* DesktopBrowserHost.make;
+ const host = yield* makeDrawnHost;
const debuggee = makeDebuggee();
host.attach(key, debuggee.tab);
const replies = yield* watchReplies(host);
@@ -617,7 +651,7 @@ describe("DesktopBrowserHost", () => {
it.effect("paints for a screenshot queued behind one its viewer abandoned mid-capture", () =>
Effect.gen(function* () {
- const host = yield* DesktopBrowserHost.make;
+ const host = yield* makeDrawnHost;
const debuggee = makeDebuggee();
host.attach(key, debuggee.tab);
const replies = yield* watchReplies(host);
@@ -655,7 +689,7 @@ describe("DesktopBrowserHost", () => {
it.effect("stops painting for a queued screenshot once its session detaches", () =>
Effect.gen(function* () {
- const host = yield* DesktopBrowserHost.make;
+ const host = yield* makeDrawnHost;
const debuggee = makeDebuggee();
host.attach(key, debuggee.tab);
const replies = yield* watchReplies(host);
@@ -694,7 +728,7 @@ describe("DesktopBrowserHost", () => {
it.effect("never sends a screenshot whose session detached while focus was changing", () =>
Effect.gen(function* () {
- const host = yield* DesktopBrowserHost.make;
+ const host = yield* makeDrawnHost;
const debuggee = makeDebuggee({ deferFocus: true });
host.attach(key, debuggee.tab);
const replies = yield* watchReplies(host);
@@ -718,7 +752,7 @@ describe("DesktopBrowserHost", () => {
it.effect("holds no focus for a screenshot still queued when the agent's turn ends", () =>
Effect.gen(function* () {
- const host = yield* DesktopBrowserHost.make;
+ const host = yield* makeDrawnHost;
const debuggee = makeDebuggee();
host.attach(key, debuggee.tab);
const painting = yield* watchPainting(host);
@@ -748,7 +782,7 @@ describe("DesktopBrowserHost", () => {
it.effect("lets a guest throttle when Chromium refuses a viewer's screencast", () =>
Effect.gen(function* () {
- const host = yield* DesktopBrowserHost.make;
+ const host = yield* makeDrawnHost;
const debuggee = makeDebuggee({ refuse: (method) => method === "Page.startScreencast" });
host.attach(key, debuggee.tab);
const replies = yield* watchReplies(host);
@@ -769,7 +803,7 @@ describe("DesktopBrowserHost", () => {
it.effect("lets a guest throttle after a person's input through a viewer that then closed", () =>
Effect.gen(function* () {
- const host = yield* DesktopBrowserHost.make;
+ const host = yield* makeDrawnHost;
const debuggee = makeDebuggee();
host.attach(key, debuggee.tab);
const replies = yield* watchReplies(host);
@@ -798,7 +832,7 @@ describe("DesktopBrowserHost", () => {
it.effect("keeps a page's screencast when a child session's screencast is refused", () =>
Effect.gen(function* () {
- const host = yield* DesktopBrowserHost.make;
+ const host = yield* makeDrawnHost;
const debuggee = makeDebuggee({
refuse: (method, sessionId) => method === "Page.startScreencast" && sessionId !== undefined,
});
@@ -820,7 +854,7 @@ describe("DesktopBrowserHost", () => {
it.effect("ignores a screencast that arrives on a session after it detached", () =>
Effect.gen(function* () {
- const host = yield* DesktopBrowserHost.make;
+ const host = yield* makeDrawnHost;
const debuggee = makeDebuggee();
host.attach(key, debuggee.tab);
const replies = yield* watchReplies(host);
@@ -846,7 +880,7 @@ describe("DesktopBrowserHost", () => {
it.effect("lets a guest throttle once the session waiting on its command detaches", () =>
Effect.gen(function* () {
- const host = yield* DesktopBrowserHost.make;
+ const host = yield* makeDrawnHost;
const debuggee = makeDebuggee();
host.attach(key, debuggee.tab);
const replies = yield* watchReplies(host);
@@ -873,7 +907,7 @@ describe("DesktopBrowserHost", () => {
it.effect("never sends a screenshot queued by a session that has since detached", () =>
Effect.gen(function* () {
- const host = yield* DesktopBrowserHost.make;
+ const host = yield* makeDrawnHost;
const debuggee = makeDebuggee();
host.attach(key, debuggee.tab);
const replies = yield* watchReplies(host);
@@ -904,7 +938,7 @@ describe("DesktopBrowserHost", () => {
it.effect("keeps a streamed guest focused until its screencast ends", () =>
Effect.gen(function* () {
- const host = yield* DesktopBrowserHost.make;
+ const host = yield* makeDrawnHost;
const debuggee = makeDebuggee();
host.attach(key, debuggee.tab);
@@ -933,7 +967,7 @@ describe("DesktopBrowserHost", () => {
it.effect("keeps a guest focused while any of its screencasts runs", () =>
Effect.gen(function* () {
- const host = yield* DesktopBrowserHost.make;
+ const host = yield* makeDrawnHost;
const debuggee = makeDebuggee();
host.attach(key, debuggee.tab);
const replies = yield* watchReplies(host);
@@ -965,7 +999,7 @@ describe("DesktopBrowserHost", () => {
it.effect("paints a hidden guest only while the screenshot it is taking is pending", () =>
Effect.gen(function* () {
- const host = yield* DesktopBrowserHost.make;
+ const host = yield* makeDrawnHost;
const debuggee = makeDebuggee();
host.attach(key, debuggee.tab);
const painting = yield* watchPainting(host);
@@ -991,7 +1025,7 @@ describe("DesktopBrowserHost", () => {
it.effect("stops painting for a screenshot Chromium never answers once its document goes", () =>
Effect.gen(function* () {
- const host = yield* DesktopBrowserHost.make;
+ const host = yield* makeDrawnHost;
const debuggee = makeDebuggee();
host.attach(key, debuggee.tab);
const painting = yield* watchPainting(host);
@@ -1036,7 +1070,7 @@ describe("DesktopBrowserHost", () => {
it.effect("paints a streamed guest until its last screencast ends", () =>
Effect.gen(function* () {
- const host = yield* DesktopBrowserHost.make;
+ const host = yield* makeDrawnHost;
const debuggee = makeDebuggee();
host.attach(key, debuggee.tab);
const replies = yield* watchReplies(host);
@@ -1243,7 +1277,7 @@ describe("DesktopBrowserHost", () => {
it.effect("saves a server tab's download under its CDP guid where the server asked", () =>
Effect.gen(function* () {
- const host = yield* DesktopBrowserHost.make;
+ const host = yield* makeDrawnHost;
const debuggee = makeDebuggee();
host.attach(key, debuggee.tab);
const replies = yield* watchReplies(host);
@@ -1278,7 +1312,7 @@ describe("DesktopBrowserHost", () => {
it.effect("tells a download the person clicked from one the agent's input started", () =>
Effect.gen(function* () {
- const host = yield* DesktopBrowserHost.make;
+ const host = yield* makeDrawnHost;
const debuggee = makeDebuggee();
host.attach(key, debuggee.tab);
@@ -1342,7 +1376,7 @@ describe("DesktopBrowserHost", () => {
it.effect("detaches only the tab whose CDP event is too large to relay", () =>
Effect.gen(function* () {
- const host = yield* DesktopBrowserHost.make;
+ const host = yield* makeDrawnHost;
const tabs = [makeDebuggee({ deferFocus: true }), makeDebuggee()];
const send = vi.spyOn(tabs[0]!.tab.debugger, "sendCommand");
const keys = [key, { threadId: "thread-2", tabId: "tab-2" }];
diff --git a/apps/desktop/src/preview/DesktopBrowserHost.ts b/apps/desktop/src/preview/DesktopBrowserHost.ts
index e0326b7b76ec..ce5d7074a786 100644
--- a/apps/desktop/src/preview/DesktopBrowserHost.ts
+++ b/apps/desktop/src/preview/DesktopBrowserHost.ts
@@ -30,6 +30,8 @@ const AGENT_INPUT_WINDOW_MS = 5_000;
/** A viewer's pointer travelling over the stream activates nothing on the page. */
const POINTER_TRAVEL = new Set(["mouseMoved", "mouseWheel"]);
const FOCUS_IDLE = "5 seconds";
+/** How long a screenshot waits for the client to draw its guest at full detail. */
+const CAPTURE_DRAW_WAIT = "1 second";
/** Well inside the server's 10 s DESKTOP_ATTACH_TIMEOUT, for a first page that never reports it is up. */
const FIRST_PAGE_TIMEOUT = "5 seconds";
const ERR_ABORTED = -3;
@@ -101,6 +103,8 @@ export class DesktopBrowserHost extends Context.Service<
readonly detach: (key: DesktopBrowserTabKey) => void;
readonly loadFailed: (key: DesktopBrowserTabKey, failure: PreviewAutomationLoadError) => void;
readonly setShown: (key: DesktopBrowserTabKey, shown: boolean | undefined) => void;
+ /** Whether the client draws the guest at full detail while it is captured. */
+ readonly setCaptureDrawn: (key: DesktopBrowserTabKey, drawn: boolean | undefined) => void;
readonly humanStartedDownload: (source: Electron.WebContents) => boolean;
/** Whether what the page does now follows the agent's input, not a viewer's. */
readonly agentLedPage: (source: Electron.WebContents) => boolean;
@@ -138,6 +142,8 @@ export const make = Effect.gen(function* () {
// Kept apart from attachment: the renderer can show a webview before its debugger attaches,
// and the server forgets `shown` on detach, for example while DevTools holds the debugger.
const shownTabs = new Map();
+ const drawnTabs = new Set();
+ const drawWaiters = new Map void>>();
const emit = (event: DesktopBrowserEventType) => runFork(PubSub.publish(outbox, event));
const nextScreenshot = (tab: AttachedTab) => {
@@ -266,12 +272,32 @@ export const make = Effect.gen(function* () {
});
};
+ /**
+ * A scaled guest rasters at its on-screen size until the client draws it at full detail,
+ * and a screenshot taken before that copies the blurred frame. A client that cannot draw
+ * (a hidden window, say) only delays the capture.
+ */
+ const whenDrawn = (tab: AttachedTab) =>
+ new Promise((resolve) => {
+ const id = keyOf(tab.key);
+ const waiters = drawWaiters.get(id) ?? new Set();
+ drawWaiters.set(id, waiters);
+ const done = () => {
+ waiters.delete(done);
+ if (waiters.size === 0 && drawWaiters.get(id) === waiters) drawWaiters.delete(id);
+ resolve();
+ };
+ waiters.add(done);
+ runFork(Effect.sleep(CAPTURE_DRAW_WAIT).pipe(Effect.andThen(Effect.sync(done))));
+ });
+
/** Chromium answers a capture, and frees its wake lock, only once the guest paints a frame. */
const paintUntilAnswered = (tab: AttachedTab, send: () => Promise) => {
const sent = {};
tab.capturing.add(sent);
syncPainting(tab);
- return send().finally(() => {
+ // Sent at once when already drawn, so it keeps its place among the commands after it.
+ return (drawnTabs.has(keyOf(tab.key)) ? send() : whenDrawn(tab).then(send)).finally(() => {
tab.capturing.delete(sent);
syncPainting(tab);
});
@@ -368,12 +394,15 @@ export const make = Effect.gen(function* () {
// Waits for focus emulation; insertText and other non-CDP input would not queue behind it.
const forward = (current?: () => boolean) => {
const change = tab.focusChange;
- const run = () =>
- tab.relay !== relay || (current !== undefined && !current())
+ const stale = () => tab.relay !== relay || (current !== undefined && !current());
+ const sendUnlessStale = () =>
+ stale()
? Promise.reject(new Error("The page this screenshot was for has moved on."))
- : current === undefined
- ? send(method, params, sessionId)
- : paintUntilAnswered(tab, () => send(method, params, sessionId));
+ : send(method, params, sessionId);
+ const run = () =>
+ current === undefined || stale()
+ ? sendUnlessStale()
+ : paintUntilAnswered(tab, sendUnlessStale);
return change === null ? run() : change.then(run);
};
return method === "Page.captureScreenshot"
@@ -587,6 +616,17 @@ export const make = Effect.gen(function* () {
if (tabs.get(id)?.stopWaiting === null) emit({ type: "shown", ...key, shown });
};
+ const setCaptureDrawn = (key: DesktopBrowserTabKey, drawn: boolean | undefined) => {
+ const id = keyOf(key);
+ if (!drawn) {
+ drawnTabs.delete(id);
+ return;
+ }
+ drawnTabs.add(id);
+ for (const done of drawWaiters.get(id) ?? []) done();
+ drawWaiters.delete(id);
+ };
+
const loadFailed: DesktopBrowserHost["Service"]["loadFailed"] = (key, failure) => {
if (tabs.has(keyOf(key))) emit({ type: "loadFailed", ...key, ...failure });
};
@@ -663,6 +703,7 @@ export const make = Effect.gen(function* () {
detach,
loadFailed,
setShown,
+ setCaptureDrawn,
placeDownload,
humanStartedDownload,
agentLedPage,
diff --git a/apps/desktop/src/preview/Manager.test.ts b/apps/desktop/src/preview/Manager.test.ts
index 64b584fbed7f..2091ff3c7f8f 100644
--- a/apps/desktop/src/preview/Manager.test.ts
+++ b/apps/desktop/src/preview/Manager.test.ts
@@ -617,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) =>
@@ -658,6 +684,7 @@ describe("PreviewManager", () => {
attach: () => {},
detach: () => {},
setShown: () => {},
+ setCaptureDrawn: () => {},
loadFailed: () => {},
humanStartedDownload: () => true,
agentLedPage: () => false,
@@ -2436,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())),
diff --git a/apps/desktop/src/preview/Manager.ts b/apps/desktop/src/preview/Manager.ts
index 957a00d6a4b6..32ac876996c8 100644
--- a/apps/desktop/src/preview/Manager.ts
+++ b/apps/desktop/src/preview/Manager.ts
@@ -1827,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(
[
@@ -2635,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);
}
}
});
@@ -3503,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(
@@ -3517,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({
@@ -3715,6 +3728,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
setAnnotationSendEnabled,
setAudioMuted,
setShown,
+ setCaptureDrawn,
setColorScheme,
setMainWindow,
setForwardedShortcuts: (shortcuts: ReadonlyArray) =>
@@ -3931,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,
@@ -4093,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 3486c296da51..7808682dfd82 100644
--- a/apps/desktop/src/shell/DesktopShellEnvironment.test.ts
+++ b/apps/desktop/src/shell/DesktopShellEnvironment.test.ts
@@ -2,6 +2,7 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, describe, it } from "@effect/vitest";
import * as HostProcess from "@t3tools/shared/HostProcess";
+import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as Deferred from "effect/Deferred";
@@ -62,6 +63,26 @@ function makeProcess(output: string, exitCode = 0): ChildProcessSpawner.ChildPro
});
}
+function makeSlowProcess(
+ output: string,
+ delay: Duration.Input,
+): ChildProcessSpawner.ChildProcessHandle {
+ const stdout = Stream.fromEffect(Effect.as(Effect.sleep(delay), textEncoder.encode(output)));
+ return ChildProcessSpawner.makeHandle({
+ pid: ChildProcessSpawner.ProcessId(125),
+ stdout,
+ stderr: Stream.empty,
+ all: stdout,
+ exitCode: Effect.as(Effect.sleep(delay), ChildProcessSpawner.ExitCode(0)),
+ isRunning: Effect.succeed(true),
+ kill: () => Effect.void,
+ stdin: Sink.drain,
+ getInputFd: () => Sink.drain,
+ getOutputFd: () => Stream.empty,
+ unref: Effect.succeed(Effect.void),
+ });
+}
+
function makeHungProcess(): ChildProcessSpawner.ChildProcessHandle {
return ChildProcessSpawner.makeHandle({
pid: ChildProcessSpawner.ProcessId(124),
@@ -670,6 +691,129 @@ describe("DesktopShellEnvironment", () => {
}),
);
+ it.effect("retries the user's shell when only the fallback shell answered", () =>
+ Effect.gen(function* () {
+ const env: NodeJS.ProcessEnv = { SHELL: "/usr/bin/fish", PATH: "/usr/bin" };
+ const commands: string[] = [];
+ let fishReady = false;
+ yield* runShellEnvironment({
+ env,
+ platform: "linux",
+ handler: (command) => {
+ if (command._tag !== "StandardCommand") return "";
+ commands.push(command.command);
+ if (command.command !== "/usr/bin/fish") return envOutput({ PATH: "/usr/bin" });
+ return fishReady
+ ? envOutput({ PATH: "/fish/bin:/usr/bin" })
+ : { output: "", exitCode: 7 };
+ },
+ use: (service) =>
+ Effect.gen(function* () {
+ assert.isTrue(yield* service.awaitDiscovery);
+ assert.equal(env.PATH, "/usr/bin");
+ // The Linux probe checks the D-Bus socket on the real filesystem, which the clock does not await.
+ const published = yield* service.updates.pipe(
+ Stream.filter((snapshot) => snapshot.environment.PATH === "/fish/bin:/usr/bin"),
+ Stream.runHead,
+ Effect.forkChild({ startImmediately: true }),
+ );
+
+ fishReady = true;
+ yield* TestClock.adjust("30 seconds");
+ assert.isTrue(Option.isSome(yield* Fiber.join(published)));
+ assert.equal(env.PATH, "/fish/bin:/usr/bin");
+ return true;
+ }),
+ }).pipe(Effect.provide(Logger.layer([])));
+ assert.deepEqual(commands, ["/usr/bin/fish", "/bin/bash", "/usr/bin/fish"]);
+
+ // With no user shell to wait for, the fallback's answer is final.
+ commands.length = 0;
+ yield* runShellEnvironment({
+ env: { PATH: "/usr/bin" },
+ platform: "linux",
+ handler: (command) => {
+ if (command._tag === "StandardCommand") commands.push(command.command);
+ return envOutput({ PATH: "/usr/bin" });
+ },
+ use: (service) =>
+ Effect.gen(function* () {
+ assert.isTrue(yield* service.awaitDiscovery);
+ yield* TestClock.adjust("5 minutes");
+ return true;
+ }),
+ }).pipe(Effect.provide(Logger.layer([])));
+ assert.deepEqual(commands, ["/bin/bash"]);
+ }),
+ );
+
+ it.effect("gives background retries time for a locked or slow shell, then publishes", () =>
+ Effect.gen(function* () {
+ const env: NodeJS.ProcessEnv = { SHELL: "/bin/zsh", PATH: "/usr/bin" };
+ // Startup fails fast, the first retry meets a shell blocked on a lock, the second a slow one.
+ const spawned = yield* Effect.forEach([0, 1, 2], () => Deferred.make());
+ const stopped = yield* Deferred.make();
+ let attempts = 0;
+ yield* runShellEnvironment({
+ env,
+ platform: "darwin",
+ handler: () => "",
+ processSpawner: ChildProcessSpawner.make((command) => {
+ if (command._tag !== "StandardCommand" || command.command !== "/bin/zsh") {
+ return Effect.succeed(makeProcess(""));
+ }
+ const attempt = attempts++;
+ const spawn = Deferred.succeed(spawned[attempt]!, undefined);
+ if (attempt === 0) return spawn.pipe(Effect.as(makeProcess("")));
+ if (attempt === 1) {
+ return spawn.pipe(
+ Effect.andThen(
+ Effect.acquireRelease(Effect.succeed(makeHungProcess()), () =>
+ Deferred.succeed(stopped, command.options),
+ ),
+ ),
+ );
+ }
+ return spawn.pipe(
+ Effect.as(makeSlowProcess(envOutput({ PATH: "/fresh/bin" }), "20 seconds")),
+ );
+ }),
+ use: (service) =>
+ Effect.gen(function* () {
+ assert.isFalse(yield* service.awaitDiscovery);
+ const published = yield* service.updates.pipe(
+ Stream.drop(1),
+ Stream.runHead,
+ Effect.forkChild({ startImmediately: true }),
+ );
+
+ yield* TestClock.adjust("30 seconds");
+ yield* Deferred.await(spawned[1]!);
+ // pyenv waits up to 60 s on its rehash lock before the shell continues.
+ yield* TestClock.adjust("1 minute");
+ assert.isFalse(yield* Deferred.isDone(stopped));
+ yield* TestClock.adjust("1 minute");
+ const stop = yield* Deferred.await(stopped);
+ // pyenv releases that lock in an EXIT trap, which SIGTERM runs and SIGKILL skips.
+ assert.equal(stop.killSignal, "SIGTERM");
+ assert.isAtLeast(Duration.toMillis(stop.forceKillAfter ?? 0), 5_000);
+
+ yield* TestClock.adjust("30 seconds");
+ yield* Deferred.await(spawned[2]!);
+ yield* TestClock.adjust("20 seconds");
+ const snapshot = yield* Fiber.join(published);
+ assert.equal(env.PATH, "/fresh/bin:/usr/bin");
+ assert.isTrue(Option.isSome(snapshot) && snapshot.value.discovered);
+ assert.equal(
+ Option.isSome(snapshot) ? snapshot.value.environment.PATH : undefined,
+ "/fresh/bin:/usr/bin",
+ );
+ return true;
+ }),
+ });
+ }),
+ );
+
it.effect("recovers the login-shell PATH when the first probe outlasts the timeout", () =>
Effect.gen(function* () {
const env: NodeJS.ProcessEnv = { SHELL: "/bin/zsh", PATH: "/usr/bin:/bin:/usr/sbin:/sbin" };
diff --git a/apps/desktop/src/shell/DesktopShellEnvironment.ts b/apps/desktop/src/shell/DesktopShellEnvironment.ts
index 5389d94c1e8e..351150aa4b98 100644
--- a/apps/desktop/src/shell/DesktopShellEnvironment.ts
+++ b/apps/desktop/src/shell/DesktopShellEnvironment.ts
@@ -15,6 +15,7 @@ import * as Deferred from "effect/Deferred";
import * as Path from "effect/Path";
import * as PubSub from "effect/PubSub";
import * as Ref from "effect/Ref";
+import * as Schedule from "effect/Schedule";
import * as Scope from "effect/Scope";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
@@ -28,9 +29,17 @@ import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
type EnvironmentPatch = Record;
+interface ProbeBudget {
+ readonly timeout: Duration.Duration;
+ // One longer wait for the first login shell that times out.
+ readonly slowTimeout?: Duration.Duration;
+ readonly terminateGrace: Duration.Duration;
+}
+
interface ShellEnvironmentConfig {
readonly env: NodeJS.ProcessEnv;
readonly platform: NodeJS.Platform;
+ readonly budget: ProbeBudget;
}
interface WindowsProbeOptions {
@@ -125,6 +134,20 @@ const LOGIN_SHELL_TIMEOUT = Duration.seconds(5);
const SLOW_LOGIN_SHELL_TIMEOUT = Duration.seconds(20);
const LAUNCHCTL_TIMEOUT = Duration.seconds(2);
const PROCESS_TERMINATE_GRACE = Duration.seconds(1);
+const STARTUP_PROBE: ProbeBudget = {
+ timeout: LOGIN_SHELL_TIMEOUT,
+ slowTimeout: SLOW_LOGIN_SHELL_TIMEOUT,
+ terminateGrace: PROCESS_TERMINATE_GRACE,
+};
+// Retries block nothing, so they outlast pyenv's 60 s wait on its rehash lock, and SIGTERM gets
+// time to run the exit trap that releases it. A SIGKILL leaves the lock for two minutes.
+const RETRY_PROBE: ProbeBudget = {
+ timeout: Duration.minutes(2),
+ terminateGrace: Duration.seconds(10),
+};
+// A Mac asleep at launch fails the first probe on wake, and nothing else would probe again.
+const DISCOVERY_RETRY_DELAY = Duration.seconds(30);
+const DISCOVERY_RETRIES = 10;
const trimNonEmpty = (value: string | null | undefined): Option.Option =>
Option.fromNullishOr(value).pipe(
@@ -245,6 +268,7 @@ const runCommandOutput = Effect.fn("desktop.shellEnvironment.runCommandOutput")(
readonly args: ReadonlyArray;
readonly env: NodeJS.ProcessEnv;
readonly timeout: Duration.Duration;
+ readonly terminateGrace?: Duration.Duration;
readonly shell?: boolean;
}): Effect.fn.Return<
string,
@@ -263,7 +287,7 @@ const runCommandOutput = Effect.fn("desktop.shellEnvironment.runCommandOutput")(
stdout: "pipe",
stderr: "ignore",
killSignal: "SIGTERM",
- forceKillAfter: PROCESS_TERMINATE_GRACE,
+ forceKillAfter: input.terminateGrace ?? PROCESS_TERMINATE_GRACE,
}),
);
return yield* Effect.all([Stream.mkString(Stream.decodeText(child.stdout)), child.exitCode], {
@@ -329,6 +353,7 @@ const readLoginShellEnvironment = (
names: ReadonlyArray,
env: NodeJS.ProcessEnv,
timeout: Duration.Duration,
+ terminateGrace: Duration.Duration,
): Effect.Effect<
EnvironmentPatch,
DesktopShellEnvironmentCommandTimeoutError,
@@ -342,6 +367,7 @@ const readLoginShellEnvironment = (
args: ["-ilc", buildEnvironmentCaptureCommand(shell, names)],
env,
timeout,
+ terminateGrace,
}).pipe(Effect.map((output) => extractEnvironment(output, names)));
const readLaunchctlPath = (env: NodeJS.ProcessEnv) =>
@@ -358,6 +384,7 @@ const readWindowsEnvironment = Effect.fn("desktop.shellEnvironment.readWindowsEn
names: ReadonlyArray,
options: WindowsProbeOptions,
env: NodeJS.ProcessEnv,
+ budget: ProbeBudget,
): Effect.fn.Return {
if (names.length === 0) return {};
@@ -375,7 +402,8 @@ const readWindowsEnvironment = Effect.fn("desktop.shellEnvironment.readWindowsEn
command,
args,
env,
- timeout: LOGIN_SHELL_TIMEOUT,
+ timeout: budget.timeout,
+ terminateGrace: budget.terminateGrace,
}).pipe(orEmptyOnTimeout);
const environment = extractEnvironment(output, names);
if (Object.keys(environment).length > 0) {
@@ -393,8 +421,13 @@ const installWindowsEnvironment = Effect.fn("desktop.shellEnvironment.installWin
): Effect.fn.Return {
const [noProfile, profile] = yield* Effect.all(
[
- readWindowsEnvironment(["PATH"], { loadProfile: false }, config.env),
- readWindowsEnvironment(WINDOWS_PROFILE_ENV_NAMES, { loadProfile: true }, config.env),
+ readWindowsEnvironment(["PATH"], { loadProfile: false }, config.env, config.budget),
+ readWindowsEnvironment(
+ WINDOWS_PROFILE_ENV_NAMES,
+ { loadProfile: true },
+ config.env,
+ config.budget,
+ ),
],
{ concurrency: 2 },
);
@@ -418,6 +451,9 @@ const installWindowsEnvironment = Effect.fn("desktop.shellEnvironment.installWin
},
);
+const listUserShells = (env: NodeJS.ProcessEnv): ReadonlyArray =>
+ [env.SHELL?.trim(), readUserLoginShell()].filter((shell): shell is string => Boolean(shell));
+
const installPosixEnvironment = Effect.fn("desktop.shellEnvironment.installPosixEnvironment")(
function* (
config: ShellEnvironmentConfig,
@@ -428,22 +464,28 @@ const installPosixEnvironment = Effect.fn("desktop.shellEnvironment.installPosix
> {
const fileSystem = yield* FileSystem.FileSystem;
const shellEnvironment: EnvironmentPatch = {};
- const userShells = [config.env.SHELL?.trim(), readUserLoginShell()];
+ const userShells = listUserShells(config.env);
let answeredBy: string | undefined;
let waitedForSlowShell = false;
for (const shell of listLoginShellCandidates(config.platform, config.env.SHELL)) {
const read = (timeout: Duration.Duration) =>
- readLoginShellEnvironment(shell, LOGIN_SHELL_ENV_NAMES, config.env, timeout);
+ readLoginShellEnvironment(
+ shell,
+ LOGIN_SHELL_ENV_NAMES,
+ config.env,
+ timeout,
+ config.budget.terminateGrace,
+ );
Object.assign(
shellEnvironment,
- yield* read(LOGIN_SHELL_TIMEOUT).pipe(
+ yield* read(config.budget.timeout).pipe(
Effect.catchTags({
DesktopShellEnvironmentCommandTimeoutError: (error) => {
- const retry = !waitedForSlowShell;
+ const slowTimeout = waitedForSlowShell ? undefined : config.budget.slowTimeout;
waitedForSlowShell = true;
return logShellEnvironmentCommandError(error).pipe(
- Effect.andThen(retry ? read(SLOW_LOGIN_SHELL_TIMEOUT) : Effect.succeed({})),
+ Effect.andThen(slowTimeout ? read(slowTimeout) : Effect.succeed({})),
);
},
}),
@@ -557,7 +599,10 @@ const installPosixEnvironment = Effect.fn("desktop.shellEnvironment.installPosix
}
const prepared = Option.isSome(trimNonEmpty(shellEnvironment.PATH));
- return { prepared, fromUserShell: prepared && userShells.includes(answeredBy) };
+ return {
+ prepared,
+ fromUserShell: prepared && answeredBy !== undefined && userShells.includes(answeredBy),
+ };
},
);
@@ -641,38 +686,60 @@ export const make = Effect.gen(function* () {
yield* Ref.set(latest, Option.some(message));
yield* PubSub.publish(changes, message);
});
- const refresh = Effect.gen(function* () {
- // Refresh from the inherited baseline so removed cached paths and values do not survive.
- const fresh = { ...inherited };
- const discovery = yield* installShellEnvironment({
- env: fresh,
- platform: environment.platform,
- });
- const { prepared } = discovery;
- const patch = Object.fromEntries(
- Object.keys(ShellEnvironmentPatch.fields).map((name) => [name, fresh[name] ?? null]),
- );
- if (prepared || Option.isNone(yield* Ref.get(latest))) yield* publish(patch, prepared);
- if (prepared) {
- const cached = Object.fromEntries(
- CACHED_ENV_NAMES.flatMap((name) => (fresh[name] ? [[name, fresh[name]]] : [])),
- );
- const persist = Effect.gen(function* () {
- const encoded = yield* encodeCache({ version: 1, key, environment: cached });
- yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true });
- yield* fileSystem.writeFileString(cachePath + ".tmp", encoded, { mode: 0o600 });
- yield* fileSystem.rename(cachePath + ".tmp", cachePath);
+ const probe = Effect.fn("desktop.shellEnvironment.refresh")(
+ function* (budget: ProbeBudget) {
+ // Refresh from the inherited baseline so removed cached paths and values do not survive.
+ const fresh = { ...inherited };
+ const discovery = yield* installShellEnvironment({
+ env: fresh,
+ platform: environment.platform,
+ budget,
});
- yield* persist.pipe(
- Effect.catch(() => Effect.logWarning("Could not cache shell environment")),
+ const { prepared } = discovery;
+ const patch = Object.fromEntries(
+ Object.keys(ShellEnvironmentPatch.fields).map((name) => [name, fresh[name] ?? null]),
);
- }
- return discovery;
- }).pipe(
+ if (prepared || Option.isNone(yield* Ref.get(latest))) yield* publish(patch, prepared);
+ if (prepared) {
+ const cached = Object.fromEntries(
+ CACHED_ENV_NAMES.flatMap((name) => (fresh[name] ? [[name, fresh[name]]] : [])),
+ );
+ const persist = Effect.gen(function* () {
+ const encoded = yield* encodeCache({ version: 1, key, environment: cached });
+ yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true });
+ yield* fileSystem.writeFileString(cachePath + ".tmp", encoded, { mode: 0o600 });
+ yield* fileSystem.rename(cachePath + ".tmp", cachePath);
+ });
+ yield* persist.pipe(
+ Effect.catch(() => Effect.logWarning("Could not cache shell environment")),
+ );
+ }
+ return discovery;
+ },
Effect.provideService(FileSystem.FileSystem, fileSystem),
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
- Effect.withSpan("desktop.shellEnvironment.refresh"),
+ );
+ // A fallback shell's PATH can miss folders the user's own shell adds, so keep asking that shell.
+ const awaitsUserShell = listUserShells(inherited).length > 0;
+ const settled = ({ prepared, fromUserShell }: ShellDiscovery) =>
+ fromUserShell || (prepared && !awaitsUserShell);
+ const refresh = probe(STARTUP_PROBE).pipe(
Effect.onExit((exit) => Deferred.done(discovered, exit)),
+ Effect.flatMap((discovery) =>
+ settled(discovery)
+ ? Effect.void
+ : Effect.sleep(DISCOVERY_RETRY_DELAY).pipe(
+ Effect.andThen(
+ probe(RETRY_PROBE).pipe(
+ Effect.repeat({
+ until: settled,
+ schedule: Schedule.spaced(DISCOVERY_RETRY_DELAY),
+ times: DISCOVERY_RETRIES - 1,
+ }),
+ ),
+ ),
+ ),
+ ),
);
const installIntoProcess = yield* Effect.cached(
Effect.gen(function* () {
diff --git a/apps/desktop/src/updates/DesktopRemoteUpdates.test.ts b/apps/desktop/src/updates/DesktopRemoteUpdates.test.ts
index 1f5321148b77..fdac65f86a59 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 });
@@ -691,7 +757,7 @@ describe("DesktopRemoteUpdates", () => {
const backgroundCheck = yield* updates.check("poll").pipe(Effect.forkChild);
yield* Deferred.await(backgroundCheckStarted);
- assert.equal((yield* updates.getState).status, "checking");
+ assert.isTrue(yield* updates.isActionActive);
yield* Queue.offer(commits, {
version: 1,
@@ -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 560e2e78d4bb..ce2f23ab3e78 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 7ee2ff5dd51c..53bd956ca6da 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)));
}),
@@ -1262,6 +1283,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 db31e0bc112b..055c6574391a 100644
--- a/apps/desktop/src/updates/DesktopUpdates.ts
+++ b/apps/desktop/src/updates/DesktopUpdates.ts
@@ -63,7 +63,7 @@ const CHANNEL_CHANGE_RETRY_DELAY = Duration.seconds(1);
const CHANNEL_CHANGE_RETRIES = 30;
const AUTO_UPDATE_STARTUP_DELAY = "15 seconds";
const AUTO_UPDATE_POLL_INTERVAL = "4 hours";
-const PREPARED_INSTALL_CHECK_WAIT = Duration.seconds(90);
+const UPDATE_CHECK_WAIT = Duration.seconds(90);
type UpdateAction = "check" | "download" | "install" | "install-recovery" | "channel";
@@ -318,6 +318,10 @@ function getCanRetryFromState(state: DesktopUpdateState): boolean {
return state.availableVersion !== null || state.downloadedVersion !== null;
}
+function isOffered(state: DesktopUpdateState): boolean {
+ return state.status === "available" || state.status === "downloaded";
+}
+
function shouldBroadcastDownloadProgress(
currentState: DesktopUpdateState,
nextPercent: number,
@@ -518,6 +522,23 @@ export const make = Effect.gen(function* () {
),
);
+ // Re-runs admit after each finished action, so a caller waiting on a check decides on its result.
+ const admitAfterCheck = Effect.fn("desktop.updates.admitAfterCheck")(function* (
+ admit: Effect.Effect<"admitted" | "refused" | "wait-for-check">,
+ ) {
+ const actionCompletions = yield* PubSub.subscribe(finishedUpdateActions);
+ let admission = yield* stateMutex.withPermits(1)(admit);
+ while (admission === "wait-for-check") {
+ const finishedAction = yield* PubSub.take(actionCompletions).pipe(
+ Effect.timeoutOption(UPDATE_CHECK_WAIT),
+ );
+ admission = Option.isNone(finishedAction)
+ ? "refused"
+ : yield* stateMutex.withPermits(1)(admit);
+ }
+ return admission;
+ });
+
const applyAutoUpdaterChannel = Effect.fn("desktop.updates.applyAutoUpdaterChannel")(function* (
channel: DesktopUpdateChannel,
) {
@@ -559,8 +580,10 @@ export const make = Effect.gen(function* () {
if (actionReservation === "acquire" && !(yield* tryStartUpdateAction("check"))) return false;
const check = Effect.gen(function* () {
- const checkedAt = yield* currentIsoTimestamp;
- yield* setState(reduceDesktopUpdateStateOnCheckStart(state, checkedAt));
+ // An offer stays on screen while re-checking, so finding it again changes nothing.
+ if (!isOffered(state)) {
+ yield* setState(reduceDesktopUpdateStateOnCheckStart(state, yield* currentIsoTimestamp));
+ }
yield* logUpdaterInfo("checking for updates", { reason });
// The flag is shared updater state, so it flips only while this check holds the reservation.
@@ -597,15 +620,30 @@ export const make = Effect.gen(function* () {
});
const downloadAvailableUpdate = Effect.gen(function* () {
- const state = yield* Ref.get(updateStateRef);
- if (!(yield* Ref.get(updaterConfiguredRef)) || state.status !== "available") {
- return { accepted: false, completed: false };
- }
-
- if (!(yield* tryStartUpdateAction("download"))) {
+ const admission = yield* Effect.scoped(
+ admitAfterCheck(
+ Effect.gen(function* () {
+ const state = yield* Ref.get(updateStateRef);
+ if (!(yield* Ref.get(updaterConfiguredRef)) || state.status !== "available") {
+ return "refused" as const;
+ }
+ const activeAction = yield* Ref.get(activeUpdateActionRef);
+ if (Option.isSome(activeAction)) {
+ return activeAction.value === "check"
+ ? ("wait-for-check" as const)
+ : ("refused" as const);
+ }
+ return (yield* tryStartUpdateAction("download"))
+ ? ("admitted" as const)
+ : ("refused" as const);
+ }),
+ ),
+ );
+ if (admission === "refused") {
return { accepted: false, completed: false };
}
+ const state = yield* Ref.get(updateStateRef);
return yield* Effect.gen(function* () {
yield* setState(reduceDesktopUpdateStateOnDownloadStart(state));
yield* electronUpdater.setDisableDifferentialDownload(
@@ -798,47 +836,35 @@ export const make = Effect.gen(function* () {
const installDownloadedUpdate = (expectedVersion?: string) =>
Effect.scoped(
Effect.gen(function* () {
- const actionCompletions = yield* PubSub.subscribe(finishedUpdateActions);
- let admission: "admitted" | "refused" | "wait-for-check" = "wait-for-check";
- while (admission === "wait-for-check") {
- admission = yield* stateMutex.withPermits(1)(
- Effect.gen(function* () {
- const state = yield* Ref.get(updateStateRef);
- const activeAction = yield* Ref.get(activeUpdateActionRef);
- const hasExpectedDownload =
- state.downloadedVersion !== null &&
- (expectedVersion === undefined || state.downloadedVersion === expectedVersion);
- if (
- (yield* Ref.get(desktopState.quitting)) ||
- !(yield* Ref.get(updaterConfiguredRef)) ||
- !hasExpectedDownload
- ) {
- return "refused" as const;
- }
- if (Option.isSome(activeAction)) {
- return activeAction.value === "check" && expectedVersion !== undefined
- ? ("wait-for-check" as const)
- : ("refused" as const);
- }
- const hasInstallableDownload =
- state.status === "downloaded" ||
- (state.status === "error" &&
- (state.errorContext === null || state.errorContext === "install"));
- if (!hasInstallableDownload) return "refused" as const;
- return (yield* tryStartUpdateAction("install"))
- ? ("admitted" as const)
+ const admission = yield* admitAfterCheck(
+ Effect.gen(function* () {
+ const state = yield* Ref.get(updateStateRef);
+ const activeAction = yield* Ref.get(activeUpdateActionRef);
+ const hasExpectedDownload =
+ state.downloadedVersion !== null &&
+ (expectedVersion === undefined || state.downloadedVersion === expectedVersion);
+ if (
+ (yield* Ref.get(desktopState.quitting)) ||
+ !(yield* Ref.get(updaterConfiguredRef)) ||
+ !hasExpectedDownload
+ ) {
+ return "refused" as const;
+ }
+ if (Option.isSome(activeAction)) {
+ return activeAction.value === "check"
+ ? ("wait-for-check" as const)
: ("refused" as const);
- }),
- );
- if (admission === "wait-for-check") {
- const finishedAction = yield* PubSub.take(actionCompletions).pipe(
- Effect.timeoutOption(PREPARED_INSTALL_CHECK_WAIT),
- );
- if (Option.isNone(finishedAction)) {
- admission = "refused";
}
- }
- }
+ const hasInstallableDownload =
+ state.status === "downloaded" ||
+ (state.status === "error" &&
+ (state.errorContext === null || state.errorContext === "install"));
+ if (!hasInstallableDownload) return "refused" as const;
+ return (yield* tryStartUpdateAction("install"))
+ ? ("admitted" as const)
+ : ("refused" as const);
+ }),
+ );
if (admission === "refused") {
return { accepted: false, completed: false, failed: false };
}
@@ -982,6 +1008,7 @@ export const make = Effect.gen(function* () {
yield* Ref.set(lastLoggedDownloadMilestoneRef, -1);
return;
}
+ if (isOffered(state) && state.availableVersion === info.version) return;
const checkedAt = yield* currentIsoTimestamp;
const { releaseNotes, omittedReleaseCount } = normalizeDesktopUpdateReleaseNotes(
@@ -1161,6 +1188,8 @@ export const make = Effect.gen(function* () {
),
configure: Effect.gen(function* () {
const context = yield* Effect.context();
+ // Runs synchronously up to the first await, so a check's outcome is applied before the
+ // check's promise resolves and wakes the actions waiting on it.
const runEffect = (effect: Effect.Effect) => {
void Effect.runPromiseWith(context)(effect);
};
diff --git a/apps/desktop/src/window/DesktopApplicationMenu.test.ts b/apps/desktop/src/window/DesktopApplicationMenu.test.ts
index 612ec441ba99..46004ca30229 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 44d2c234f835..b4025ebfde8e 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 f66586503e24..46311dbba812 100644
--- a/apps/desktop/src/window/DesktopWindow.test.ts
+++ b/apps/desktop/src/window/DesktopWindow.test.ts
@@ -1226,6 +1226,38 @@ 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();
diff --git a/apps/desktop/src/window/DesktopWindow.ts b/apps/desktop/src/window/DesktopWindow.ts
index 7be14bc72083..4628be44d5ce 100644
--- a/apps/desktop/src/window/DesktopWindow.ts
+++ b/apps/desktop/src/window/DesktopWindow.ts
@@ -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();
}
diff --git a/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts b/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts
index 0787956a72b7..7f4a2507a736 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 4e5e5b423f20..5ba7d3794fad 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/marketing/src/pages/[...locale]/index.astro b/apps/marketing/src/pages/[...locale]/index.astro
index 3d8d44568d44..e8f4b5f1b5fa 100644
--- a/apps/marketing/src/pages/[...locale]/index.astro
+++ b/apps/marketing/src/pages/[...locale]/index.astro
@@ -1234,6 +1234,8 @@ const mobileEndorsementRows = [
section { padding: 56px 0; }
.sec-cta { padding: 80px 0; }
.container { padding-left: 20px; padding-right: 20px; }
+ /* A nowrap tag widens its column past the grid, which then clips the other column. */
+ .harness-tag { white-space: normal; }
.endorsements-head {
margin-bottom: 40px;
}
@@ -1265,4 +1267,8 @@ const mobileEndorsementRows = [
font-size: 11px;
}
}
+
+ @media (max-width: 360px) {
+ .harness { padding-left: 12px; padding-right: 12px; }
+ }
diff --git a/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift b/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift
index 96551d05bbb5..6b2e18389293 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
@@ -301,18 +309,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 +338,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 +362,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 +418,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 +430,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 +561,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 +730,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 +759,7 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro
func setPlaceholder(_ placeholder: String) {
placeholderLabel.text = placeholder
+ textView.accessibilityLabel = placeholder
setNeedsLayout()
}
@@ -1027,8 +1048,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 +1348,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 +1372,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 4435b1022161..6009daacb404 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,25 @@ for readOnly in [true, false] {
check(provider.loadCount == 0, "Locked inputs must not load pasted image providers")
}
+// 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 +272,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 af67e80afebb..5b3d84aedcee 100644
--- a/apps/mobile/modules/t3-native-controls/ios/T3NativeControlsModule.swift
+++ b/apps/mobile/modules/t3-native-controls/ios/T3NativeControlsModule.swift
@@ -10,6 +10,9 @@ public final class T3NativeControlsModule: Module {
private let presentationSources = T3PresentationSources()
private var videoPresentation: T3NativeVideoPresentation?
private var filePresentation: T3NativeFilePresentation?
+ /// The last file preview that closed. Written on main, read synchronously from JS.
+ private let filePreviewActivity = NSLock()
+ private var finishedFilePreview: String?
public func definition() -> ModuleDefinition {
Events("videoPlaybackChange")
@@ -94,6 +97,12 @@ public final class T3NativeControlsModule: Module {
file.present(urls: urls, titles: titles, selectedIndex: selectedIndex, from: presenter)
}.runOnQueue(.main)
+ // A tap can reach JS before the old viewer's close does; this tells it whether that viewer is gone.
+ // A presentation main has not started yet reads as still open.
+ Function("isFilePreviewFinished") { (identifier: String) -> Bool in
+ self.filePreviewActivity.withLock { self.finishedFilePreview == identifier }
+ }
+
// A nil URL marks the item as one that could not be resolved.
AsyncFunction("updateFile") { (identifier: String, index: Int, url: URL?) in
if self.filePresentation?.identifier == identifier { self.filePresentation?.update(index: index, url: url) }
@@ -294,15 +303,22 @@ public final class T3NativeControlsModule: Module {
guard filePresentation == nil, videoPresentation == nil,
appContext?.utilities?.currentViewController() != nil
else { throw URLError(.cannotLoadFromNetwork) }
- let file = T3NativeFilePresentation(identifier: identifier, sources: presentationSources,
- sourceIdentifiers: sourceIdentifiers) { [weak self] error in
- self?.filePresentation = nil
- if let error { promise.reject(error) } else { promise.resolve(nil) }
- }
+ let file = T3NativeFilePresentation(
+ identifier: identifier, sources: presentationSources, sourceIdentifiers: sourceIdentifiers,
+ onFinish: { [weak self] in self?.setFinishedFilePreview(identifier) },
+ completion: { [weak self] error in
+ self?.filePresentation = nil
+ if let error { promise.reject(error) } else { promise.resolve(nil) }
+ }
+ )
filePresentation = file
return file
}
+ private func setFinishedFilePreview(_ identifier: String) {
+ filePreviewActivity.withLock { finishedFilePreview = identifier }
+ }
+
private func presentFile(url: URL, title: String, sourceIdentifier: String,
identifier: String, promise: Promise) throws {
let file = try makeFilePresentation(sourceIdentifiers: [sourceIdentifier], identifier: identifier, promise: promise)
diff --git a/apps/mobile/modules/t3-native-controls/ios/T3NativeFilePresentation.swift b/apps/mobile/modules/t3-native-controls/ios/T3NativeFilePresentation.swift
index 791e39b2840c..979e87edc1b0 100644
--- a/apps/mobile/modules/t3-native-controls/ios/T3NativeFilePresentation.swift
+++ b/apps/mobile/modules/t3-native-controls/ios/T3NativeFilePresentation.swift
@@ -8,232 +8,217 @@ private final class FilePreviewItem: NSObject, QLPreviewItem {
var previewItemTitle: String?
}
-private enum FilePreviewState { case loading, ready, failed }
-
private final class FilePreviewController: QLPreviewController {
var onAppear: (() -> Void)?
- // Quick Look shows a blank page for an item without a file, so loading and failure are ours to show.
- private let spinner = UIActivityIndicatorView(style: .large)
- private let failure = UILabel()
- var state = FilePreviewState.ready {
- didSet { if isViewLoaded { showState() } }
- }
-
- override func viewDidLoad() {
- super.viewDidLoad()
- failure.text = "This image could not be loaded."
- failure.textColor = .secondaryLabel
- failure.textAlignment = .center
- failure.numberOfLines = 0
- for status in [spinner, failure] as [UIView] {
- status.isUserInteractionEnabled = false
- status.translatesAutoresizingMaskIntoConstraints = false
- view.addSubview(status)
- NSLayoutConstraint.activate([
- status.centerXAnchor.constraint(equalTo: view.centerXAnchor),
- status.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: 64),
- status.widthAnchor.constraint(lessThanOrEqualTo: view.widthAnchor, constant: -48),
- ])
- }
- showState()
- }
-
- override func viewDidLayoutSubviews() {
- super.viewDidLayoutSubviews()
- view.bringSubviewToFront(spinner)
- view.bringSubviewToFront(failure)
- }
+ var onDismiss: (() -> Void)?
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
onAppear?()
}
- private func showState() {
- if state == .loading { spinner.startAnimating() } else { spinner.stopAnimating() }
- failure.isHidden = state != .failed
+ // Quick Look's own didDismiss callback can lag well behind the screen being tappable again,
+ // so a tap on the thumbnail in that gap would land while JS still thinks the viewer is open.
+ override func viewDidDisappear(_ animated: Bool) {
+ super.viewDidDisappear(animated)
+ if isBeingDismissed { onDismiss?() }
}
}
+/// How long the gallery waits for siblings once the selected file is ready; later ones are left out.
+private let siblingGraceNanoseconds: UInt64 = 1_000_000_000
+/// A load faster than this zooms straight from the thumbnail without a spinner.
+private let spinnerDelayNanoseconds: UInt64 = 250_000_000
+
+/// Quick Look only ever receives pages whose file is on disk: a page refreshed after it first
+/// rendered blank keeps a stale scroll offset, so drags scroll the image instead of paging or dismissing.
final class T3NativeFilePresentation: NSObject, QLPreviewControllerDataSource,
QLPreviewControllerDelegate, UIAdaptivePresentationControllerDelegate {
let identifier: String
private var controller: FilePreviewController?
private let completion: (Error?) -> Void
+ private let onFinish: () -> Void
private weak var sources: T3PresentationSources?
private let sourceIdentifiers: [String]
- private var items: [FilePreviewItem] = []
+ private var titles: [String] = []
private var urls: [URL?] = []
- private var states: [FilePreviewState] = []
+ /// A prepared file, or nil while loading or after failing; `settled` tells those apart.
+ private var files: [URL?] = []
+ private var settled: [Bool] = []
+ private var downloads: [Int: Task] = [:]
private var selectedIndex = 0
+ /// The pages Quick Look shows, as indices into `files`.
+ private var pages: [Int] = []
+ private var items: [FilePreviewItem] = []
private weak var presenter: UIViewController?
- /// Files that arrived while their page was off screen; Quick Look may still hold the blank page.
- private var staleIndices = Set()
- private var currentIndexObservation: NSKeyValueObservation?
- private var download: (index: Int, task: Task)?
- private var placeholder: Task?
+ private var grace: Task?
+ private var spinnerDelay: Task?
+ private var spinner: UIView?
private var openError: Error?
private var dismissRequested = false
private var finished = false
init(identifier: String, sources: T3PresentationSources, sourceIdentifiers: [String],
- completion: @escaping (Error?) -> Void) {
+ onFinish: @escaping () -> Void, completion: @escaping (Error?) -> Void) {
self.identifier = identifier
self.sources = sources
self.sourceIdentifiers = sourceIdentifiers
+ self.onFinish = onFinish
self.completion = completion
super.init()
}
/// Downloads the file before presenting so Quick Look can refuse a format the caller should share instead.
func present(url: URL, title: String, from presenter: UIViewController) {
- load(urls: [url], titles: [title], selectedIndex: 0, from: presenter, opensWhileLoading: false)
+ present(urls: [url], titles: [title], selectedIndex: 0, from: presenter)
}
- /// Opens the selected image once it is ready, or a loading page if it is slow, and loads the rest
- /// of the gallery behind it so a slow or broken sibling never holds the viewer back.
+ /// Loads the gallery in parallel and opens once the selected file is ready, with whichever
+ /// siblings are ready by the end of a short grace, so a slow or broken one never holds it back.
func present(urls: [URL?], titles: [String], selectedIndex: Int, from presenter: UIViewController) {
- load(urls: urls, titles: titles, selectedIndex: selectedIndex, from: presenter, opensWhileLoading: true)
+ self.titles = titles
+ self.urls = urls
+ self.selectedIndex = selectedIndex
+ self.presenter = presenter
+ files = Array(repeating: nil, count: urls.count)
+ settled = Array(repeating: false, count: urls.count)
+ spinnerDelay = Task { @MainActor [self] in
+ try? await Task.sleep(nanoseconds: spinnerDelayNanoseconds)
+ guard !Task.isCancelled else { return }
+ showSpinner()
+ }
+ for index in urls.indices { download(index) }
}
/// Delivers a URL that was still resolving when the gallery opened, or nil when it never will.
func update(index: Int, url: URL?) {
- guard !finished, urls.indices.contains(index), urls[index] == nil, states[index] == .loading else { return }
+ guard !finished, controller == nil, urls.indices.contains(index), urls[index] == nil,
+ !settled[index]
+ else { return }
guard let url else {
- failed(index, error: URLError(.resourceUnavailable))
+ settle(index, result: .failure(URLError(.resourceUnavailable)))
return
}
urls[index] = url
- loadNext()
- }
-
- private func load(urls: [URL?], titles: [String], selectedIndex: Int, from presenter: UIViewController,
- opensWhileLoading: Bool) {
- items = titles.map { title in
- let item = FilePreviewItem()
- item.previewItemTitle = title
- return item
- }
- self.urls = urls
- self.selectedIndex = selectedIndex
- self.presenter = presenter
- states = Array(repeating: .loading, count: urls.count)
- if opensWhileLoading {
- // A short grace keeps the zoom from the thumbnail into a loaded image when the file is quick.
- placeholder = Task { @MainActor [self] in
- try? await Task.sleep(nanoseconds: 250_000_000)
- guard !Task.isCancelled, !finished, controller == nil else { return }
- show()
- }
- }
- loadNext()
+ download(index)
}
- /// Downloads one file at a time, nearest the page on screen first. The page on screen takes over
- /// from a background download, which restarts later.
- private func loadNext() {
- guard !finished, !dismissRequested else { return }
- let current = controller?.currentPreviewItemIndex ?? selectedIndex
- guard let next = urls.indices
- .filter({ urls[$0] != nil && states[$0] == .loading })
- .min(by: { abs($0 - current) < abs($1 - current) })
- else { return }
- if let download {
- guard next == current, download.index != current else { return }
- download.task.cancel()
- }
- guard let url = urls[next] else { return }
- let title = items[next].previewItemTitle ?? ""
- let task = Task { @MainActor [self] in
+ private func download(_ index: Int) {
+ guard let url = urls[index], downloads[index] == nil else { return }
+ let title = titles[index]
+ downloads[index] = Task { @MainActor [self] in
let result: Result
do {
result = .success(try await Self.prepareFile(url: url, title: title))
} catch {
result = .failure(error)
}
- guard !finished, !Task.isCancelled else {
- if case .success(let file) = result {
- try? FileManager.default.removeItem(at: file.deletingLastPathComponent())
- }
- return
- }
- download = nil
- switch result {
- case .success(let file): loaded(next, file: file)
- case .failure(let error): failed(next, error: error)
- }
- loadNext()
+ downloads[index] = nil
+ settle(index, result: result)
}
- download = (next, task)
}
- private func loaded(_ index: Int, file: URL) {
- // Quick Look knows which formats it renders; refuse before presenting so the caller
- // can fall back instead of showing an "unsupported format" page.
- guard QLPreviewController.canPreview(file as NSURL) else {
- try? FileManager.default.removeItem(at: file.deletingLastPathComponent())
- failed(index, error: NSError(
- domain: "T3NativePresentation",
- code: 3,
- userInfo: [NSLocalizedDescriptionKey: "This file type cannot be previewed on this device."]
- ))
+ private func settle(_ index: Int, result: Result) {
+ guard !finished, controller == nil, !dismissRequested else {
+ if case .success(let file) = result { Self.remove(file) }
return
}
- items[index].previewItemURL = file
- states[index] = .ready
- if controller != nil { refresh(index) } else if index == selectedIndex { show() }
- }
-
- private func failed(_ index: Int, error: Error) {
- guard index != selectedIndex else {
+ settled[index] = true
+ if let error = store(index, result: result), index == selectedIndex {
openError = error
dismiss()
return
}
- states[index] = .failed
- refresh(index)
+ guard files[selectedIndex] != nil else { return }
+ if settled.allSatisfy({ $0 }) {
+ show()
+ } else if grace == nil {
+ grace = Task { @MainActor [self] in
+ try? await Task.sleep(nanoseconds: siblingGraceNanoseconds)
+ guard !Task.isCancelled else { return }
+ show()
+ }
+ }
+ }
+
+ private func store(_ index: Int, result: Result) -> Error? {
+ switch result {
+ case .success(let file):
+ // Quick Look knows which formats it renders; refuse before presenting so the caller
+ // can fall back instead of showing an "unsupported format" page.
+ guard QLPreviewController.canPreview(file as NSURL) else {
+ Self.remove(file)
+ return NSError(
+ domain: "T3NativePresentation",
+ code: 3,
+ userInfo: [NSLocalizedDescriptionKey: "This file type cannot be previewed on this device."]
+ )
+ }
+ files[index] = file
+ return nil
+ case .failure(let error):
+ return error
+ }
}
private func show() {
+ guard !finished, controller == nil, !dismissRequested else { return }
guard let presenter else { finish(); return }
- placeholder?.cancel()
+ cancelLoading()
+ pages = files.indices.filter { files[$0] != nil }
+ items = pages.map { index in
+ let item = FilePreviewItem()
+ item.previewItemURL = files[index]
+ item.previewItemTitle = titles[index]
+ return item
+ }
let preview = FilePreviewController()
preview.delegate = self
preview.dataSource = self
- preview.currentPreviewItemIndex = selectedIndex
+ preview.currentPreviewItemIndex = pages.firstIndex(of: selectedIndex) ?? 0
preview.onAppear = { [weak self] in self?.resumePendingDismissal() }
+ preview.onDismiss = { [weak self] in self?.finish() }
controller = preview
- preview.state = states[selectedIndex]
- currentIndexObservation = preview.observe(\.currentPreviewItemIndex) { [weak self] _, _ in
- DispatchQueue.main.async { self?.currentItemChanged() }
- }
presenter.present(preview, animated: !UIAccessibility.isReduceMotionEnabled) { [self] in
resumePendingDismissal()
}
preview.presentationController?.delegate = self
}
- private func refresh(_ index: Int) {
- guard let controller else { return }
- guard controller.currentPreviewItemIndex == index else {
- if states[index] == .ready { staleIndices.insert(index) }
- return
- }
- if states[index] == .ready { controller.refreshCurrentPreviewItem() }
- controller.state = states[index]
+ /// Shows over the tapped thumbnail that a slow open is on its way.
+ private func showSpinner() {
+ guard !finished, controller == nil, spinner == nil,
+ sourceIdentifiers.indices.contains(selectedIndex),
+ let source = sources?.view(for: sourceIdentifiers[selectedIndex]),
+ let window = source.window
+ else { return }
+ let backing = UIView(frame: CGRect(x: 0, y: 0, width: 44, height: 44))
+ backing.backgroundColor = UIColor.black.withAlphaComponent(0.55)
+ backing.layer.cornerRadius = 22
+ backing.isUserInteractionEnabled = false
+ let indicator = UIActivityIndicatorView(style: .medium)
+ indicator.color = .white
+ indicator.center = CGPoint(x: 22, y: 22)
+ indicator.startAnimating()
+ backing.addSubview(indicator)
+ backing.center = source.convert(CGPoint(x: source.bounds.midX, y: source.bounds.midY), to: window)
+ window.addSubview(backing)
+ spinner = backing
}
- private func currentItemChanged() {
- guard !finished, let controller, states.indices.contains(controller.currentPreviewItemIndex) else { return }
- let index = controller.currentPreviewItemIndex
- if staleIndices.remove(index) != nil { controller.refreshCurrentPreviewItem() }
- controller.state = states[index]
- loadNext()
+ private func cancelLoading() {
+ for task in downloads.values { task.cancel() }
+ downloads.removeAll()
+ grace?.cancel()
+ grace = nil
+ spinnerDelay?.cancel()
+ spinnerDelay = nil
+ spinner?.removeFromSuperview()
+ spinner = nil
}
func dismiss() {
dismissRequested = true
- download?.task.cancel()
guard !finished else { return }
guard let controller else { finish(); return }
// Drain Close from viewDidAppear after opening or cancelling an interactive dismissal.
@@ -257,10 +242,10 @@ final class T3NativeFilePresentation: NSObject, QLPreviewControllerDataSource,
private func sourceView(for item: QLPreviewItem) -> UIView? {
guard !UIAccessibility.isReduceMotionEnabled,
- let index = items.firstIndex(where: { $0 === item }),
- sourceIdentifiers.indices.contains(index)
+ let page = items.firstIndex(where: { $0 === item }),
+ sourceIdentifiers.indices.contains(pages[page])
else { return nil }
- return sources?.view(for: sourceIdentifiers[index])
+ return sources?.view(for: sourceIdentifiers[pages[page]])
}
func previewController(_ controller: QLPreviewController, transitionViewFor item: QLPreviewItem) -> UIView? {
@@ -278,24 +263,20 @@ final class T3NativeFilePresentation: NSObject, QLPreviewControllerDataSource,
func presentationControllerDidDismiss(_ presentationController: UIPresentationController) { finish() }
- private func finish(error: Error? = nil) {
+ private func finish() {
guard !finished else { return }
finished = true
- download?.task.cancel()
- download = nil
- placeholder?.cancel()
- placeholder = nil
- currentIndexObservation = nil
- for item in items {
- if let file = item.previewItemURL {
- try? FileManager.default.removeItem(at: file.deletingLastPathComponent())
- }
- }
+ cancelLoading()
+ for file in files.compactMap({ $0 }) { Self.remove(file) }
+ files.removeAll()
items.removeAll()
- urls.removeAll()
- states.removeAll()
- let result = error ?? openError
- DispatchQueue.main.async { [completion] in completion(result) }
+ DispatchQueue.main.async { [completion, openError] in completion(openError) }
+ // After queueing the completion, so a new presentation JS starts on seeing this lands behind it.
+ onFinish()
+ }
+
+ private static func remove(_ file: URL) {
+ try? FileManager.default.removeItem(at: file.deletingLastPathComponent())
}
/// Copy original bytes so preview and sharing do not mutate a draft or workspace file.
@@ -305,6 +286,7 @@ final class T3NativeFilePresentation: NSObject, QLPreviewControllerDataSource,
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
do {
let download = directory.appendingPathComponent("original")
+ var mimeType: String?
if url.isFileURL {
try FileManager.default.copyItem(at: url, to: download)
} else if url.scheme == "data" {
@@ -317,6 +299,7 @@ final class T3NativeFilePresentation: NSObject, QLPreviewControllerDataSource,
guard let response = response as? HTTPURLResponse, (200..<300).contains(response.statusCode) else {
throw URLError(.badServerResponse)
}
+ mimeType = response.mimeType
try FileManager.default.moveItem(at: temporaryFile, to: download)
}
try Task.checkCancellation()
@@ -330,7 +313,8 @@ final class T3NativeFilePresentation: NSObject, QLPreviewControllerDataSource,
type = detectedType
} else if CGPDFDocument(download as CFURL) != nil {
type = .pdf
- } else if originalExtension.lowercased() == "svg" {
+ } else if originalExtension.lowercased() == "svg" || mimeType == "image/svg+xml" {
+ // ImageIO cannot read SVG, and served images such as QR codes often have no extension.
type = .svg
}
let fileExtension: String
diff --git a/apps/mobile/modules/t3-native-controls/ios/T3ScrollEdgeBleedView.swift b/apps/mobile/modules/t3-native-controls/ios/T3ScrollEdgeBleedView.swift
index 924fa4ddeb14..6732f2dae2f1 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-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 7a1225cd392b..2f1e4d9fd4a4 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 770bc656de56..83f32788e8ab 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 63ab13dde3d1..03609e3658e8 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 54ff86c611a8..91bb6719ed8f 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 7f96dc17a25e..4c60b20c1add 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 2fcb8a480180..d1be707b0d9d 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 a80a39138075..7fe4a068f9bb 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/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 50cd48b3380e..ad0de0702510 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
@@ -331,8 +331,9 @@ 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)
}
}
diff --git a/apps/mobile/src/components/ComposerAttachmentStrip.tsx b/apps/mobile/src/components/ComposerAttachmentStrip.tsx
index 49d30e06e45f..66393de96bc6 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 f7ce1f9918d8..029f454b902f 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/VideoThumbnailImage.tsx b/apps/mobile/src/components/VideoThumbnailImage.tsx
index 6f6fea83063c..2a031b54b44f 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 a17e48c2604c..f9e3b2ac0124 100644
--- a/apps/mobile/src/components/ui/AndroidAnchoredMenu.android.tsx
+++ b/apps/mobile/src/components/ui/AndroidAnchoredMenu.android.tsx
@@ -61,6 +61,10 @@ export function AndroidAnchoredMenu(props: AndroidAnchoredMenuProps) {
setPath([]);
setOverlay(null);
};
+ // The in-window menu is pinned to the trigger's spot above the keyboard, which is stale once it hides.
+ if (anchor?.keyboardWasVisible === true && !keyboardVisible) {
+ close();
+ }
const open = () => {
anchorNode?.measureInWindow((x, y, width, height) => {
diff --git a/apps/mobile/src/components/ui/FilePreviewModal.tsx b/apps/mobile/src/components/ui/FilePreviewModal.tsx
index aff82eae479c..eba89cdb28c9 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 37dd9ea9e16b..4311776b0ad9 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 a5b51aa5cf4b..8a38a70605cd 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 5df8acf001e0..a7a60ce5555b 100644
--- a/apps/mobile/src/components/ui/FilePreviewSession.tsx
+++ b/apps/mobile/src/components/ui/FilePreviewSession.tsx
@@ -97,6 +97,7 @@ function ResolvedFilePreview(
readonly source: FilePreviewSource;
readonly onRequestClose: () => void;
readonly onOpenError?: (error: unknown) => void;
+ readonly onPresent: (isFinished: () => boolean) => void;
},
) {
const { progressiveGallery, Viewer } = props;
@@ -161,6 +162,7 @@ function ResolvedFilePreview(
);
@@ -205,6 +207,7 @@ function ResolvedFilePreview(
}}
onRequestClose={props.onRequestClose}
onOpenError={onOpenError}
+ onPresent={props.onPresent}
/>
);
}
@@ -220,15 +223,43 @@ export function FilePreviewSession(props: FilePreviewModalProps & FilePreviewSes
? null
: { ...props.source, gallery: filePreviewGallery(props.source, group) };
usePreviewPresentation(source && filePreviewKey(source), props.onRequestClose);
+ // A tap can land after the native viewer closed but before its close reached the caller, which
+ // still holds the same item; that tap only opens a new viewer under a new key.
+ // Only a viewer that presented and has since closed reopens; one still resolving never does.
+ const [opening, setOpening] = useState<{
+ readonly source: FilePreviewModalProps["source"];
+ readonly count: number;
+ readonly presented: { readonly isFinished: () => boolean } | null;
+ }>({ source: props.source, count: 0, presented: null });
+ if (opening.source !== props.source) {
+ const sameItem =
+ opening.source !== null &&
+ props.source !== null &&
+ filePreviewKey(opening.source) === filePreviewKey(props.source);
+ const reopened = sameItem && opening.presented?.isFinished() === true;
+ setOpening({
+ source: props.source,
+ count: opening.count + (reopened ? 1 : 0),
+ presented: sameItem && !reopened ? opening.presented : null,
+ });
+ }
+ const { count } = opening;
+ const onPresent = (isFinished: () => boolean) =>
+ setOpening((current) =>
+ current.count === count && current.presented === null
+ ? { ...current, presented: { isFinished } }
+ : current,
+ );
if (!source) return null;
return (
);
diff --git a/apps/mobile/src/features/diagnostics/SettingsDiagnosticsRouteScreen.tsx b/apps/mobile/src/features/diagnostics/SettingsDiagnosticsRouteScreen.tsx
index 528a18541eb4..448fd929e42e 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 7f503239c21d..4d73a7cda5c3 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 bf8c6e8e311c..2699bb995406 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/home/HomeScreen.tsx b/apps/mobile/src/features/home/HomeScreen.tsx
index 8110cca26793..6f5db6a52f59 100644
--- a/apps/mobile/src/features/home/HomeScreen.tsx
+++ b/apps/mobile/src/features/home/HomeScreen.tsx
@@ -469,7 +469,6 @@ export function HomeScreen(props: HomeScreenProps) {
selectedThreadKey)
}
project={projectByKey.get(pendingScopeKey) ?? null}
- projectTitle={v2ProjectTitleByProjectKey.get(pendingScopeKey)}
environmentLabel={
Object.keys(props.savedConnectionsById).length > 1
? (props.savedConnectionsById[item.pendingTask.environmentId]?.environmentLabel ??
diff --git a/apps/mobile/src/features/home/ThreadUndoNotice.tsx b/apps/mobile/src/features/home/ThreadUndoNotice.tsx
index caeb47a3c219..544a2909124e 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/thread-swipe-actions.tsx b/apps/mobile/src/features/home/thread-swipe-actions.tsx
index 532badd9b35c..5a0305ca23a8 100644
--- a/apps/mobile/src/features/home/thread-swipe-actions.tsx
+++ b/apps/mobile/src/features/home/thread-swipe-actions.tsx
@@ -512,7 +512,9 @@ export function ThreadSwipeable(props: ThreadSwipeableProps) {
overshootRight
renderRightActions={renderRightActions}
rightThreshold={actionsWidth * 0.42}
- simultaneousWith={props.simultaneousWith}
+ // Only iPad trackpad pans need rows to swipe while the list scrolls; on Android touch it
+ // lets a diagonal swipe scroll the list, which the scroll gate turns into a closed row.
+ simultaneousWith={Platform.OS === "ios" ? props.simultaneousWith : undefined}
>
{
/* oxlint-disable react/refs -- The render callback receives a close/open handler; only invoking that handler accesses the ref. */
diff --git a/apps/mobile/src/features/layout/createWorkspaceStackNavigator.ios.tsx b/apps/mobile/src/features/layout/createWorkspaceStackNavigator.ios.tsx
index 71a452f7d342..fb144bdd16c7 100644
--- a/apps/mobile/src/features/layout/createWorkspaceStackNavigator.ios.tsx
+++ b/apps/mobile/src/features/layout/createWorkspaceStackNavigator.ios.tsx
@@ -107,7 +107,10 @@ function ColumnScreen(props: {
readonly selectedThreadKey?: string | null;
readonly selectedPullRequestKey?: string | null;
readonly onDismiss: (routeKey: string, native: boolean) => void;
- readonly onAppearance: (type: "willAppear" | "didAppear" | "willDisappear", key: string) => void;
+ readonly onAppearance: (
+ type: "willAppear" | "didAppear" | "willDisappear" | "didDisappear",
+ key: string,
+ ) => void;
readonly onCompose?: () => void;
readonly navigation: ViewProps["navigation"];
readonly footer?: ReactNode;
@@ -152,9 +155,10 @@ function ColumnScreen(props: {
props.onAppearance("willDisappear", key);
props.navigation.emit({ type: "transitionStart", target: key, data: { closing: true } });
}}
- onDidDisappear={() =>
- props.navigation.emit({ type: "transitionEnd", target: key, data: { closing: true } })
- }
+ onDidDisappear={() => {
+ props.onAppearance("didDisappear", key);
+ props.navigation.emit({ type: "transitionEnd", target: key, data: { closing: true } });
+ }}
>
@@ -307,7 +311,7 @@ function WorkspaceColumns(
}
};
const followCollapsedSplit = (
- type: "willAppear" | "didAppear" | "willDisappear",
+ type: "willAppear" | "didAppear" | "willDisappear" | "didDisappear",
key: string,
) => {
if (!collapsed.current || layout.usesSplitView) return;
@@ -534,7 +538,6 @@ function WorkspaceStackView(props: ViewProps & { readonly nativeColumns: boolean
0 &&
!primaryVisible &&
!layout.usesSplitView &&
diff --git a/apps/mobile/src/features/layout/workspace/WorkspaceRootScreen.tsx b/apps/mobile/src/features/layout/workspace/WorkspaceRootScreen.tsx
index e8e7c0d32598..355e3440c531 100644
--- a/apps/mobile/src/features/layout/workspace/WorkspaceRootScreen.tsx
+++ b/apps/mobile/src/features/layout/workspace/WorkspaceRootScreen.tsx
@@ -100,8 +100,8 @@ function WorkspaceRootContent() {
layout.variant === "medium" && state.selectedTab === "usage"
? workspaceDockBottomClearance({ bottomInset: insets.bottom, keyboardHeight })
: isDuoDevice(deviceType)
- ? // The column's safe area already holds the Duo's search toolbar and keyboard.
- Math.max(insets.bottom, keyboardHeight) + 16
+ ? // The column's safe area holds the Duo's search toolbar, but not the sidebar's own tab bar.
+ Math.max(insets.bottom + (sidebarPicker ? 64 : 0), keyboardHeight) + 16
: compactTabs || deviceType === "pad"
? workspaceDockBottomClearance({ bottomInset: insets.bottom, keyboardHeight })
: Math.max(insets.bottom, keyboardHeight) +
diff --git a/apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx b/apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx
index 8e33a5bec100..d72cbe743f23 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";
@@ -382,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
@@ -441,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.
@@ -830,7 +822,7 @@ export function PullRequestRouteScreen({ route }: StaticScreenProps
) : null}
@@ -1010,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]);
@@ -1072,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
@@ -1329,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/pullRequestDiffPages.test.ts b/apps/mobile/src/features/pull-requests/pullRequestDiffPages.test.ts
index 82027addc72c..b0c91ab3ada9 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 9abf7cfc0c07..8ec7cea70bf3 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/usePullRequestActivityFilter.ts b/apps/mobile/src/features/pull-requests/usePullRequestActivityFilter.ts
new file mode 100644
index 000000000000..1f2d0d8582de
--- /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 6e49993a137f..f091e5b6847d 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 d4fe1ab3461b..8ba0721fd7fb 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/nativeReviewDiffAdapter.ts b/apps/mobile/src/features/review/nativeReviewDiffAdapter.ts
index e943fd5c5792..63372efb661b 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";
@@ -226,6 +227,8 @@ export function createNativeReviewDiffTheme(
deleteBar: terminalRed ?? "#ff2e3f",
addText: "#5ECC71",
deleteText: "#FF6762",
+ warningText: nativeColor(appTheme["--color-warning-foreground"]),
+ warningBackground: nativeColor(appTheme["--color-warning"]),
};
}
@@ -243,6 +246,8 @@ export function createNativeReviewDiffTheme(
deleteBar: terminalRed ?? "#ff2e3f",
addText: "#199F43",
deleteText: "#D52C36",
+ warningText: nativeColor(appTheme["--color-warning-foreground"]),
+ warningBackground: nativeColor(appTheme["--color-warning"]),
};
}
@@ -270,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 [];
}
@@ -388,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}`,
@@ -396,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 df3c7c51324b..3a1028dbb173 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 18a22e96b62b..8368c1ec63aa 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: [],
diff --git a/apps/mobile/src/features/settings/SettingsClientStorageRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsClientStorageRouteScreen.tsx
index c0f93d2ee324..1b34022d4cae 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/appearance/useScaledTextRole.ts b/apps/mobile/src/features/settings/appearance/useScaledTextRole.ts
index ffeb6114c17a..c71298a89822 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/shortcuts/appShortcutsRuntime.test.ts b/apps/mobile/src/features/shortcuts/appShortcutsRuntime.test.ts
index c985506480b7..961c0f42fa53 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 b182c33b0786..a8c3d7b96477 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 173e0cb62c62..f3ed8b01983c 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,
@@ -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 17fabe588115..6e5046dab35c 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 9c5e05dcc24f..0f09d109e363 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 ec9bd9d74d93..254508513791 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 d070bdc16882..b09e365587d5 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 cf03775b7c7f..203343eb5a68 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 ac9e2ce81363..8027e1572a07 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/SubagentRow.tsx b/apps/mobile/src/features/threads/SubagentRow.tsx
index 96f6f659aa5a..77097c565aa0 100644
--- a/apps/mobile/src/features/threads/SubagentRow.tsx
+++ b/apps/mobile/src/features/threads/SubagentRow.tsx
@@ -128,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),
@@ -158,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 fc845138bc22..ce4e4b7fb0e4 100644
--- a/apps/mobile/src/features/threads/ThreadComposer.tsx
+++ b/apps/mobile/src/features/threads/ThreadComposer.tsx
@@ -30,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";
@@ -80,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,
@@ -91,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";
@@ -219,12 +225,20 @@ export interface ThreadComposerProps {
readonly selectedThread: EnvironmentThreadShell;
readonly reportedModelSelection?: ModelSelection | null;
readonly hasCompactableConversation: boolean;
+ /** Set while the next send compacts the thread first. */
+ readonly compactBeforeSend?: {
+ readonly tokens: number;
+ readonly keepFullHistory: boolean;
+ readonly toggleKeepFullHistory: () => void;
+ } | null;
/** Arms a fresh session for the next message; absent where `/clear` is unavailable. */
readonly onFreshSession?: () => void;
readonly offersSideChat?: boolean;
readonly serverConfig: T3ServerConfig | null;
readonly queueCount: number;
readonly activeThreadBusy: boolean;
+ /** Sending declines a pending approval and redirects the agent, so `/side` is plain text. */
+ readonly redirectsApproval: boolean;
readonly canStopThread: boolean;
readonly environmentId: EnvironmentId;
readonly projectCwd: string | null;
@@ -421,7 +435,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);
@@ -488,7 +502,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:
@@ -574,6 +591,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 }),
@@ -819,6 +837,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)}
@@ -1099,6 +1143,7 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps
compactEditor.isExpanded ? { flex: 1, justifyContent: "flex-end" } : undefined
}
>
+ {compactControl}
{modelControl}
;
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";
@@ -274,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;
@@ -573,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;
@@ -809,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 {
@@ -908,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 ||
@@ -915,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.
@@ -1498,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;
@@ -1706,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 a98cb2d93287..eb3f9d93f2bc 100644
--- a/apps/mobile/src/features/threads/ThreadFeed.tsx
+++ b/apps/mobile/src/features/threads/ThreadFeed.tsx
@@ -26,6 +26,7 @@ import { LinkRequestCard } from "./LinkRequestCard";
import { SecretRequestCard } from "./SecretRequestCard";
import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";
import {
+ WorktreePreparingHeader,
WorktreeWorkingHeader,
WorktreeSetupCard,
type WorktreeSetupCardProps,
@@ -96,6 +97,7 @@ import { CHAT_LIST_ANCHOR_OFFSET, resolveChatListAnchoredEndSpace } from "@t3too
import { imageMimeType } from "@t3tools/shared/image";
import { videoMimeType } from "@t3tools/shared/video";
import { SymbolView, type AppSymbolName } from "../../components/ui/AppSymbol";
+import { textDirection } from "@t3tools/shared/textDirection";
import { useFocusEffect, useNavigation } from "@react-navigation/native";
import { useNativeWorkspaceColumnsSupported } from "../../native/NativeWorkspaceColumns";
import { useDeviceType } from "../../native/native-layout-metrics";
@@ -135,6 +137,11 @@ import { assetImageSource } from "../../lib/assetImageSource";
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 +294,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 +327,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;
@@ -480,12 +488,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 +530,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,6 +551,8 @@ 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();
@@ -548,8 +566,15 @@ function MessageAttachmentImage(props: {
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 +618,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 +860,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 +898,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 +916,8 @@ function UserMessageMedia(props: {
rememberSentImage(props.messageId, index, image)}
onPressPreview={props.onPressPreview}
onPlaybackStart={props.onPlaybackStart}
/>
@@ -899,6 +934,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 +1001,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));
@@ -1089,7 +1133,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 +1172,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 +1717,7 @@ function renderFeedEntry(
| "threadId"
| "workspaceRoot"
> & {
+ readonly formatMessageTime: (input: string) => string;
readonly copiedRowId: string | null;
readonly expandedWorkRows: Record;
readonly workRowSizing: ReturnType;
@@ -1907,7 +1963,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("
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 +3096,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 +3173,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 +3401,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,
@@ -3422,7 +3489,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) => {
@@ -3746,6 +3815,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 +3861,8 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
) : props.setupWorkingStartedAt && info.index === setupAnchorIndex ? (
+ ) : props.preparingWorktree && info.index === setupAnchorIndex ? (
+
) : null}
@@ -3887,6 +3959,8 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
{usesNativeAutomaticInsets ? null : }
{setupAnchorIndex < 0 && props.worktreeSetup ? (
+ ) : setupAnchorIndex < 0 && props.preparingWorktree ? (
+
) : null}
{props.historyControls ? (
diff --git a/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx b/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx
index 6aa576f984fc..865cc8d4b6f8 100644
--- a/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx
+++ b/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx
@@ -390,7 +390,6 @@ function ThreadNavigationSidebarPane(props: ThreadNavigationSidebarProps) {
) === props.selectedThreadKey)
}
project={projectByKey.get(pendingScopeKey) ?? null}
- projectTitle={projectTitleByProjectKey.get(pendingScopeKey)}
environmentLabel={
Object.keys(savedConnectionsById).length > 1
? (savedConnectionsById[item.pendingTask.environmentId]?.environmentLabel ?? null)
diff --git a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx
index 0bed5a25f027..4d814d3a8a4f 100644
--- a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx
+++ b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx
@@ -51,6 +51,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";
@@ -95,7 +96,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,
@@ -290,8 +294,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 (
+
+
+
);
}
@@ -859,7 +866,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",
@@ -944,14 +951,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
@@ -962,6 +961,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 = () => (
<>
@@ -977,7 +1000,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 bee63a9775a0..328f56bcf006 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 fb7920dcdd5f..a4f3a306b2eb 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 55028a58b7df..0f83743f99d3 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 6beb9cb6cb01..941a875c9500 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 94f6010acd4a..fa1ab4be779b 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 5624b71c0c91..cfae85e09266 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/thread-inspector-preview.tsx b/apps/mobile/src/features/threads/thread-inspector-preview.tsx
index d41d1f0c7e9b..c2d3a96c34ec 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 69d0c84ecaa8..01bd49b02846 100644
--- a/apps/mobile/src/features/threads/thread-list-v2-items.tsx
+++ b/apps/mobile/src/features/threads/thread-list-v2-items.tsx
@@ -84,6 +84,7 @@ import {
resolveThreadListV2ProviderDrivers,
resolveThreadListV2SwipeActions,
layoutThreadListV2RowMenuActions,
+ threadListV2RowAccessibilityLabel,
type ThreadListV2Status,
} from "./threadListV2";
import { QueuedMessageIcon } from "./queued-message-icon";
@@ -379,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";
@@ -426,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);
@@ -468,7 +467,7 @@ export const ThreadListV2PendingRow = memo(function ThreadListV2PendingRow(props
faviconPath={props.project.faviconPath}
projectIcon={props.project.projectIcon}
size={projectIconSize}
- projectTitle={projectTitle}
+ projectTitle={props.project.title}
workspaceRoot={props.project.workspaceRoot}
/>
@@ -784,8 +783,20 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
: workingLabel) ?? (isUnread ? DONE_STATUS_LABEL : undefined);
const recede = shouldRecedeThreadRow({ status, selected });
const isRegeneratingTitle = thread.titleRegeneration != null;
- const rowAccessibilityLabel = `${thread.title}${providerNameLabel ? `, ${providerNameLabel}` : ""}${props.hasQueuedMessages ? ", messages queued to send" : ""}${isRegeneratingTitle ? ", regenerating title" : ""}`;
const timeLabel = props.timeLabel;
+ const rowAccessibilityLabel = threadListV2RowAccessibilityLabel({
+ title: thread.title,
+ variant,
+ woke: showsWoke,
+ // Working and waiting rows show only an icon and a duration, so name them for speech.
+ statusLabel:
+ statusLabel && (statusLabel.label ?? (status === "waiting" ? "Waiting" : "Working")),
+ timeLabel,
+ snoozeWakeLabel: snoozedRow ? props.snoozeWakeLabelText : undefined,
+ providerNameLabel,
+ hasQueuedMessages: props.hasQueuedMessages === true,
+ regeneratingTitle: isRegeneratingTitle,
+ });
const visitThread = useAtomCommand(threadEnvironment.visit, { reportFailure: false });
const handleAcknowledgeWoke = useCallback(() => {
@@ -1581,7 +1592,12 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
threadTitle={thread.title}
>
{(close) => (
-